diff --git "a/4417.jsonl" "b/4417.jsonl" new file mode 100644--- /dev/null +++ "b/4417.jsonl" @@ -0,0 +1,736 @@ +{"seq_id":"277949980","text":"#!/usr/bin/python\n# LSST Data Management System\n# Copyright 2014 LSST Corporation.\n#\n# This product includes software developed by the\n# LSST Project (http://www.lsst.org/).\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the LSST License Statement and\n# the GNU General Public License along with this program. If not,\n# see .\n#\n# convertVocab.py converts ANTLRv2 token vocabularies to c++ header files\nfrom __future__ import print_function\nfrom itertools import chain\nfrom optparse import OptionParser\nimport hashlib\nimport os\nimport subprocess\nimport sys\n\nfrom string import digits\ntry:\n from string import ascii_letters\nexcept ImportError:\n from string import letters as ascii_letters\n\nsample = \"\"\"// $ANTLR 2.7.2\nSqlSQL2Imp // input token vocab name\nSQL2NRW_ada=\"ada\"=5\nSQL2NRW_c=\"c\"=6\nSQL2NRW_catalog_name=\"catalog_name\"=7\nSQL2NRW_character_set_catalog=\"character_set_catalog\"=8\nSQL2NRW_character_set_name=\"character_set_name\"=9\nSQL2NRW_character_set_schema=\"character_set_schema\"=10\nSQL2NRW_class_origin=\"class_origin\"=11\nSQL2NRW_cobol=\"cobol\"=12\nSQL2NRW_collation_catalog=\"collation_catalog\"=13\nSQL2RW_drop=\"drop\"=126\nSQL2RW_immediate=\"immediate\"=156\nSQL2RW_in=\"in\"=157\nSQL2RW_indicator=\"indicator\"=158\nSQL2RW_view=\"view\"=273\nSQL2RW_when=\"when\"=274\nSQL2RW_whenever=\"whenever\"=275\nSQL2RW_where=\"where\"=276\nSQL2RW_with=\"with\"=277\nSQL2RW_work=\"work\"=278\nSQL2RW_write=\"write\"=279\nSQL2RW_year=\"year\"=280\nSQL2RW_zone=\"zone\"=281\nUNSIGNED_INTEGER(\"an integer number\")=282 // Imaginary token based on subtoken typecasting - see the rule \nAPPROXIMATE_NUM_LIT(\"a number\")=283 // Imaginary token based on subtoken typecasting - see the rule \nQUOTE(\"'\")=284 // Imaginary token based on subtoken typecasting - see the rule \nPERIOD(\".\")=285 // Imaginary token based on subtoken typecasting - see the rule \nMINUS_SIGN(\"-\")=286 // Imaginary token based on subtoken typecasting - see the rule \")=289 // Imaginary token based on subtoken typecasting - see the rule \nLESS_THAN_OR_EQUALS_OP(\"<=\")=290 // Imaginary token based on subtoken typecasting - see the rule \nGREATER_THAN_OR_EQUALS_OP(\">=\")=291 // Imaginary token based on subtoken typecasting - see the rule \nCONCATENATION_OP(\"||\")=292 // Imaginary token based on subtoken typecasting\n\"\"\"\n# {0} header filename\n# {1} token ident\nsampleCC = \"\"\"\n#include \"{0}\"\n\nint main(int argc, char** argv) {{\n int catalogtoken = {1}::SQL2NRW_catalog_name;\n char const* quote = {1}::toString({1}::QUOTE);\n return 0;\n}}\n\"\"\"\n\n\ndef splitEq(line):\n # Consider writing with a regex.\n clean = line.strip()\n # remove comment\n commentLoc = clean.find(\"//\")\n if commentLoc != -1:\n clean = clean[:commentLoc]\n # split by equals sign\n lefteq = clean.find(\"=\")\n righteq = clean.rfind(\"=\")\n if \"(\" in clean[:lefteq]: # If there is a paren ( FOO(\"foo\")=3423 format)\n # Make sure the closing paren is also in there.\n if \")\" not in clean[:lefteq]:\n # if not, advance to closing paren and look for equals from there.\n lefteq = clean.find(\"=\", clean.find(\")\"))\n if lefteq == -1:\n return ()\n if lefteq == righteq:\n return (clean[:lefteq], clean[lefteq+1:])\n else:\n return (clean[:lefteq], clean[lefteq+1:righteq], clean[righteq+1:])\n\n\ndef stripQuotes(s):\n if s[0] == s[-1] and s[0] in ['\"', \"'\"]:\n return s[1:-1]\n return s\n\n\nclass NoValueError(ValueError):\n\n def __init__(self, descr):\n super(NoValueError, self).__init__(descr)\n pass\n\n\n# Mimic ANTLR 2.7 generated header format.\n# {0} sanitized filename\n# {1} source filename\n# {2} this file ( __file__ )\n# {3} struct name\n# {4} 8-space indented definitions\n# {5} 12-space indented descriptions\n# (braces \"{}\" are doubled to escape them in Python's string formatter)\ncppTemplate = \"\"\"#ifndef INC_{0}\n#define INC_{0}\n/* Computed from {1} using {2} */\nstruct {3} {{\n enum {{\n{4}\n }};\n static char const* toString(int n) {{\n switch(n) {{\n{5}\n default: return 0;\n }}\n}}\n}};\n\n#endif /* INC_{0} */\n\"\"\"\nenumTemplate = \"{0} = {1}\"\ncaseTemplate = \"case {0}: return \\\"{1}\\\";\"\n\n\nclass Vocabulary:\n \"\"\"Vocabulary is an object that bundles a ANTLRv2 token vocabulary.\nIt consists of an identifier, some textual description or representation,\nand an integer tokenid.\nSee: http://www.antlr2.org/doc/vocab.html\n\"\"\"\n\n def __init__(self):\n self.tokens = []\n self.legalIdent = set(chain(ascii_letters, digits, [\"_\"]))\n self.legalFirst = set(chain(ascii_letters, [\"_\"]))\n self.sourceFile = \"undefined\"\n\n def importBuffer(self, text):\n \"\"\"Import a text buffer into the vocabulary\"\"\"\n for line in text.split(\"\\n\"):\n if not line:\n continue\n try:\n self.tokens.append(Token(line))\n except NoValueError as e:\n # print e.message\n print(\"ignoring\", line)\n pass\n pass\n\n def importFile(self, filename):\n \"\"\"Import the contents of a file into the vocabulary and remember the\nsource file name\"\"\"\n self.sourceFile = self.sanitizeIdent(os.path.basename(filename))\n self.importBuffer(open(filename).read())\n\n def exportCppHeader(self, targetFile=None):\n \"\"\"Export the current vocabulary as a C++ header file\"\"\"\n # {0} sanitized filename\n # {1} source filename\n # {2} this file ( __file__ )\n # {3} struct name\n # {4} 8-space indented definitions\n # {5} 8-space indented descriptions\n filename = \"tokens_h\"\n sourceFilename = self.sourceFile\n structName = \"tokens\"\n if targetFile:\n basename = os.path.basename(targetFile)\n filename = self.sanitizeIdent(basename)\n structName = self.sanitizeIdent(os.path.splitext(basename)[0])\n enums = \",\\n\".join(s.toEnum() for s in self.tokens)\n cases = \"\\n\".join(s.toCase() for s in self.tokens)\n return cppTemplate.format(filename, sourceFilename, __file__,\n structName, enums, cases)\n\n def sanitizeIdent(self, raw):\n \"\"\"Sanitize an identifier by converting illegal characters to underscores\nand prefixing with 'x' if the first character is still not legal.\"\"\"\n def makeLegal(ch):\n if ch not in self.legalIdent:\n return \"_\"\n else:\n return ch\n sanitized = [makeLegal(l) for l in raw]\n if sanitized[0] not in self.legalFirst:\n sanitized = [\"x\"] + sanitized\n return \"\".join(sanitized)\n\n pass\n\n\nclass Token:\n \"\"\"A Token object represents an entry in an ANTLR vocabulary\"\"\"\n\n def __init__(self, line):\n t = splitEq(line)\n if not t:\n raise NoValueError(\"No token definition in: [%s]\" % line.strip())\n ident = t[0]\n tokenid = t[-1]\n descr = None\n if len(t) == 2: # like: MINUS_SIGN(\"-\")=286 // Imaginary token based on\n # look for parens\n lparen = t[0].find(\"(\")\n rparen = t[0].rfind(\")\")\n if lparen == -1:\n raise RuntimeError('Expected Foo(\"foo\")=1234, got' + line)\n\n descr = stripQuotes(t[0][lparen+1:rparen])\n ident = t[0][:lparen]\n pass\n elif len(t) == 3: # like: SQL2RW_zone=\"zone\"=281\n # strip quotes from descr\n descr = stripQuotes(t[1])\n else:\n pass\n self.ident = ident\n self.descr = descr\n self.tokenid = int(tokenid)\n # print \"ident\",ident,\"descr\",descr,\"tokenid\",tokenid\n pass\n\n def toEnum(self, indent=\" \"):\n return indent + enumTemplate.format(self.ident, self.tokenid)\n\n def toCase(self, indent=\" \"):\n return indent + caseTemplate.format(self.ident, self.descr)\n\n\ndef debugTest():\n v = Vocabulary()\n v.importBuffer(sample)\n print(v.exportCppHeader(\"SomeTokens.h\"))\n\n\nclass UnitTest:\n \"\"\"Unit test this module by exercising the conversion over sample token data\n and ensuring that the result can be compiled in g++\"\"\"\n\n def __init__(self):\n # Make a probably-unique digest from: userid + __file__ + pid\n m = hashlib.md5()\n m.update(str(os.getuid()))\n m.update(__file__)\n # m.update(str(os.getpid()))\n digest = m.hexdigest()\n v = Vocabulary()\n self.digest = v.sanitizeIdent(digest)\n # Decide on some pathnames\n self.inputTokenFile = os.path.join(\"/tmp\", self.digest + \".txt\")\n self.outputHeaderFile = os.path.join(\"/tmp\", self.digest + \"gen.h\")\n self.ccFile = os.path.join(\"/tmp\", self.digest + \"test.cc\")\n self.progFile = os.path.splitext(self.ccFile)[0]\n self.testFiles = [self.inputTokenFile, self.outputHeaderFile,\n self.ccFile, self.progFile]\n\n def writeFiles(self):\n # Write the sample files\n open(self.inputTokenFile, \"w\").write(sample)\n m = Main()\n m.convertFile(self.inputTokenFile, self.outputHeaderFile)\n\n # Compute a test .cc file and write it\n ccTest = sampleCC.format(self.outputHeaderFile, self.digest+\"gen_h\")\n\n open(self.ccFile, \"w\").write(sampleCC.format(self.outputHeaderFile,\n self.digest+\"gen\"))\n\n def compile(self):\n # Try compiling\n progFile = os.path.splitext(self.ccFile)[0]\n\n try:\n retcode = subprocess.call(\" \".join([\"g++\", \"-o\",\n self.progFile, self.ccFile]),\n shell=True)\n if retcode < 0:\n print(\"Test failed: terminated by signal\", -retcode, file=sys.stderr)\n else:\n if retcode == 0:\n print(\"Test success\", file=sys.stderr)\n # Cleanup\n for f in self.testFiles:\n os.remove(f)\n else:\n print(\"Compilation failure: g++ returned\", retcode, file=sys.stderr)\n print(\"Test files:\", \" \".join(self.testFiles))\n\n except OSError as e:\n print(\"Execution failed:\", e, file=sys.stderr)\n pass\n\n def run(self):\n self.writeFiles()\n self.compile()\n\n\nclass Main:\n\n def __init__(self):\n usage = \"usage: %prog [options] \"\n op = OptionParser(usage=usage)\n op.add_option(\"-t\", \"--test\", action=\"store_true\", dest=\"testOnly\",\n default=False, help=\"run debug test (default: don't test)\")\n op.add_option(\"-u\", \"--unittest\", action=\"store_true\", dest=\"unitTest\",\n default=False, help=\"run unit test (generate and compile)\")\n\n self.oParser = op\n pass\n\n def convertFile(self, tokenFile, headerFile):\n v = Vocabulary()\n v.importFile(tokenFile)\n open(headerFile, \"w\").write(v.exportCppHeader(headerFile))\n\n def run(self):\n (options, args) = self.oParser.parse_args()\n if options.testOnly:\n debugTest()\n return\n elif options.unitTest:\n u = UnitTest()\n u.run()\n return\n else:\n if len(args) != 2:\n self.oParser.print_help()\n return\n self.convertFile(args[0], args[1])\n\n\nif __name__ == \"__main__\":\n # debugTest()\n m = Main()\n m.run()\n","sub_path":"site_scons/convertVocab.py","file_name":"convertVocab.py","file_ext":"py","file_size_in_byte":12124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"596484982","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import expon #SUBSTITUIDA PELA dist_exponencial_pdf\n# Distribuição\nmu = 0 # Média\nlambda1 = 2.0 # Desvio padrâo\nlambda2 = 5.0\nT=0.001 # Taxa de amostragem\nx=np.arange(0,30+T,T) # Eixo x \n\ndef dist_exponencial_pdf(x,lbd):\n return lbd*np.exp(-lbd*x)\n\n\nDistExpo1=dist_exponencial_pdf(x,lambda1) # Distribuição exponencial\nDistExpo2=dist_exponencial_pdf(x,lambda2) # Distribuição exponencial \n\n# Cálculo da probabilidade\nlimite_direito1 = np.max(np.where(x>3))\nlimite_direito2 = np.max(np.where(x>3))\nlimite_esquerdo1 = np.max(np.where(x<3))\nlimite_esquerdo2 = np.max(np.where(x<3))\n\n#limite_direito = np.min(np.where(x>sigma))\nindices1 = np.arange(limite_esquerdo1+1,limite_direito1)\n#indices1 = np.arange(limite_direito1)\nindices2 = np.arange(limite_esquerdo2+1,limite_direito2)\n\n\nprob11=np.sum(DistExpo1[indices1])*T*100 # Probabilidade de um evento ocorrer no intervalo\nprob12=np.sum(DistExpo2[indices2])*T*100 # Probabilidade de um evento ocorrer no intervalo\n\nplt.figure(1,[8,6])\nplt.plot(x,DistExpo1,'k') \nplt.title('Probabilidade de = ' + str(prob11)) # Mostra valor verdadeiro de prob1\nplt.fill_between(x[indices1],DistExpo1[indices1],facecolor='midnightblue')\n\nplt.figure(2,[8,6])\nplt.plot(x,DistExpo2,'k') \nplt.title('Probabilidade de = ' + str(prob12)) # Mostra valor verdadeiro de prob1\nplt.fill_between(x[indices2],DistExpo2[indices2],facecolor='midnightblue')\n\nplt.show()\n\n# calculando diretamente da integral\nimport sympy as ss\nss.init_printing(use_unicode=False, wrap_line=False, no_global=True)\na1,f1 = ss.symbols('a1,f1')\nlambda1 = 2.0 # Desvio padrâo\nlambda2 = 5.0\nf1 = lambda1*ss.exp(-lambda1*a1)\nprob21 = ss.integrate(f1, (a1,3,30))\na2,f2 = ss.symbols('a2,f2')\nf2 = lambda2*ss.exp(-lambda2*a2)\nprob22 = ss.integrate(f2, (a2,3,30))\nprint(\"Probabilidade pela integral da fórmula da PDF para lambda 2 = \"+str(prob11)+\" %\")\nprint('Probabilidade pela área da PDF para lambda 2 ={} %'.format(prob21*100))\nprint(\"Probabilidade pela integral da fórmula da PDF para lambda 5 = \"+str(prob12)+\" %\")\nprint('Probabilidade pela área da PDF para lambda 5 ={} %'.format(prob22*100))\n","sub_path":"HandsOn03/handson3pyteste.py","file_name":"handson3pyteste.py","file_ext":"py","file_size_in_byte":2461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"319730309","text":"#\n# Copyright (c) 2015, Adel Noureddine\n# All rights reserved.\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of the nor the\n# names of its contributors may be used to endorse or promote products\n# derived from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 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# Author : Adel Noureddine\n#\n\nimport sys\n#directory = sys.argv[1]\nfileToRead = sys.argv[1]\n#fileToRead = directory + \"/sm-cabs.txt\"\nfileToWrite = fileToRead + \".csv\"\nf = open(fileToRead)\ncf = open(fileToWrite, \"w\")\nprogramVolume = 0\nprogramDifficulty = 0\nfor line in f:\n line = line.strip()\n parts = line.split(\":\")\n if len(parts) > 1:\n name = parts[0]\n value = parts[1]\n if name == \"Total operators\":\n cf.write(name + \";\" + value.strip() + \"\\n\")\n elif name == \"Distinct operators\":\n cf.write(name + \";\" + value.strip() + \"\\n\")\n elif name == \"Total_operands\":\n cf.write(\"Total operands;\" + value.strip() + \"\\n\")\n elif name == \"Distinct operands\":\n cf.write(name + \";\" + value.strip() + \"\\n\")\n elif name == \"Program length\":\n cf.write(name + \";\" + value.strip() + \"\\n\")\n elif name == \"Vocabulary size\":\n cf.write(name + \";\" + value.strip() + \"\\n\")\n elif name == \"Program volume\":\n cf.write(name + \";\" + value.strip() + \"\\n\")\n programVolume = value.strip()\n elif name == \"Effort\":\n cf.write(name + \";\" + value.strip() + \"\\n\")\n elif name == \"Program level\":\n cf.write(name + \";\" + value.strip() + \"\\n\")\n elif name == \"Difficulty level\":\n cf.write(name + \";\" + value.strip() + \"\\n\")\n programDifficulty = value.strip()\n elif name == \"Time to implement\":\n cf.write(name + \";\" + value.strip() + \"\\n\")\n elif name == \"Bugs delivered\":\n cf.write(name + \";\" + value.strip() + \"\\n\")\nprogramIntelligentContent = float(programVolume) / float(programDifficulty)\ncf.write(\"Intelligent Content;\" + str(programIntelligentContent))\ncf.close()\nf.close()","sub_path":"frama-c/processCabs.py","file_name":"processCabs.py","file_ext":"py","file_size_in_byte":3344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"381604391","text":"\"\"\"\n@author - Mohsin\n\"\"\"\nimport numpy as np\n\nnp.random.seed(786) # for reproducibility\nimport pandas as pd\nfrom sklearn.model_selection import KFold, cross_val_predict\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import LabelEncoder\nfrom scipy.sparse import load_npz, hstack\nfrom tqdm import tqdm\nimport lightgbm as lgb\n\ntqdm.pandas(tqdm)\n\nfrom TargetEncoder import TargetEncoder\nfrom ContinousBinning import ContinousBinning\nfrom utils import *\nimport logging\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\ndef cv_oof_predictions(estimator, X, y, cvlist, est_kwargs, fit_params, predict_test=False, X_test=None, ):\n preds = np.zeros(len(y)) # Initialize empty array to hold prediction\n test_preds = []\n for tr_index, val_index in cvlist:\n gc.collect()\n X_tr, X_val = X[tr_index], X[val_index]\n y_tr, y_val = y[tr_index], y[val_index]\n est = estimator.set_params(**est_kwargs)\n # print(X_tr.shape, X_val.shape, y_tr.shape, y_val.shape)\n est.fit(X_tr, y_tr, eval_set=[(X_tr, y_tr), (X_val, y_val)], eval_metric='rmse',\n early_stopping_rounds=50, verbose=200, **fit_params) # Might need to change this depending on estimator\n val_preds = est.predict(X_val)\n\n preds[val_index] = val_preds\n if predict_test:\n tpreds = est.predict(X_test)\n test_preds.append(tpreds)\n break\n if len(test_preds) > 0:\n test_preds = np.mean(test_preds, axis=0)\n return est, preds, test_preds #est, y_val, val_preds #\n\n\nif __name__ == \"__main__\":\n LOGGER_FILE = \"lgbBaseChecker_v1.log\"\n MODEL_ID = \"cleanedv3_iter1\"\n NFOLDS=5\n CONT_COLS = ['price', 'item_seq_number', 'user_id_counts', 'price_binned']\n\n BASE_FEATURES = ['region_lbenc_2', 'city_lbenc_2', 'parent_category_name_lbenc_2',\n 'category_name_lbenc_2', 'param_1_lbenc_2', 'param_2_lbenc_2', 'param_3_lbenc_2',\n 'image_top_1_lbenc_2', 'user_type_lbenc_2', 'user_id_trenc_3', 'city_trenc_3',\n 'parent_category_name_trenc_3', 'param_1_trenc_3', 'param_2_trenc_3', 'param_3_trenc_3',\n 'image_top_1_trenc_3', 'region_parent_category_name_trenc_8', 'region_param_2_trenc_8',\n 'region_param_3_trenc_8', 'region_image_top_1_trenc_8', 'city_parent_category_name_trenc_8',\n 'city_category_name_trenc_8', 'city_param_1_trenc_8', 'city_param_3_trenc_8',\n 'parent_category_name_param_2_trenc_8', 'parent_category_name_param_3_trenc_8',\n 'parent_category_name_image_top_1_trenc_8', 'parent_category_name_user_type_trenc_8',\n 'category_name_param_1_trenc_8', 'category_name_image_top_1_trenc_8',\n 'param_1_image_top_1_trenc_8', 'param_2_image_top_1_trenc_8',\n 'user_type_region_category_name_param_1_trenc_8',\n 'user_type_city_category_name_param_1_trenc_8']\n\n PRICE_COMB_COLS = [\n 'price_binned_param_2_trenc_5'\n ]\n\n PRICE_MEAN_COLS = [\n 'category_name_priceenc_5', 'param_1_priceenc_5', 'param_2_priceenc_5',\n 'param_3_priceenc_5', 'image_top_1_priceenc_5'\n ]\n\n COUNT_COLS = ['param_1_counts', 'user_type_counts', 'param_1_user_type_activation_date_counts',\n 'param_2_user_type_activation_date_counts',\n 'region_param_1_user_type_activation_date_counts',\n 'city_category_name_param_1_user_type_counts',\n 'city_category_name_param_2_user_type_counts']\n\n IMAGE_FEATS = ['image1_image_isna', 'image1_ar', 'image1_height',\n 'image1_width', 'image1_average_pixel_width',\n 'image1_average_red', 'image1_dominant_red',\n 'image1_whiteness', 'image1_dominant_green',\n 'image1_average_green', 'image1_blurrness',\n 'image1_size', 'image1_dullness', 'image1_average_blue']\n\n GIBA_FEATS = ['giba1_nchar_title', 'giba1_nchar_desc', 'giba1_titl_capE', 'giba1_titl_capR',\n 'giba1_titl_lowE', 'giba1_titl_lowR', 'giba1_titl_pun', 'giba1_desc_pun', 'giba1_titl_dig',\n 'giba1_desc_dig', 'giba1_wday', 'giba1_ce1', 'giba1_ce2', 'giba1_ce3', 'giba1_ce4', 'giba1_ce6', 'giba1_ce7',\n 'giba1_ce8', 'giba1_ce9', 'giba1_ce10', 'giba1_ce11', 'giba1_ce12', 'giba1_ce13', 'giba1_ce14', 'giba1_ce15',\n 'giba1_ce16', 'giba1_ce17', 'giba1_ce18', 'giba1_dif_time1', 'giba1_dif_isn1', 'giba1_mflag1',\n 'giba1_dif_time2', 'giba1_dif_time3', 'giba1_dif_time4', 'giba1_dif_time5', 'giba1_dif_time6',\n 'giba1_N1', 'giba1_N2', 'giba1_N3', 'giba1_N4', 'giba1_N5', 'giba1_N6', 'giba1_image1', 'giba1_image2', 'giba1_image3',\n 'giba1_image4', 'giba1_image5', 'giba1_image6', 'giba1_rev_seq']\n\n IMAGE3_FEATS = ['image3_br_std', 'image3_br_min', 'image3_sat_avg', 'image3_lum_mean',\n 'image3_lum_std', 'image3_lum_min', 'image3_contrast',\n 'image3_CF', 'image3_kp', 'image3_dominant_color',\n 'image3_dominant_color_ratio', 'image3_simplicity', 'image3_object_ratio']\n\n TEXT_STATS = ['title_num_emojis',\n 'title_word_len_ratio', 'title_digits_len_ratio',\n 'title_caps_len_ratio', 'title_punct_len_ratio', 'desc_num_words',\n 'desc_unq_words', 'desc_num_digits', 'desc_num_emojis',\n 'desc_word_len_ratio',\n 'desc_digits_len_ratio', 'desc_caps_len_ratio',\n 'title_num_words', 'title_unq_words', 'title_desc_word_ratio']\n EXTRA_FEATS = ['inception_v3_prob_0', 'xception_prob_0', 'resnet50_prob_0',\n 'avg_days_up_user', 'std_days_up_user', 'avg_times_up_user', 'std_times_up_user',\n 'n_user_items', 'agg_isnull', 'inception_v3_label_0', 'xception_label_0', 'resnet50_label_0']\n\n EXTRA_FEATS2 = [\"pcat_p123_deal_nunq\", \"cat_p123_deal_nunq\", \"city_p123_deal_nunq\",\n \"region_p123_deal_nunq\"]\n\n TEXT_PREDS = [\"title_ridge_comb0\", \"title_lgb_comb0\", \"description_ridge_comb1\", \"description_ridge_comb0\"]\n CAT_PREDS = [\"lgbcats_0\", \"lgbcats_1\"]\n\n #SURR_FEATS = [\"param2_pred_labels\"]\n\n TITLE_COMB = 1\n DESC_COMB = 1\n\n LGB_PARAMS1 = {\n \"n_estimators\":15000,\n 'learning_rate': 0.01,\n \"num_leaves\": 255,\n \"colsample_bytree\": 0.4,\n \"subsample\": 0.8,\n \"reg_alpha\": 0,\n \"reg_lambda\": 5,\n \"min_data_in_leaf\": 200,\n \"max_bin\": 512,\n \"verbose\":0\n }\n\n ###################### Logger #########################################\n handler = logging.FileHandler(LOGGER_FILE)\n handler.setLevel(logging.INFO)\n\n # create a logging format\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n handler.setFormatter(formatter)\n\n logger.addHandler(handler)\n\n ###################### Read data ##########################################\n logger.info(\"Reading data\")\n train = pd.read_csv(\"../input/train.csv\", parse_dates=['activation_date'])\n test = pd.read_csv(\"../input/test.csv\", parse_dates=['activation_date'])\n test['deal_probability'] = -1\n\n # City correction\n for df in train, test:\n df['city'] = df['region'].astype(str) + \"_\" + df[\"city\"].astype(str)\n df[\"param_1_2_3\"] = df[\"param_1\"].astype(str) + \" \" + \\\n df[\"param_2\"].astype(str) + \" \" + \\\n df[\"param_3\"].astype(str)\n df = df.fillna(-1)\n\n y = train['deal_probability'].values\n cvlist = list(KFold(NFOLDS, random_state=123).split(y))\n cvlist2 = list(KFold(NFOLDS, random_state=123).split(y[:100000]))\n logger.info(\"Done. Read data with shape {} and {}\".format(train.shape, test.shape))\n #del train, test\n\n ################### Process and load features #######################################\n logger.info(\"Loading text features\")\n X_title = load_npz(\"../utility/X_train_title_{}.npz\".format(TITLE_COMB))\n X_title_test = load_npz(\"../utility/X_test_title_{}.npz\".format(TITLE_COMB))\n\n X_desc = load_npz(\"../utility/X_train_description_{}.npz\".format(DESC_COMB))\n X_desc_test = load_npz(\"../utility/X_test_description_{}.npz\".format(DESC_COMB))\n\n features = BASE_FEATURES + CONT_COLS + PRICE_COMB_COLS + PRICE_MEAN_COLS + COUNT_COLS + IMAGE_FEATS + GIBA_FEATS + \\\n IMAGE3_FEATS + TEXT_STATS + EXTRA_FEATS + EXTRA_FEATS2 + TEXT_PREDS + CAT_PREDS\n X_cats = np.vstack([np.load(\"../utility/X_train_{}.npy\".format(col), mmap_mode='r') for col in features]).T\n X_cats_test = np.vstack([np.load(\"../utility/X_test_{}.npy\".format(col), mmap_mode='r') for col in features]).T\n\n train[\"cat_enc\"] = np.load(\"../utility/X_train_category_name_lbenc_1.npy\")\n test[\"cat_enc\"] = np.load(\"../utility/X_test_category_name_lbenc_1.npy\")\n image_top_1_cat = pd.concat([train, test]).groupby(\"image_top_1\")[\"cat_enc\"].apply(lambda x: x.mode())\n X_imaget1_cat = train[\"image_top_1\"].map(image_top_1_cat).values.reshape(-1,1)\n X_imaget1_cat_test = test[\"image_top_1\"].map(image_top_1_cat).values.reshape((-1,1))\n #pipe = make_pipeline(TfidfVectorizer(ngram_range=(1,1), max_features=100000),\n # TruncatedSVD(20))\n #X_tsvd = pipe.fit_transform(train[\"description\"].astype(str))\n #X_tsvd_test = pipe.transform(test[\"description\"].astype(str))\n lbenc = LabelEncoder()\n train[\"deal_label\"] = ContinousBinning(bin_array=[-1, 0.05, 0.4, 0.7, 1.1]).fit_transform(train[\"deal_probability\"])\n train[\"deal_label\"] = LabelEncoder().fit_transform(train[\"deal_label\"])\n\n cat_deal_count = TargetEncoder(cols=[\"category_name\"], targetcol=\"deal_label\", func=np.bincount)\n X_cat_bins = cross_val_predict(cat_deal_count, train, y=train[\"deal_probability\"], cv=cvlist,\n method=\"transform\") / int((1 - 1 / NFOLDS) * len(train))\n X_cat_bins = [arr.tolist() if len(arr) == 4 else [0,0,0,0] for arr in X_cat_bins]\n X_cat_bins = np.vstack(X_cat_bins)\n\n X_cat_bins_test = cat_deal_count.fit(train).transform(test) / len(train)\n X_cat_bins_test = [arr.tolist() if len(arr) == 4 else [0,0,0,0] for arr in X_cat_bins_test]\n X_cat_bins_test = np.vstack(X_cat_bins_test)\n\n imt_deal_count = TargetEncoder(cols=[\"image_top_1\"], targetcol=\"deal_label\", func=np.bincount)\n X_imt_bins = cross_val_predict(imt_deal_count, train, y=train[\"deal_probability\"], cv=cvlist,\n method=\"transform\") / int((1 - 1 / NFOLDS) * len(train))\n X_imt_bins = [arr.tolist() if (type(arr) == list) and (len(arr) == 4) else [0,0,0,0] for arr in X_imt_bins]\n X_imt_bins = np.vstack(X_imt_bins)\n\n X_imt_bins_test = imt_deal_count.fit(train).transform(test) / len(train)\n X_imt_bins_test = [arr.tolist() if (type(arr) == list) and (len(arr) == 4) else [0,0,0,0] for arr in X_imt_bins_test]\n X_imt_bins_test = np.vstack(X_imt_bins_test)\n\n #imt_deal_count = TargetEncoder(cols=[\"image_top_1\"], targetcol= \"deal_label\", func=np.bincount)\n #X_imt_bins = cross_val_predict(imt_deal_count, train, y=train[\"deal_probability\"], cv=cvlist,\n # method=\"transform\") / int((1 - 1 / 5) * len(train))\n #X_imt_bins_test = imt_deal_count.fit(train).transform(test) / len(train)\n\n logger.info(\"Stack all features\")\n X = hstack((X_cats, X_title, X_desc, X_imaget1_cat, X_cat_bins, X_imt_bins)).tocsr()\n X_test = hstack((X_cats_test, X_title_test, X_desc_test, X_imaget1_cat_test, X_cat_bins_test, X_imt_bins_test)).tocsr()\n logger.info(\"Shape for base dataset is {} and {}\".format(X.shape, X_test.shape))\n ################### Run LGB ######################\n #\n feature_names = BASE_FEATURES + CONT_COLS + PRICE_COMB_COLS + PRICE_MEAN_COLS + COUNT_COLS + IMAGE_FEATS + GIBA_FEATS + \\\n IMAGE3_FEATS + TEXT_STATS + EXTRA_FEATS + EXTRA_FEATS2 + TEXT_PREDS + CAT_PREDS + \\\n [\"title_tfidf_\"+str(i) for i in range(X_title.shape[1])] + \\\n [\"desc_tfidf_\" + str(i) for i in range(X_desc.shape[1])]\n\n categorical_features = ['region_lbenc_2', 'city_lbenc_2', 'parent_category_name_lbenc_2',\n 'category_name_lbenc_2', 'param_1_lbenc_2', 'param_2_lbenc_2', 'param_3_lbenc_2',\n 'image_top_1_lbenc_2', 'user_type_lbenc_2', 'inception_v3_label_0', 'xception_label_0',\n 'resnet50_label_0', \"image3_dominant_color\", \"price_binned\"]\n\n model = lgb.LGBMRegressor()\n est, y_preds_lgb, y_test_lgb = cv_oof_predictions(model, X[:100000], y[:100000], cvlist2, LGB_PARAMS1, predict_test=True,\n X_test=X_test,\n #fit_params={\"feature_name\": feature_names,\n # \"categorical_feature\": categorical_features}\n fit_params={})\n best_rmse_lgb_base = rmse(y, y_preds_lgb)\n logger.info(\"Best score for base cols in {}\".format(best_rmse_lgb_base))\n\n logger.info(\"Saving predicitions\")\n np.save(\"../utility/X_train_lgb_{}.npy\".format(MODEL_ID), y_preds_lgb)\n np.save(\"../utility/X_test_lgb_{}.npy\".format(MODEL_ID), y_test_lgb)\n\n logger.info(\"Writing out submissions\")\n sub = pd.read_csv(\"../input/sample_submission.csv\")\n sub['deal_probability'] = np.clip(y_test_lgb, 0, 1)\n sub['deal_probability'] = sub['deal_probability'].clip(0, 1)\n sub.to_csv(\"../outputs/sub_lgb_{}.csv\".format(MODEL_ID), index=False)\n\n\n handler.close()\n logger.removeHandler(handler)\n","sub_path":"lgbBaseChecker_v3.py","file_name":"lgbBaseChecker_v3.py","file_ext":"py","file_size_in_byte":13932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"46373298","text":"\n\n\n\nimport spider_c.spider_modules.job as job\nimport spider_c.spider_modules.name_manager as nm\nimport spider_c.spider_modules.standard_spider_back as ss\nimport re\nfrom bs4 import BeautifulSoup\nimport requests\nimport math\nimport time\nimport random\n\n\ndef get_html(url):\n data = requests.get(url)\n data.encoding = 'utf-8'\n datatext = data.text\n data.close()\n time.sleep(5 * random.random())\n return datatext\n\n\n\nclass first(ss.ThreadingSpider):\n\n def get(self,url):\n url = \"http://www.freepatentsonline.com/featured/patentclasses.html\"\n urls=[]\n html = get_html(url)\n\n soup = BeautifulSoup(html, \"html.parser\")\n table_tag = soup.find(\"table\", class_=\"listing_table\")\n for a_tag in table_tag.find_all(\"a\"):\n urls.append(\"http://www.freepatentsonline.com\" + a_tag[\"href\"])\n\n return urls\n\nclass second(ss.ThreadingSpider):\n\n def get(self,url):\n html = get_html(url)\n urls = []\n soup = BeautifulSoup(html, \"html.parser\")\n table_tag = soup.find(\"div\", class_=\"well well-small\")\n td = table_tag.find(\"td\", width=\"36%\")\n tstr = td.get_text()\n num = re.search(\"of\", tstr).span()\n print(tstr[num[1]:])\n\n s = math.ceil(int(tstr[num[1]:]) / 50)\n if s > 200:\n s = 200\n s = s - 1\n\n urls.append(\"http://www.freepatentsonline.com/CCL-367.html\")\n for i in range(s):\n urls.append(\"http://www.freepatentsonline.com/CCL-367-p\" + str(i + 2) + \".html\")\n return urls\n\nclass thrid(ss.ThreadingSpider):\n def get(self,url):\n html = get_html(url)\n urls = []\n soup = BeautifulSoup(html, \"html.parser\")\n div_tag = soup.find(\"div\", class_=\"container_white\")\n for a_tag in div_tag.find_all(\"a\"):\n urls.append(\"http://www.freepatentsonline.com\" + a_tag[\"href\"])\n return urls\nclass four(ss.ThreadingSpider):\n def get(self,url):\n html = get_html(url)\n text = \"\"\n soup = BeautifulSoup(html, \"html.parser\")\n for div in soup.find_all(\"div\", class_=\"disp_doc2\"):\n\n if div.find(\"div\", class_=\"disp_elm_title\"):\n dtitle = div.find(\"div\", class_=\"disp_elm_title\").get_text()\n if dtitle:\n line = div.get_text().strip().replace(\"\\n\", \"\")\n text = text + line + \"$$$$\"\n\n self.file.write(url+\"$$$$\"+text[:-4]+\"\\n\")\n\n\nif __name__ == '__main__':\n file_path = \"C:/file/ResultFile/fpo_spider_result.txt\"\n f = open(file_path, \"a+\",encoding=\"utf-8\")\n names = nm.Name_Manager(\"fpo\", 4)\n j = job.Job(f)\n\n\n fi=first(names)\n se=second(names)\n th=thrid(names)\n fo=four(names)\n j.start(names, fi,se,th,fo)\n\n\n\n\n","sub_path":"spider/spider_thread/fpo.py","file_name":"fpo.py","file_ext":"py","file_size_in_byte":2754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"372424152","text":"# -*- coding: utf-8 -*-\n\n__author__ = 'foresterd'\n__date__ = '9 May 2017'\n\n'''\nTakes in a raw image from a Pyxis micro-grid linear polarimeter, returns a Stokes\nproduct image or one of the polarizer 'channel' images (0-deg, 90-deg, 45-deg, 135-deg)\ninput: uint16 2d Numpy array\noutput: uint8 2d Numpy array\n'''\n\nimport numpy as np\nfrom skimage.transform import warp, AffineTransform, resize\nfrom scipy.ndimage.interpolation import shift\nfrom scipy.misc import bytescale\n\ndef get_image(in_image, out_image='dolp'):\n\n # dimensions of the input image\n imgH, imgW = in_image.shape\n # dimensions of each of the 4 channel images\n r, c = (int(imgH/2), int(imgW/2))\n\n # fdata is a flattened copy of the frame\n fdata = in_image.copy().flatten()\n\n # define the locations of the four differently polarized sensors\n p90 = [[i+j*imgW for i in range(imgW) if i%2==0]for j in range(imgH) if j%2==0]\n p90idx = np.array([item for sublist in p90 for item in sublist]) # combine lists\n\n p0 = [[i+1+j*imgW for i in range(imgW) if i%2==0]for j in range(imgH) if j%2==0]\n p0idx = np.array([item for sublist in p0 for item in sublist]) # combine lists\n\n p135 = [[i+j*imgW for i in range(imgW) if i%2==0]for j in range(imgH) if j%2==1]\n p135idx = np.array([item for sublist in p135 for item in sublist]) # combine lists\n\n p45 = [[i+1+j*imgW for i in range(imgW) if i%2==0]for j in range(imgH) if j%2==1]\n p45idx = np.array([item for sublist in p45 for item in sublist]) # combine lists\n\n I_90 = fdata[p90idx].reshape([r,c]) # s0 polarized sub-image\n I_0 = fdata[p0idx].reshape([r,c]) # s0 polarized sub-image\n I_135 = fdata[p135idx].reshape([r,c]) # s0 polarized sub-image\n I_45 = fdata[p45idx].reshape([r,c]) # s0 polarized sub-image\n\n # spatial alignment of the four p images\n dr,dc = (0.25, 0.25)\n tform = AffineTransform(translation=(dr, dc))\n I_90 = warp(I_0, tform.inverse)\n tform = AffineTransform(translation=(dr, -dc))\n I_0 = warp(I_0, tform.inverse)\n tform = AffineTransform(translation=(-dr, -dc))\n I_135 = warp(I_135, tform.inverse)\n tform = AffineTransform(translation=(-dr, dc))\n I_45 = warp(I_45, tform.inverse)\n\n # Stoke's parameters\n S0 = I_90 + I_0\n S1 = I_90 - I_0\n S2 = I_45 - I_135\n DoLP = np.sqrt(S1**2 + S2**2)/S0\n\n # zero-out border pixels of DoLP\n DoLP[:,0] = 0\n DoLP[:,-1] = 0\n DoLP[0,:] = 0\n DoLP[-1,:] = 0\n\n if out_image.lower() == 'dolp':\n return bytescale(DoLP)\n elif out_image.lower() == 's0':\n return bytescale(S0)\n elif out_image.lower() == 's1':\n return bytescale(S1)\n elif out_image.lower() == 's2':\n return bytescale(S2) \n elif out_image == '':\n print('ERROR: please specify what kind of image you wish to be returned.')\n return None\n else:\n print('ERROR: That Polarization image not found')\n return None\n","sub_path":"utils/polarization.py","file_name":"polarization.py","file_ext":"py","file_size_in_byte":2931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"174391532","text":"N,K,Q = map(int, input().split())\nary = [0] * (N+1)\n\nfor i in range(Q):\n A = int(input())\n ary[A] += 1\n\ni = 1\nfor i in range(1, N+1):\n print('Yes' if ((K + ary[i] - Q) > 0) else 'No')\n","sub_path":"Python_codes/p02911/s631528481.py","file_name":"s631528481.py","file_ext":"py","file_size_in_byte":187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"532512464","text":"import libraries\nfrom libraries import *\n\ndef save_array(fname, arr): c=bcolz.carray(arr, rootdir=fname, mode='w'); c.flush()\ndef load_array(fname): return bcolz.open(fname)[:]\n\ndef silence():\n back = sys.stdout\n sys.stdout = open(os.devnull, 'w')\n\n return back\n\ndef speak(back): sys.stdout = back\n\ndef plot(im):\n plt.axis('off')\n plt.tight_layout()\n plt.imshow(im.astype(np.uint8))\n\n# def plot_ims(data, alpha=True): # plot_images(12)\n# \"\"\"\n# Expects numpy array with channels last\n# \"\"\"\n# nrows = 1\n# if len(data.shape) == 3: ncols = 1\n# else: ncols = data.shape[0] // nrows\n# fig, axes = plt.subplots(nrows=nrows, ncols=ncols)\n# fig.set_size_inches(12, 5)\n# fig.tight_layout()\n# for i, ax in enumerate(axes.flat):\n# if len(data[i].shape) == 2: im = ax.imshow(data[i])\n# elif (data[i].shape[2] == 4) & alpha: im = ax.imshow(data[i][:,:,[2,1,0,3]])\n# elif (data[i].shape[2] == 3): im = ax.imshow(data[i][:,:,[2,1,0]])\n# else: print('Data dimensions not supported')\n# ax.set_axis_off()\n# ax.title.set_visible(False)\n# ax.xaxis.set_ticks([])\n# ax.yaxis.set_ticks([])\n# for spine in ax.spines.values():\n# spine.set_visible(False)\n# plt.subplots_adjust(left=0, hspace=0, wspace=0)\n# plt.show()\n\n# def plot_im(data, alpha=True): # plot_images(12)\n# \"\"\"\n# Expects numpy array\n# \"\"\"\n# nrows, ncols = 1, 1\n# fig, ax = plt.subplots(nrows=nrows, ncols=ncols)\n# fig.set_size_inches(10, 10)\n# fig.tight_layout()\n\n# data = data.astype(np.uint8)\n\n# if len(data.shape) == 2: im = ax.imshow(data)\n# elif (data.shape[2] == 4) & alpha: im = ax.imshow(data[:,:,[2,1,0,3]])\n# elif (data.shape[2] == 3): im = ax.imshow(data[:,:,[2,1,0]])\n# else: print('Data dimensions not supported')\n\n# ax.set_axis_off()\n# ax.title.set_visible(False)\n# ax.xaxis.set_ticks([])\n# ax.yaxis.set_ticks([])\n# for spine in ax.spines.values():\n# spine.set_visible(False)\n# plt.subplots_adjust(left=0, hspace=0, wspace=0)\n# plt.show()\n\ndef rotate_im(im, angle, center=None, scale=1.0):\n # angle in degrees\n # grab the dimensions of the image\n (h, w) = im.shape[:2]\n\n # if the center is None, initialize it as the center of the image\n if center is None:\n center = (w // 2, h // 2)\n\n # perform the rotation\n M = cv2.getRotationMatrix2D(center, angle, scale)\n rotated = cv2.warpAffine(im, M, (w, h))\n\n return rotated\n\ndef shape_to_np(shape, dtype=\"int\"):\n # initialize the list of (x, y)-coordinates\n coords = np.zeros((68, 2), dtype=dtype)\n # loop over the 68 facial landmarks and convert them to a 2-tuple of (x, y)-coordinates\n for i in range(0, shape.num_parts):\n coords[i] = (shape.part(i).x, shape.part(i).y)\n return coords\n\ndef read_pts_file(filename):\n \"\"\"A helper function to read ibug .pts landmarks from a file.\"\"\"\n lines = open(filename).read().splitlines()\n if int(lines[1:2][0].split('n_points:')[-1]) != 68:\n print ('No 68-landmark format founded')\n return None\n lines = lines[3:71]\n\n landmarks = []\n for l in lines:\n coords = l.split()\n landmarks.append([float(coords[0]), float(coords[1])])\n return landmarks\n\ndef save_landmarks_as_pts(landmarks, path, f_name):\n # write data in a file.\n file_w = open(os.path.join(path, '{}.pts'.format(f_name)), 'w')\n\n header = ['version: 1 \\n', \\\n 'n_points: 68 \\n', \\\n '{ \\n']\n text = landmarks\n footer = ['}']\n\n file_w.writelines(header)\n file_w.writelines([str(i[0]) + ' ' + str(i[1]) + '\\n' for i in text])\n file_w.writelines(footer)\n file_w.close() #to change file access modes\n\n# def compute_landmarks(i_path,\n# o_path,\n# detected_face_images_path,\n# non_detected_face_images_path,\n# predictor_path, sample_size, plot_landmarks=False):\n#\n# for i in glob.glob(os.path.join(i_path, \"*jpg\"))[:sample_size]:\n# print(\"Processing file: %s\" %i)\n# im = io.imread(i)\n# im = cv2.imread(i) #.astype(np.float32)\n#\n# face_det = dlib.get_frontal_face_detector()\n# shape_pred = dlib.shape_predictor(predictor_path)\n# dets = face_det(im, 1)\n# # second argument indicates the number of times we should upsample the image in order to detect more faces.\n#\n# # rotate images if no landmarks detected\n# while len(dets) == 0:\n# rot_degrees = 90\n# for i in range(int(360//rot_degrees) + 1):\n# im = rotate_im(im, rot_degrees*i)\n# dets = face_det(im, 1)\n# rot_degrees = -90\n# for i in range(int(360//rot_degrees) + 1):\n# im = rotate_im(im, rot_degrees*i)\n# dets = face_det(im, 1)\n#\n# print(\"Number of faces detected: {}\".format(len(dets)))\n#\n# f_name = i.split('/')[-1].split('.')[0]\n#\n# if len(dets) == 0:\n# cv2.imwrite(os.path.join(non_detected_face_images_path, f_name + '.jpg'), im)\n#\n# else:\n# id_path = os.path.join(detected_face_images_path, f_name)\n#\n# if not os.path.exists(id_path): os.mkdir(id_path)\n# else:\n# shutil.rmtree(id_path)\n# os.mkdir(id_path)\n#\n# # cv2.imwrite(os.path.join(id_path, f_name + '.jpg'), im)\n#\n# for _, i in enumerate(dets):\n# (x0, y0, x1, y1) = i.left(), i.top(), i.right(), i.bottom();\n# # get the landmarks/parts for the face in box d.\n# landmarks = shape_to_np(shape_pred(im, i))\n# save_landmarks_as_pts(landmarks, id_path, f_name.split('.')[0])\n#\n# if plot_landmarks:\n# for _, i in enumerate(landmarks):\n# point = (i[0], i[1])\n# cv2.circle(im, point, 1, (0, 0, 255), -1)\n#\n# cv2.imwrite(os.path.join(id_path, f_name + '_landmarked.jpg'), im)\n#\n# n_im_lanmarked = glob.glob(os.path.join(o_path, \"*\"))\n# return n_im_lanmarked\n\n# def compute_3D_shape_and_texture(landmarks_path, path_to_eos):\n#\n# model = eos.morphablemodel.load_model(os.path.join(path_to_eos, \"eos/share/sfm_shape_3448.bin\"))\n# blendshapes = eos.morphablemodel.load_blendshapes(os.path.join(path_to_eos, \"eos/share/expression_blendshapes_3448.bin\"))\n#\n# # alternative: .scm models\n# # path_to_sfm = '/home/blanca/Documents/project/resources/www.cvssp.org/facemodels/shape/sfm.py'\n# # sys.path.append(path_to_scm_models)\n# # import sfm\n# # shape_only = False\n#\n# model = eos.morphablemodel.load_model('/home/blanca/Documents/project/resources/www.cvssp.org/facemodels/shape/eos/sfm_shape_29587.bin')\n# blendshapes = eos.morphablemodel.load_blendshapes('/home/blanca/Documents/project/resources/www.cvssp.org/facemodels/shape/expression/expression_blendshapes_29587.bin')\n# print('Using the 30k vertex SFM model..')\n#\n# landmark_mapper = eos.core.LandmarkMapper(os.path.join(path_to_eos, 'eos/share/ibug_to_sfm.txt'))\n# edge_topology = eos.morphablemodel.load_edge_topology(os.path.join(path_to_eos, 'eos/share/sfm_3448_edge_topology.json'))\n# contour_landmarks = eos.fitting.ContourLandmarks.load(os.path.join(path_to_eos, 'eos/share/ibug_to_sfm.txt'))\n# model_contour = eos.fitting.ModelContour.load(os.path.join(path_to_eos, 'eos/share/model_contours.json'))\n#\n# for i in glob.glob(os.path.join(landmarks_path, \"*\")):\n# f_name = i.split('/')[-1]\n#\n# im = cv2.imread(os.path.join(i, f_name + '.jpg'))\n#\n# \"\"\"Demo for running the eos fitting from Python.\"\"\"\n# landmarks = read_pts_file(os.path.join(i, f_name + '.pts'))\n# landmark_ids = list(map(str, range(1, 69))) # generates the numbers 1 to 68, as strings\n# im_width = im.shape[1] #1280 # Make sure to adjust these when using your own images!\n# im_height = im.shape[0] #1024\n#\n# (mesh, pose, shape_coeffs, blendshape_coeffs) = eos.fitting.fit_shape_and_pose(model, blendshapes,\n# landmarks, landmark_ids, landmark_mapper, im_width, im_height,\n# edge_topology, contour_landmarks, model_contour)\n#\n# # Now you can use your favourite plotting/rendering library to display the fitted mesh, using the rendering\n# # parameters in the 'pose' variable.\n#\n# isomap = eos.render.extract_texture(mesh, pose, im)\n# cv2.imwrite(os.path.join(i, f_name + '.isomap.png'), isomap)\n# eos.core.write_textured_obj(mesh, os.path.join(i, f_name + '.obj'))\n#\n# n_meshes = len(glob.glob(os.path.join(landmarks_path, \"*\")))\n# return n_meshes\n#\n#\n# def render_profiles(input_folder, degrees_step = 10):\n# # TODO: mute warning\n# stdout = silence() # filters the stdout\n#\n# import menpo3d\n# from mayavi import mlab\n#\n# for f in glob.glob(os.path.join(input_folder, \"*\")):\n#\n# f_name = f.split('/')[-1]\n# output_path = input_folder\n# profiles_folder_path = os.path.join(f, '%s_profiles' %f_name)\n# if not os.path.exists(profiles_folder_path): os.mkdir(profiles_folder_path)\n#\n# mesh = menpo3d.io.import_mesh(os.path.join(f, f_name + '.obj'))\n# mesh.view()\n#\n# s = mlab.gcf()\n# s.scene.camera.view_up = np.array([0, 0, 0])\n#\n# offset_angle = -90 # angle in the x plane wrt the frontal view\n# n_shots = 2 * abs(offset_angle) / degrees_step\n#\n# for i in range(n_shots):\n# mlab.view(azimuth=0, elevation=offset_angle + i * degrees_step, roll=0)\n# s.scene.save(os.path.join(profiles_folder_path, f_name + '_%d.jpg'%i))\n#\n# n_profiles = len(glob.glob(os.path.join(profiles_folder_path, \"*\")))\n#\n# speak(stdout) # unmute\n# return n_profiles\n","sub_path":"3d-model-fitting-pipeline/src/utils_delete.py","file_name":"utils_delete.py","file_ext":"py","file_size_in_byte":9952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"540269819","text":"'''\nCreated on Feb 6, 2018\n\n@author: mmp\n'''\n\nif __name__ == '__main__':\n\t\n\ttext = input('Some text:')\n\t\n\tdict = {}\n\tfor word in text.split():\t### other variant split(',') split('\\t') \n\t\t\t\t\t\t\t## split('space')\n\t\tif word in dict: dict[word] += 1\n\t\telse: dict[word] = 1\n\tprint(dict)","sub_path":"day_2/module_10.py","file_name":"module_10.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"409583257","text":"# Copyright 2021 NVIDIA 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 numpy as np\n\nimport legate.numpy as lg\n\n\ndef test():\n a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n a_lg = lg.array(a)\n b_lg = a_lg.swapaxes(0, 1)\n\n print(\"small\")\n assert lg.array_equal(a_lg.sum(axis=0), b_lg.sum(axis=1))\n\n a_tall = np.concatenate((a,) * 100)\n a_tall_lg = lg.array(a_tall)\n b_tall_lg = a_tall_lg.swapaxes(0, 1)\n\n print(\"tall\")\n assert lg.array_equal(a_tall_lg.sum(axis=0), b_tall_lg.sum(axis=1))\n\n a_wide = np.concatenate((a,) * 100, axis=1)\n a_wide_lg = lg.array(a_wide)\n b_wide_lg = a_wide_lg.swapaxes(0, 1)\n\n print(\"wide\")\n assert lg.array_equal(a_wide_lg.sum(axis=0), b_wide_lg.sum(axis=1))\n\n a_big = np.concatenate((a_tall,) * 100, axis=1)\n a_big_lg = lg.array(a_big)\n b_big_lg = a_big_lg.swapaxes(0, 1)\n\n print(\"big\")\n assert lg.array_equal(a_big_lg.sum(axis=0), b_big_lg.sum(axis=1))\n\n\nif __name__ == \"__main__\":\n test()\n","sub_path":"tests/swapaxes.py","file_name":"swapaxes.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"400920155","text":"from rest_framework import viewsets, generics\n\n\nclass QueryParamApiView(generics.GenericAPIView):\n \"\"\"\n query_params: a dictionary, containing query_param name as key\n and its filter argument as value\n e.g. {'author': 'author_id'}\n will work with ..?author=1 and filter it by (author_id=1)\n \"\"\"\n query_params = None\n\n def get_queryset(self):\n qs = super(QueryParamApiView, self).get_queryset()\n if self.query_params is not None:\n for param in self.query_params:\n value = self.request.query_params.get(param)\n if value is not None:\n kwargs = {self.query_params[param]: value}\n qs = qs.filter(**kwargs)\n return qs\n","sub_path":"rest_api/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"233179129","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: /Users/ismailsunni/.qgis2/python/plugins/inasafe/safe/metadata/property/dictionary_property.py\n# Compiled at: 2018-03-19 11:25:21\n\"\"\"Dictionary property.\"\"\"\nimport json\nfrom datetime import datetime\nfrom types import NoneType\nfrom safe.common.exceptions import MetadataCastError\nfrom safe.metadata.property import BaseProperty\nfrom safe.metadata.utilities import serialize_dictionary\n__copyright__ = 'Copyright 2016, The InaSAFE Project'\n__license__ = 'GPL version 3'\n__email__ = 'info@inasafe.org'\n__revision__ = '$Format:%H$'\n\nclass DictionaryProperty(BaseProperty):\n \"\"\"A property that accepts dictionary input.\"\"\"\n _allowed_python_types = [\n dict, NoneType]\n\n def __init__(self, name, value, xml_path):\n super(DictionaryProperty, self).__init__(name, value, xml_path, self._allowed_python_types)\n\n @classmethod\n def is_valid(cls, value):\n return True\n\n def cast_from_str(self, value):\n try:\n value = json.loads(value)\n for k, v in value.items():\n if isinstance(v, basestring):\n try:\n dictionary_value = json.loads(v)\n if isinstance(dictionary_value, dict):\n value[k] = dictionary_value\n except ValueError:\n try:\n value[k] = datetime.strptime(v, '%Y-%m-%dT%H:%M:%S.%f')\n except ValueError:\n pass\n\n return value\n except ValueError as e:\n raise MetadataCastError(e)\n\n @property\n def xml_value(self):\n if self.python_type is dict:\n try:\n return json.dumps(self.value)\n except (TypeError, ValueError):\n string_value = serialize_dictionary(self.value)\n return json.dumps(string_value)\n\n else:\n if self.python_type is NoneType:\n return ''\n raise RuntimeError('self._allowed_python_types and self.xml_value are out of sync. This should never happen')","sub_path":"pycfiles/inasafe-core-4.4.0.tar/dictionary_property.py","file_name":"dictionary_property.py","file_ext":"py","file_size_in_byte":2249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"218608766","text":"from urllib.request import urlopen\n\ndef callback(MEIKOdata = None):\n pmap = urlopen('http://www.pollens.fr/docs/Departements_de_France-simple.png')\n status = '{}\\n{}'.format(\"[#pollen #allergie] Statut actuel, plus d'informations : \",\n \"http://www.pollens.fr/docs/vigilance.html\")\n tootinfo = { \n 'type':'media',\n 'sensitive': False,\n 'visibility':'',\n 'spoiler_text': None\n }\n return tootinfo, (status, [{'fname':pmap, 'mime':'image/png'}])\n","sub_path":"Mods/Pollens.py","file_name":"Pollens.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"61853978","text":"# Image Blending\r\n\r\nimport cv2\r\n\r\nimg1 = cv2.imread('img_1.jpg')\r\nimg2 = cv2.imread('img_2.jpg')\r\ndst = cv2.addWeighted(img1,0.5,img2,0.5,0)\r\ncv2.imshow('Image1',img1)\r\ncv2.imshow('Image2',img2)\r\ncv2.imshow('dst',dst)\r\ncv2.imwrite(\"blend_image.jpg\",dst)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n","sub_path":"OpeCV sample code/blurr.py","file_name":"blurr.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"588666712","text":"import scipy as sp\nimport numpy as np\nfrom scipy import linalg as la\nfrom typing import List, Callable\nimport logging\n\nfrom ..sampler import Sampler\nfrom .scales import standard_deviation\nfrom .base import Distance\n\n\nlogger = logging.getLogger(\"Distance\")\n\n\nclass PNormDistance(Distance):\n \"\"\"\n Use weighted p-norm\n\n .. math::\n\n d(x, y) = \\\n \\\\left [\\\\sum_{i} \\\\left| w_i ( x_i-y_i ) \\\\right|^{p} \\\\right ]^{1/p}\n\n to compute distances between sets of summary statistics. E.g. set p=2 to\n get a Euclidean distance.\n\n Parameters\n ----------\n\n p: float\n p for p-norm. Required p >= 1, p = np.inf allowed (infinity-norm).\n\n w: dict\n Weights. Dictionary indexed by time points. Each entry contains a\n dictionary of numeric weights, indexed by summary statistics labels.\n If None is passed, a weight of 1 is considered for every summary\n statistic. If no entry is available in w for a given time point,\n the maximum available time point is selected.\n \"\"\"\n\n def __init__(self,\n p: float = 2,\n w: dict = None):\n super().__init__()\n\n if p < 1:\n raise ValueError(\"It must be p >= 1\")\n self.p = p\n\n self.w = w\n\n def __call__(self,\n x: dict,\n x_0: dict,\n t: int,\n par: dict = None) -> float:\n # make sure weights are initialized\n if self.w is None:\n self._set_default_weights(t, x.keys())\n\n # select last time point for which weights exist\n if t not in self.w:\n t = max(self.w)\n\n # extract weights for time point\n w = self.w[t]\n\n # compute distance\n if self.p == np.inf:\n d = max(abs(w[key] * (x[key] - x_0[key]))\n if key in x and key in x_0 else 0\n for key in w)\n else:\n d = pow(\n sum(pow(abs(w[key] * (x[key] - x_0[key])), self.p)\n if key in x and key in x_0 else 0\n for key in w),\n 1 / self.p)\n\n return d\n\n def _set_default_weights(self,\n t: int,\n sum_stat_keys):\n \"\"\"\n Init weights to 1 for every summary statistic.\n \"\"\"\n self.w = {t: {k: 1 for k in sum_stat_keys}}\n\n def get_config(self) -> dict:\n return {\"name\": self.__class__.__name__,\n \"p\": self.p,\n \"w\": self.w}\n\n\nclass AdaptivePNormDistance(PNormDistance):\n \"\"\"\n In the p-norm distance, adapt the weights for each generation, based on\n the previous simulations. This class is motivated by [#prangle]_.\n\n Parameters\n ----------\n\n p: float, optional (default = 2)\n p for p-norm. Required p >= 1, p = np.inf allowed (infinity-norm).\n\n adaptive: bool, optional (default = True)\n True: Adapt distance after each iteration.\n False: Adapt distance only once at the beginning in initialize().\n This corresponds to a pre-calibration.\n\n scale_function: Callable, optional (default = standard_deviation)\n (data: list, x_0: float) -> scale: float. Computes the scale (i.e.\n inverse weight s = 1 / w) for a given summary statistic. Here, data\n denotes the list of simulated summary statistics, and x_0 the observed\n summary statistic. Implemented are absolute_median_deviation,\n standard_deviation (default), centered_absolute_median_deviation,\n centered_standard_deviation.\n\n normalize_weights: bool, optional (default = True)\n Whether to normalize the weights to have mean 1. This just possibly\n smoothes the decrease of epsilon and might aid numeric stability, but\n is not strictly necessary.\n\n max_weight_ratio: float, optional (default = None)\n If not None, large weights will be bounded by the ratio times the\n smallest non-zero absolute weight. In practice usually not necessary,\n it is theoretically required to ensure convergence.\n\n\n .. [#prangle] Prangle, Dennis. \"Adapting the ABC Distance Function\".\n Bayesian Analysis, 2017. doi:10.1214/16-BA1002.\n \"\"\"\n\n def __init__(self,\n p: float = 2,\n adaptive: bool = True,\n scale_function=None,\n normalize_weights: bool = True,\n max_weight_ratio: float = None):\n # call p-norm constructor\n super().__init__(p=p, w=None)\n\n self.adaptive = adaptive\n\n if scale_function is None:\n scale_function = standard_deviation\n self.scale_function = scale_function\n\n self.normalize_weights = normalize_weights\n self.max_weight_ratio = max_weight_ratio\n\n self.x_0 = None\n\n def configure_sampler(self,\n sampler: Sampler):\n \"\"\"\n Make the sampler return also rejected particles,\n because these are needed to get a better estimate of the summary\n statistic variabilities, avoiding a bias to accepted ones only.\n\n Parameters\n ----------\n\n sampler: Sampler\n The sampler employed.\n \"\"\"\n if self.adaptive:\n sampler.sample_factory.record_rejected = True\n\n def initialize(self,\n t: int,\n get_sum_stats: Callable[[], List[dict]],\n x_0: dict = None):\n \"\"\"\n Initialize weights.\n \"\"\"\n self.x_0 = x_0\n\n # execute function\n sum_stats = get_sum_stats()\n\n # update weights from samples\n self._update(t, sum_stats)\n\n def update(self,\n t: int,\n sum_stats: List[dict]):\n \"\"\"\n Update weights based on all simulations.\n \"\"\"\n\n if not self.adaptive:\n return False\n\n self._update(t, sum_stats)\n\n return True\n\n def _update(self,\n t: int,\n sum_stats: List[dict]):\n \"\"\"\n Here the real update of weights happens.\n \"\"\"\n\n # retrieve keys\n keys = self.x_0.keys()\n\n # number of samples\n n_samples = len(sum_stats)\n\n # make sure w_list is initialized\n if self.w is None:\n self.w = {}\n\n # to-be-filled-and-appended weights dictionary\n w = {}\n\n for key in keys:\n # prepare list for key\n current_list = []\n for j in range(n_samples):\n if key in sum_stats[j]:\n current_list.append(sum_stats[j][key])\n\n # compute scaling\n scale = self.scale_function(data=current_list, x_0=self.x_0[key])\n\n # compute weight (inverted scale)\n if np.isclose(scale, 0):\n # This means that either the summary statistic is not in the\n # samples, or that all simulations were identical. In either\n # case, it should be safe to ignore this summary statistic.\n w[key] = 0\n else:\n w[key] = 1 / scale\n\n # normalize weights to have mean 1\n w = self._normalize_weights(w)\n\n # bound weights\n w = self._bound_weights(w)\n\n # add to w attribute, at time t\n self.w[t] = w\n\n # logging\n logger.debug(\"update distance weights = {}\".format(self.w[t]))\n\n def _normalize_weights(self, w):\n \"\"\"\n Normalize weights to have mean 1.\n\n This has just the effect that eps will decrease more smoothly, but is\n not important otherwise.\n \"\"\"\n if not self.normalize_weights:\n return w\n\n mean_weight = np.mean(list(w.values()))\n for key in w:\n w[key] /= mean_weight\n\n return w\n\n def _bound_weights(self, w):\n \"\"\"\n Bound all weights to self.max_weight_ratio times the minimum\n non-zero absolute weight, if self.max_weight_ratio is not None.\n\n While this is usually not required in practice, it is theoretically\n necessary that the ellipses are not arbitrarily eccentric, in order\n to ensure convergence.\n \"\"\"\n if self.max_weight_ratio is None:\n return w\n\n # find minimum weight != 0\n w_arr = np.array(list(w.values()))\n min_abs_weight = np.min(np.abs(w_arr[w_arr != 0]))\n # can be assumed to be != 0\n\n for key, value in w.items():\n # bound too large weights\n if abs(value) / min_abs_weight > self.max_weight_ratio:\n w[key] = np.sign(value) * self.max_weight_ratio \\\n * min_abs_weight\n\n return w\n\n def get_config(self) -> dict:\n return {\"name\": self.__class__.__name__,\n \"p\": self.p,\n \"adaptive\": self.adaptive,\n \"scale_function\": self.scale_function.__name__,\n \"normalize_weights\": self.normalize_weights,\n \"max_weight_ratio\": self.max_weight_ratio}\n\n\nclass DistanceWithMeasureList(Distance):\n \"\"\"\n Base class for distance functions with measure list.\n This class is not functional on its own.\n\n Parameters\n ----------\n\n measures_to_use: Union[str, List[str]].\n * If set to \"all\", all measures are used. This is the default.\n * If a list is provided, the measures in the list are used.\n * measures refers to the summary statistics.\n \"\"\"\n\n def __init__(self,\n measures_to_use='all'):\n super().__init__()\n # the measures (summary statistics) to use for distance calculation\n self.measures_to_use = measures_to_use\n\n def initialize(self,\n t: int,\n get_sum_stats: Callable[[], List[dict]],\n x_0: dict = None):\n if self.measures_to_use == 'all':\n self.measures_to_use = x_0.keys()\n\n def get_config(self):\n config = super().get_config()\n config[\"measures_to_use\"] = self.measures_to_use\n return config\n\n\nclass ZScoreDistance(DistanceWithMeasureList):\n \"\"\"\n Calculate distance as sum of ZScore over the selected measures.\n The measured Data is the reference for the ZScore.\n\n Hence\n\n .. math::\n\n d(x, y) = \\\n \\\\sum_{i \\\\in \\\\text{measures}} \\\\left| \\\\frac{x_i-y_i}{y_i} \\\\right|\n \"\"\"\n\n def __call__(self,\n x: dict,\n x_0: dict,\n t: int = None,\n par: dict = None) -> float:\n return sum(abs((x[key] - x_0[key]) / x_0[key]) if x_0[key] != 0 else\n (0 if x[key] == 0 else np.inf)\n for key in self.measures_to_use) / len(self.measures_to_use)\n\n\nclass PCADistance(DistanceWithMeasureList):\n \"\"\"\n Calculate distance in whitened coordinates.\n\n A whitening transformation :math:`X` is calculated from an initial sample.\n The distance is measured as euclidean distance in the transformed space.\n I.e\n\n .. math::\n\n d(x,y) = \\\\| Wx - Wy \\\\|\n \"\"\"\n\n def __init__(self, measures_to_use='all'):\n super().__init__(measures_to_use)\n self._whitening_transformation_matrix = None\n\n def _dict_to_vect(self, x):\n return sp.asarray([x[key] for key in self.measures_to_use])\n\n def _calculate_whitening_transformation_matrix(self, sum_stats):\n samples_vec = sp.asarray([self._dict_to_vect(x)\n for x in sum_stats])\n # samples_vec is an array of shape nr_samples x nr_features\n means = samples_vec.mean(axis=0)\n centered = samples_vec - means\n covariance = centered.T.dot(centered)\n w, v = la.eigh(covariance)\n self._whitening_transformation_matrix = (\n v.dot(sp.diag(1. / sp.sqrt(w))).dot(v.T))\n\n def initialize(self,\n t: int,\n get_sum_stats: Callable[[], List[dict]],\n x_0: dict = None):\n super().initialize(t, get_sum_stats, x_0)\n\n # execute function\n sum_stats = get_sum_stats()\n\n self._calculate_whitening_transformation_matrix(sum_stats)\n\n def __call__(self,\n x: dict,\n x_0: dict,\n t: int = None,\n par: dict = None) -> float:\n x_vec, x_0_vec = self._dict_to_vect(x), self._dict_to_vect(x_0)\n distance = la.norm(\n self._whitening_transformation_matrix.dot(x_vec - x_0_vec), 2)\n return distance\n\n\nclass RangeEstimatorDistance(DistanceWithMeasureList):\n \"\"\"\n Abstract base class for distance functions which estimate is based on a\n range.\n\n It defines the two template methods ``lower`` and ``upper``.\n\n Hence\n\n .. math::\n\n d(x, y) = \\\n \\\\sum_{i \\\\in \\\\text{measures}} \\\\left | \\\\frac{x_i - y_i}{u_i - l_i}\\\n \\\\right |\n\n where :math:`l_i` and :math:`u_i` are the lower and upper\n margin for measure :math:`i`.\n \"\"\"\n\n @staticmethod\n def lower(parameter_list: List[float]):\n \"\"\"\n Calculate the lower margin form a list of parameter values.\n\n Parameters\n ----------\n parameter_list: List[float]\n List of values of a parameter.\n\n Returns\n -------\n\n lower_margin: float\n The lower margin of the range calculated from these parameters\n \"\"\"\n\n @staticmethod\n def upper(parameter_list: List[float]):\n \"\"\"\n Calculate the upper margin form a list of parameter values.\n\n Parameters\n ----------\n parameter_list: List[float]\n List of values of a parameter.\n\n Returns\n -------\n\n upper_margin: float\n The upper margin of the range calculated from these parameters\n \"\"\"\n\n def __init__(self, measures_to_use='all'):\n super().__init__(measures_to_use)\n self.normalization = None\n\n def get_config(self):\n config = super().get_config()\n config[\"normalization\"] = self.normalization\n return config\n\n def _calculate_normalization(self, sum_stats):\n measures = {name: [] for name in self.measures_to_use}\n for sample in sum_stats:\n for measure in self.measures_to_use:\n measures[measure].append(sample[measure])\n self.normalization = {measure:\n self.upper(measures[measure])\n - self.lower(measures[measure])\n for measure in self.measures_to_use}\n\n def initialize(self,\n t: int,\n get_sum_stats: Callable[[], List[dict]],\n x_0: dict = None):\n super().initialize(t, get_sum_stats, x_0)\n\n # execute function\n sum_stats = get_sum_stats()\n\n self._calculate_normalization(sum_stats)\n\n def __call__(self,\n x: dict,\n x_0: dict,\n t: int = None,\n par: dict = None) -> float:\n distance = sum(abs((x[key] - x_0[key]) / self.normalization[key])\n for key in self.measures_to_use)\n return distance\n\n\nclass MinMaxDistance(RangeEstimatorDistance):\n \"\"\"\n Calculate upper and lower margins as max and min of the parameters.\n This works surprisingly well for normalization in simple cases\n \"\"\"\n\n @staticmethod\n def upper(parameter_list):\n return max(parameter_list)\n\n @staticmethod\n def lower(parameter_list):\n return min(parameter_list)\n\n\nclass PercentileDistance(RangeEstimatorDistance):\n \"\"\"\n Calculate normalization 20% and 80% from percentiles as lower\n and upper margins\n \"\"\"\n\n PERCENTILE = 20 #: The percentiles\n\n @staticmethod\n def upper(parameter_list):\n return sp.percentile(parameter_list,\n 100 - PercentileDistance.PERCENTILE)\n\n @staticmethod\n def lower(parameter_list):\n return sp.percentile(parameter_list,\n PercentileDistance.PERCENTILE)\n\n def get_config(self):\n config = super().get_config()\n config[\"PERCENTILE\"] = self.PERCENTILE\n return config\n","sub_path":"pyabc/distance/distance.py","file_name":"distance.py","file_ext":"py","file_size_in_byte":16202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"144914183","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.forms import modelformset_factory\nimport openpyxl\nfrom .models import Customer, BankAccountDetail, Account\nfrom .forms import BankAccountForm, BankAccountDetailForm, AccountForm\n\nINITIAL_BANK_CODE = '98000'\nINITIAL_ACCOUNT_CODE = '101'\n\n# 계정과목 관리\n\ndef account_list(request):\n accounts = Account.objects.all().order_by('code')\n\n return render(request, 'accounting/account_list.html', {'account_list': accounts})\n\ndef account_detail(request, code):\n if request.method == 'POST':\n account = Account.objects.get_or_create(code=code)[0]\n form = AccountForm(request.POST, instance=account)\n\n if form.is_valid():\n form.save()\n\n return redirect('accounting:account_list')\n else:\n try:\n account = Account.objects.get(code=code)\n form = AccountForm(instance=account)\n except:\n form = AccountForm(initial={'code': code})\n \n return render(request, 'accounting/account_detail.html', {'form': form})\n\ndef account_create(request):\n last_account = Account.objects.all().order_by('code').last()\n try:\n code = int(last_account.code) + 1\n except:\n code = INITIAL_ACCOUNT_CODE\n \n return redirect('accounting:account_detail', code=code)\n\ndef account_delete(request, code):\n account = Account.objects.get(code=code)\n\n if request.method == 'POST':\n account.delete()\n return redirect('accounting:account_list')\n \n return render(request, 'accounting/account_delete.html', {'account': account})\n\ndef account_upload(request):\n if request.method == 'POST':\n excel_file = request.FILES['excel_file']\n workbook = openpyxl.load_workbook(excel_file)\n worksheet = workbook.worksheets[0]\n\n worksheet.delete_rows(1)\n\n existing_list = list(Account.objects.all().values_list('code', flat=True))\n update_list = []\n create_list = []\n\n for row in worksheet:\n if row[0].value in existing_list:\n update_account = Account.objects.get(code=row[0].value)\n update_account.name = row[1].value\n update_account.classification = row[2].value\n update_list.append(update_account)\n else:\n create_list.append(Account(code=row[0].value, name=row[1].value, classification=row[2].value))\n \n Account.objects.bulk_update(update_list, ['name', 'classification'])\n Account.objects.bulk_create(create_list)\n\n return redirect('accounting:account_list')\n\n return render(request, 'accounting/account_upload.html')\n\n# 금융계좌 관리\n\ndef bank_list(request):\n bank_list = BankAccountDetail.objects.all().order_by('customer__code')\n\n return render(request, 'accounting/bank_list.html', {'bank_list': bank_list})\n\ndef bank_detail(request, code):\n if request.method == 'POST':\n bank_account = Customer.objects.get_or_create(code=code)[0]\n bank_account_detail = BankAccountDetail.objects.get_or_create(customer=bank_account)[0]\n\n bank_form = BankAccountForm(request.POST, instance=bank_account, prefix='bank')\n detail_form = BankAccountDetailForm(request.POST, instance=bank_account_detail, prefix='bank_detail')\n\n if bank_form.is_valid() and detail_form.is_valid():\n bank = bank_form.save(commit=False)\n bank.classification = 'bank_account'\n bank.save()\n\n detail = detail_form.save(commit=False)\n detail.customer = bank\n detail.save()\n\n return redirect('accounting:bank_list')\n else:\n try:\n bank_account = Customer.objects.get(code=code)\n bank_form = BankAccountForm(instance=bank_account, prefix='bank')\n except:\n bank_form = BankAccountForm(initial={'code':code}, prefix='bank')\n \n try:\n bank_account_detail = BankAccountDetail.objects.get(customer=bank_account)\n detail_form = BankAccountDetailForm(instance=bank_account_detail, prefix='bank_detail')\n except:\n detail_form = BankAccountDetailForm(prefix='bank_detail')\n\n return render(request, 'accounting/bank_detail.html', {'bank_form': bank_form, 'detail_form': detail_form})\n\ndef bank_create(request):\n last_bank = Customer.objects.filter(classification='bank_account').order_by('code').last()\n try:\n code = int(last_bank.code) + 1\n except:\n code = INITIAL_BANK_CODE\n\n return redirect('accounting:bank_detail', code=code)\n\ndef bank_delete(request, code):\n bank_account = Customer.objects.get(code=code)\n\n if request.method == 'POST':\n bank_account.delete()\n return redirect('accounting:bank_list')\n\n return render(request, 'accounting/bank_delete.html', {'bank_account': bank_account})\n\ndef bank_upload(request):\n if request.method == 'POST':\n excel_file = request.FILES['excel_file']\n workbook = openpyxl.load_workbook(excel_file)\n worksheet = workbook.worksheets[0]\n\n worksheet.delete_rows(1)\n\n existing_list = list(Customer.objects.filter(classification='bank_account').values_list('code', flat=True))\n update_bank_list = []\n update_bank_detail_list = []\n create_bank_detail_list = []\n\n for row in worksheet:\n if row[0].value in existing_list:\n update_bank = Customer.objects.get(code=row[0].value)\n update_bank.name = row[1].value\n update_bank_list.append(update_bank)\n\n update_bank_detail = BankAccountDetail.objects.get_or_create(customer=update_bank)[0]\n update_bank_detail.name = row[2].value\n update_bank_detail.number = row[3].value\n update_bank_detail.memo = row[4].value or ''\n update_bank_detail_list.append(update_bank_detail)\n else:\n new_bank_account = Customer.objects.create(code=row[0].value, name=row[1].value, classification='bank_account')\n create_bank_detail_list.append(BankAccountDetail(customer=new_bank_account, name=row[2].value, number=row[3].value, memo=row[4].value or ''))\n \n Customer.objects.bulk_update(update_bank_list, ['name'])\n BankAccountDetail.objects.bulk_update(update_bank_detail_list, ['name', 'number', 'memo'])\n\n BankAccountDetail.objects.bulk_create(create_bank_detail_list)\n\n return redirect('accounting:bank_list')\n\n return render(request, 'accounting/bank_upload.html')","sub_path":"accounting/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"399304625","text":"\"\"\"\nsource from: https://pypi.org/project/PyStanfordDependencies/\n\t\t\thttps://stackoverflow.com/questions/13883277/stanford-parser-and-nltk\n\n\n\"\"\"\nimport StanfordDependencies, os.path, sys\nfrom nltk.parse.stanford import StanfordParser\nparser = StanfordParser() #be sure to have set environmental path to englishPCFG.ser.gz\nsd = StanfordDependencies.get_instance(backend='subprocess')\n\ndef getTypeD(input):\n\t'returns our the string with the dependency tags'\n\tsS = \"\"\n\tmyList = list(parser.raw_parse(input))\n\tfor l in myList:\n\t\tsS+=str(l)\n\treturn sS\n\ndef createDepData(tag_sent):\n\t'method from the PyStanfordDependencies 0.3.1 package to tokenize parsed data'\n\tdata = sd.convert_tree(tag_sent)\n\treturn data\n\ndef analyzeData(myList):\n\t'creates a list of dictionaries and stores the data of the index, word, head'\n\t'(which word points to the current word) and the typed dependency'\n\tmaster_list = []\n\tfor x in myList:\n\t\tdict_list = []\n\t\tmySent = getTypeD(x)\n\t\tdata = createDepData(mySent)\n\t\tfor y in range(len(data)): # access each token in data\n\t\t\tdata_dict = {}\n\t\t\tfor z in range(len(data[y])): #access each token's content\n\t\t\t\tif str(z)=='0':\n\t\t\t\t\tdata_dict.update({'index': data[y][z]})\n\t\t\t\telif str(z)=='1':\n\t\t\t\t\tdata_dict.update({'word': data[y][z]})\n\t\t\t\telif str(z)=='6':\n\t\t\t\t\tdata_dict.update({'head': data[y][z]})\n\t\t\t\telif str(z)=='7':\n\t\t\t\t\tdata_dict.update({'deprel': data[y][z]})\n\t\t\tdict_list.append(data_dict)\n\t\tmaster_list.append(dict_list)\n\treturn master_list\n","sub_path":"volcano_examples/Parsing_Output_Volcano/createParsedDict.py","file_name":"createParsedDict.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"597648301","text":"#vlength of word for each number\ndef checkDigit(x):\n\tadd = 0\n\tif x == 1:\n\t\tadd = 3\n\telif x == 2:\n\t\tadd = 3\n\telif x == 3:\n\t\tadd = 5\n\telif x == 4:\n\t\tadd = 4\n\telif x ==5:\n\t\tadd = 4\n\telif x == 6:\n\t\tadd = 3\n\telif x == 7:\n\t\tadd =5\n\telif x== 8:\n\t\tadd = 5\n\telif x== 9:\n\t\tadd = 4 \t\t\n\treturn add\n\n#lenght for word for 10-19\ndef checkTens(x):\n\tadd = 0\n\tif x == 10:\n\t\tadd = 3\n\telif x == 11:\n\t\tadd = 6\n\telif x == 12:\n\t\tadd = 6\n\telif x == 13:\n\t\tadd = 8\n\telif x == 14:\n\t\tadd = 7\n\telif x == 15:\n\t\tadd = 7\n\telif x == 16:\n\t\tadd = 7\n\telif x == 17:\n\t\tadd = 9\n\telif x== 18:\n\t\tadd = 9\n\telif x== 19:\n\t\tadd = 8 \t\t\n\treturn add\n\n#start of loop\ntotal_length = 0\nfor number in range(1,1001):\n\t#print(number)\n\tlength = len(str(number))\n\n\tword_length = 0\n\tindex = -1 \n\n\t# for number value of digits\n\twhile abs(index) <= length:\n\t\tif index < -2:\n\t\t\tword_length += checkDigit(int(str(number)[index]))\n\t\tindex -=1\n\n\tprint(word_length)\n\n\t# for name of digit place\n\tif length == 1:\n\t\tword_length += checkDigit(int(str(number)[-1]))\n\tif length >= 2:\n\t\t#tens\n\t\tif str(number)[-2] == \"0\":\n\t\t\tword_length += checkDigit(int(str(number)[-1]))\n\n\t\tif str(number)[-2] == \"1\":\n\t\t\tword_length += checkTens(int(str(number)[-2:]))\n\t\tif str(number)[-2] == \"2\"\\\n\t\tor str(number)[-2] == \"3\"\\\n\t\tor str(number)[-2] == \"8\"\\\n\t\tor str(number)[-2] == \"9\" :\n\t\t\t#twenty, thirty, fourty, ninety,eighty\n\t\t\tword_length +=6\n\n\t\t\t#check one's place\n\t\t\tword_length += checkDigit(int(str(number)[-1]))\n\t\telif str(number)[-2] == \"5\"\\\n\t\tor str(number)[-2] == \"6\"\\\n\t\tor str(number)[-2] == \"4\":\n\t\t\t#fifty, sixty,forty\n\t\t\tword_length += 5\n\t\t\tword_length += checkDigit(int(str(number)[-1]))\n\t\telif str(number)[-2] == \"7\":\n\t\t\tword_length +=7\n\t\t\tword_length += checkDigit(int(str(number)[-1]))\n\tif length >=3:\n\t\tif str(number)[-3] != \"0\":\n\t\t\t#hundred\n\t\t\tword_length += 7\n\t\t#if had numbers for tens and ones place ADD \"and\"\n\t\tif str(number)[-2:] != \"00\":\n\t\t\tword_length += 3\n\n\t\tprint(word_length)\n\tif length >= 4:\n\t\tif str(number)[-4] != \"0\":\n\t\t\t#thousand\n\t\t\tword_length += 8\n\ttotal_length += word_length\nprint(total_length)\n\n\n\n","sub_path":"letter_count.py","file_name":"letter_count.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"159400367","text":"#!usr/bin/python\n#coding:utf-8\nimport sqlite3\nfrom py_mecab import py_mecab\nfrom tf_idf import tf\nfrom tf_idf import idf\n\nf = open('learning.txt')\nconn = sqlite3.connect('TweetData.db')\nc = conn.cursor()\ninsert_sql = \"insert into tfidf values({}, '{}', {})\" # id, word, tf-idf\n\ndef create():\n\tc.execute('create table tfidf(id int, word text, tfidf float)')\n\ndef delete():\n\tc.execute('drop table tfidf')\n\ndef main():\n\tfor line in f:\n\t\tline = line.split()\n\t\ttweet_id = line[0]\n\t\ttweet = py_mecab(' '.join(line[1:]))\n#\t\tprint('{:20}:{}'.format(tweet_id, ''.join(tweet)))\n\t\tfor word in tweet: # each word per tweet & ID\n\t\t\t\n\t\t\ttry:\n\t\t\t\tfor row in c.execute(\"select value from idf where word like '_{}_'\".format(word)):\n\t\t\t\t\tidf_value = row[0]\n\t\t\t\t\tbreak\n\t\t\texcept:\n\t\t\t\tprint(word)\n\n\t\t\ttf_value = tf(tweet, word)\n\n\t\t\ttf_idf_value = tf_value*idf_value\n\t\t\t#print(\"{}:{}:{}\\n\".format(tweet_id, word, tf_idf_value))\n\t\t\ttry:\n\t\t\t\tc.execute(insert_sql.format(tweet_id, word, tf_idf_value))\n\t\t\t\tprint('OK')\n\t\t\texcept:\n\t\t\t\tprint(\"{}:{}:{}\\n\".format(tweet_id, word, tf_idf_value))\n\t\t\t\tcontinue\n\t\t\tconn.commit()\n\n#delete()\n#create()\n#main()\n\nconn.close()\n","sub_path":"create_database_tfidf.py","file_name":"create_database_tfidf.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"389726525","text":"# Minderung im Kaufrecht\r\n# (C) Moritz Rowold\r\n\r\ndef GeldBetrag(text:str)->float: # ->float als Typehint, welches Ergebnis ausgespuckt werden soll\r\n \"Validiere Geldbeträge mit Frage text\"\r\n # gueltig boolean=False\r\n while True: # Alternative \"not gueltig\"\r\n wert=input(text)\r\n try:\r\n eingabe=float(wert)\r\n if(eingabe<0): \r\n print(\"Bitte eine positive Zahl eingeben.\")\r\n # break <- damit wird die Schleife beendet \r\n else:\r\n if(round(eingabe,2)!=eingabe): \r\n print(\"Bitte maximal zwei Nachkommastellen eingeben.\") # Eingabe negativ? -> Fehlermeldung\r\n else:\r\n break\r\n # gueltig = True\r\n except:\r\n print(\"Bitte geben Sie eine Kommazahl ein\")\r\n # Rückgabewert -> muss ein Float-Wert sein (= Kommawert)\r\n return eingabe\r\n\r\n# Kaufpreis muss > 0 sein\r\nKaufpreis:float=-1\r\nwhile Kaufpreis <= 0:\r\n Kaufpreis=GeldBetrag(\"Bitte geben Sie den Kaufpreis ein: \")\r\n\r\n# Keine zusätzliche Bedingung\r\nWahrerWert:float=GeldBetrag(\"Geben Sie den wahren Wert (mit Mangel) ein: \")\r\n\r\n# Bedingung: Größer oder gleich wahrer Wert\r\nHypoWert:float=-1\r\nwhile HypoWert' % media.images['thumbnail'].url)\n for picture in photos:\n print(picture)\n\n except InstagramAPIError as e:\n if (e.status_code == 400):\n print(\"\\nUser is set to private.\")\n return\n\ngetPictures()\n\ndef getFollowers():\n try:\n follows, next_ = api.user_follows()\n while next_:\n more_follows, next_ = api.user_follows(with_next_url=next_)\n follows.extend(more_follows)\n except InstagramAPIError as e:\n if (e.status_code == 400):\n print(\"\\nUser is set to private.\")\n return\n\n#getFollowers()\n","sub_path":"instagramDataMiner.py","file_name":"instagramDataMiner.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"505207274","text":"import numpy as np\nfrom typing import Iterator, Tuple\nfrom .column_generator import ColumnGenerator\nfrom ..models.table import Table\nfrom collections import defaultdict\n\nclass TableGenerator(object):\n\n def __init__(self, table: Table, column_generator: ColumnGenerator):\n self.table = table\n self.colum_generator = column_generator\n\n self.labels = defaultdict(list)\n\n for column in self.table.columns:\n for _ in range(table.max_number_of_labels):\n self.labels[column.order].append(\n self.colum_generator.generate_label(column)\n )\n\n super().__init__()\n\n def get_table(self) -> Tuple[str, Iterator[Iterator[str]], str]:\n ## we want this to grow right,\n actual_table = [ [] for _ in self.table.columns ]\n\n ## we want this to be flat,\n target_table = []\n\n for column in self.table.columns:\n if self.table.max_number_of_labels == 1:\n choices = self.labels[column.order]\n else:\n n_labels = np.random.randint(1, self.table.max_number_of_labels)\n\n indexes = list(range(0, len(self.labels[column.order])))\n columns = np.random.choice(indexes, size = n_labels, replace = False)\n choices = [ self.labels[column.order][col] for col in columns ]\n\n for choice in choices:\n labels = choice[0]\n unit = choice[1]\n\n actual, expected = self.colum_generator.get_value_for_label(column, labels, unit)\n\n for row in actual:\n actual_table[column.order].append(row)\n\n target_table.append(expected)\n\n return self.table.get_id(), self.table.compress(actual_table), '\\n'.join(target_table)\n","sub_path":"core/generators/table_generator.py","file_name":"table_generator.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"185385313","text":"def add_reviews(title,comment):\n if title in title_set:\n Comment = pd.DataFrame({'title':[title],'Comments':[comment]})\n Comment.to_csv('comments.csv',mode='a',header=None,index=False)\n return 200\n else:\n return 400\n \ndef show_reviews(title):\n if title in title_set:\n review = pd.read_csv('comments.csv',header=None)\n result=[]\n review = review[review[0]==title]\n for index,row in review.iterrows():\n result.append(row[1])\n return result\n else:\n return 400","sub_path":"review_func.py","file_name":"review_func.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"292951081","text":"from django import forms\n\nfrom compensation.models import CompensationBatch\nfrom compensation.validators import serial_numbers_not_registered_yet_validator\nfrom sncheck.validators import serial_numbers_list_length_validator, serial_numbers_list_validator\n\n\nclass MultiSeralNumberField(forms.Field):\n def to_python(self, value):\n \"\"\"Normalize data to a list of unique not empty strings.\"\"\"\n if not value:\n return []\n values_list = value.splitlines()\n unique_values = set(values_list)\n not_empty_values = [i for i in unique_values if i]\n return not_empty_values\n\n def validate(self, value):\n serial_numbers_not_registered_yet_validator(value)\n serial_numbers_list_length_validator(value)\n serial_numbers_list_validator(value)\n super().validate(value)\n\n\nclass CompensationForm(forms.ModelForm):\n devices = MultiSeralNumberField(widget=forms.Textarea)\n\n class Meta:\n model = CompensationBatch\n fields = ['partner', 'date', 'credit_note', 'currency', 'amount']\n\n widgets = {\n 'date': forms.DateInput(format=('%d/%m/%Y'),\n attrs={'class': 'form-control', 'placeholder': 'Select a date',\n 'type': 'date'}),\n }\n","sub_path":"pbsite/compensation/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"346871838","text":"import functools\n\ndef nim(array, n):\n answer = 0\n for x in range(len(array)):\n answer = answer ^ array[x] % 9 // 2\n if answer == 0:\n return 'Sandy'\n return 'Manasa'\n\ndef main():\n trials = int(input())\n for trial in range(trials):\n n = int(input())\n array = [int(x) for x in input().split()]\n print(nim(array, n))\n\nif __name__ == '__main__':\n main()","sub_path":"algorithms/game_theory/manasa_and_primes/manasa_and_primes.py","file_name":"manasa_and_primes.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"112070426","text":"import os\nimport mutagen\n\n\ndef __validate_track(full_path):\n \"\"\"Validates whether a file path is a valid piece of media for the library\"\"\"\n valid_extensions = ['flac', 'mp3']\n return os.path.splitext(full_path)[1].lower().lstrip('.') in valid_extensions\n\n\ndef __find_tracks(path):\n \"\"\"Find valid music files under a directory path\"\"\"\n valid_tracks = []\n raw_library = os.walk(path)\n for subdir in raw_library:\n if not subdir[2]:\n continue\n else:\n for file in subdir[2]:\n full_path = os.path.join(subdir[0], file)\n file_type = __validate_track(full_path)\n if file_type:\n t = Track(full_path)\n if t.valid:\n valid_tracks.append(t)\n\n return valid_tracks\n\n\ndef add_tracks_to_library(path):\n \"\"\"Parses information from found tracks and builds databases\"\"\"\n tracks = __find_tracks(path)\n track_db = TrackDatabase()\n album_db = AlbumDatabase()\n track_artist_db = ArtistDatabase()\n album_artist_db = ArtistDatabase()\n\n def _produce(artist_name):\n if artist_name in track_artist_db:\n return track_artist_db[artist_name]\n elif artist_name in album_artist_db:\n return album_artist_db[artist_name]\n else:\n return Artist(artist_name)\n\n for t in tracks:\n track_db[t.filename] = t\n try:\n album = album_db[t.album]\n except KeyError:\n album = Album(t.album)\n album_db[t.album] = album\n album.track_list.append(t.filename)\n track_artist = _produce(t.artist)\n track_artist_db[t.artist] = track_artist\n track_artist.album_list.add(album)\n album_artist = _produce(t.album_artist)\n album_artist_db[t.album_artist] = album_artist\n album_artist.album_list.add(album)\n\n return {'album_artists': album_artist_db, 'artists': track_artist_db, 'albums': album_db, 'tracks': track_db}\n\n\nclass Track:\n \"\"\"Base class for our song/track/what-have-you\"\"\"\n\n def __init__(self, filename=None):\n self.filename = filename\n self.artist = 'Unknown'\n self.album_artist = 'Unknown'\n self.album = 'Unknown'\n self.title = 'Unknown'\n self.genre = 'Unknown'\n self.tracknumber = '1'\n self.discnumber = '1'\n self.valid = False\n\n if filename:\n self.filetype = os.path.splitext(filename)[1].lower().lstrip('.')\n try:\n self.__attach_info()\n except InvalidInfoError:\n self.valid = False\n pass\n else:\n self.valid = True\n else:\n self.filetype = None\n\n def __repr__(self):\n text = ''\n track_attributes = []\n for item in dir(self):\n if item.startswith('_'):\n continue\n track_attributes.append(item)\n for attr in sorted(track_attributes):\n value = getattr(self, attr)\n if hasattr(value, '__call__'):\n continue\n text = text + '\\t' + attr + ': ' + str(value) + ' (' + str(type(value)) + ')' + '\\n'\n return text\n\n def __lt__(self, other):\n if self.artist.lower() < other.artist.lower():\n return True\n elif self.artist.lower() > other.artist.lower():\n return False\n else:\n if self.album.lower() < other.album.lower():\n return True\n elif self.album.lower() > other.album.lower():\n return False\n else:\n if int(self.discnumber) < int(other.discnumber):\n return True\n elif int(self.discnumber) > int(other.discnumber):\n return False\n else:\n if int(self.tracknumber) <= int(other.tracknumber):\n return True\n elif int(self.tracknumber) > int(other.tracknumber):\n return False\n\n def __attach_info_from_headers(self, mutagen_object):\n for key in mutagen_object:\n setattr(self, key, list(mutagen_object[key])[0])\n\n def __attach_info_from_stream_info(self, mutagen_object):\n for attr in dir(mutagen_object):\n if attr.startswith('__'):\n continue\n setattr(self, attr, getattr(mutagen_object, attr))\n\n def __ensure_artists(self):\n if self.album_artist == 'Unknown' and self.artist != 'Unknown':\n self.album_artist = self.artist\n elif self.artist == 'Unknown' and self.album_artist != 'Unknown':\n self.artist = self.album_artist\n else:\n self.artist = 'Unknown'\n self.album_artist = 'Unknown'\n\n def __split_number_pairs(self, number_attr):\n import re\n match_object = re.match(r'(\\d+)\\D(\\d+)', getattr(self, number_attr))\n if match_object:\n setattr(self, number_attr, match_object.group(1))\n\n def __attach_mp3_info(self):\n try:\n mutagen_id3 = mutagen.File(self.filename, easy=True)\n except mutagen.mp3.HeaderNotFoundError:\n # We should do something here, like log an error. Raise for now\n raise InvalidInfoError()\n else:\n self.__attach_info_from_headers(mutagen_id3)\n self.__split_number_pairs('tracknumber')\n self.__split_number_pairs('discnumber')\n self.tracknumber = self.tracknumber.lstrip('0') or '0'\n self.discnumber = self.discnumber.lstrip('0') or '0'\n\n try:\n mp3 = mutagen.mp3.MP3(self.filename)\n except mutagen.mp3.HeaderNotFoundError:\n # We should do something here, like log an error. Raise for now\n raise InvalidInfoError()\n else:\n self.__attach_info_from_stream_info(mp3.info)\n\n return None\n\n def __attach_flac_info(self):\n try:\n mutagen_object = mutagen.flac.FLAC(self.filename)\n except:\n # We should do something here, like log an error. Raise for now\n raise InvalidInfoError()\n else:\n self.__attach_info_from_headers(mutagen_object)\n self.__attach_info_from_stream_info(mutagen_object.info)\n self.tracknumber = self.tracknumber.lstrip('0') or '0'\n self.discnumber = self.discnumber.lstrip('0') or '0'\n\n def __attach_info(self):\n \"\"\"Fill out a track object given a filename\"\"\"\n info_funcs = {'mp3': self.__attach_mp3_info,\n 'flac': self.__attach_flac_info}\n info_funcs[self.filetype]()\n self.__ensure_artists()\n try:\n self.length\n except AttributeError:\n raise InvalidInfoError()\n else:\n m, s = divmod(int(self.length), 60)\n h, m = divmod(m, 60)\n if h:\n self.time_string = \"%d:%02d:%02d\" % (h, m, s)\n else:\n self.time_string = \"%d:%02d\" % (m, s)\n\n\n\nclass Album:\n \"\"\"List of track filenames with other attributes\"\"\"\n def __init__(self, name):\n self.title = name\n self.track_list = []\n\n def __str__(self):\n text = 'Album: ' + self.title + '\\n'\n try:\n for track in self.track_list:\n text = text + '\\t' + track + '\\n'\n except:\n text += '\\tNo tracks\\n'\n return text\n\n def __lt__(self, other):\n if self.title.lower() < other.title.lower():\n return True\n \n def add_track(self, track_filename):\n self.track_list.append(track_filename)\n\n def remove_track(self, track_filename):\n self.track_list.remove(track_filename)\n\n\nclass Artist:\n \"\"\"List of Albums with other attributes\"\"\"\n def __init__(self, name):\n self.name = name\n self.album_list = set()\n\n def __str__(self):\n text = 'Artist ' + self.name + ' appears on albums:\\n'\n try:\n for album in self.album_list:\n text = text + '\\t' + album.name + '\\n'\n except:\n text += '\\tNo tracks\\n'\n return text\n\n def __lt__(self, other):\n if self.name.lower() < other.name.lower():\n return True\n \n def add_album(self, album):\n self.album_list.add(album)\n\n def remove_album(self, album):\n self.album_list.remove(album)\n\n\nclass TrackDatabase(dict):\n \"\"\"One-to-one filename to track object database dictionary.\"\"\"\n def __init__(self):\n super().__init__()\n\n\nclass AlbumDatabase(dict):\n \"\"\"One-to-one Album name to album object database dictionary.\"\"\"\n def __init__(self):\n super().__init__()\n\n\nclass ArtistDatabase(dict):\n \"\"\"One-to-one filename to track object database dictionary.\"\"\"\n def __init__(self):\n super().__init__()\n\n\nclass InvalidInfoError(Exception): pass\n","sub_path":"library.py","file_name":"library.py","file_ext":"py","file_size_in_byte":8907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"559804262","text":"import tensorflow as tf\n\nfrom config import cfg\n\n\nclass CapsConv(object):\n def __init__(self, num_units, with_routing=True):\n ''' Capsule convolution.\n Args:\n num_units: the length of the output vector of a capsule.\n '''\n self.num_units = num_units\n self.with_routing = with_routing\n\n def __call__(self, input, num_outputs, kernel_size=None, strides=None):\n self.num_outputs = num_outputs\n self.kernel_size = kernel_size\n self.strides = strides\n\n if self.with_routing:\n # the DigitCaps layer\n # Reshape the input into shape [batch_size, 1152, 8, 1]\n self.input = tf.reshape(input, shape=(cfg.batch_size, 1152, 8, 1))\n capsules = [Capsule() for i in range(self.num_outputs)]\n capsules = [capsules[i](input) for i in range(self.num_outputs)]\n\n # Return a tensor with shape [batch_size, 10, 16, 1]\n capsules = tf.concat(capsules, axis=1)\n return(capsules)\n else:\n # the PrimaryCaps layer\n pass\n\n\nclass Capsule(object):\n ''' The routing algorithm.\n Args:\n input: A Tensor with shape [batch_size, num_caps, length(u_i), 1]\n\n Returns:\n A Tensor of shape [batch_size, 1, length(v_j), 1] representing the\n vector output `v_j` of capsule j\n Notes:\n u_i represents the vector output of capsule i in the layer l, and\n v_j the vector output of capsule j in the layer l+1.\n '''\n\n def __init__(self):\n # [batch_size, 32x6x6, 8]\n with tf.variable_scope('routing'):\n self.W_ij = tf.get_variable('w_ij', shape=(1, 1152, 16, 8))\n self.b_ij = tf.get_variable('b_ij', shape=(1, 1152, 1, 1))\n\n def __call__(self, input):\n '''\n Args:\n input: shape [batch_size, 1152, 8, 1]\n Returns:\n shape [batch_size, 1, 16, 1]\n '''\n self.input = input\n for r_iter in cfg.iter_routing:\n # line 4:\n # [1, 1152, 1, 1]\n c_i = tf.nn.softmax(self.b_ij, dim=1)\n\n # line 5:\n # [16, 8] x [8, 1] => [batch_size, 1152, 16, 1]\n u_hat = tf.matmul(self.W_ij.T, self.input)\n # weighting u_hat with c_i in the third dim,\n # then sum in the second dim, resulting in [batch_size, 1, 16, 1]\n s_j = tf.reduce_sum(tf.multipy(c_i, u_hat))\n\n # line 6:\n # squash using Eq.1, resulting in [batch_size, 1, 16, 1]\n s_abs = tf.abs(s_j)\n scalar_factor = tf.square(s_abs) / (1 + tf.square(s_abs))\n v_j = scalar_factor * tf.divide(s_j, s_abs)\n # line 7:\n # [1152, 16] x [16, 1] => [1152, 1], then reduce mean in the\n # batch_size dim, resulting in [1, 1152, 1, 1]\n u_produce_v = tf.matmul(u_hat, v_j)\n self.b_ij = self.b_ij + u_produce_v\n\n return(v_j)\n","sub_path":"capsLayer.py","file_name":"capsLayer.py","file_ext":"py","file_size_in_byte":2955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"66838142","text":"#!/usr/bin/env python\n# -----------------------------------------------------------------------------\n# Project : Pamela\n# -----------------------------------------------------------------------------\n# Author : Sebastien Pierre \n# License : Lesser GNU Public License\n# -----------------------------------------------------------------------------\n# Creation date : 10-May-2007\n# Last mod. : 10-Nov-2015\n# -----------------------------------------------------------------------------\n\nimport os, sys, re, string, json, time\nIS_PYTHON3 = sys.version_info[0] > 2\n\ntry:\n\timport reporter as logging\nexcept:\n\timport logging\n\n__version__ = \"0.7.0\"\nPAMELA_VERSION = __version__\n\n# TODO: Add an option to start a sugar compilation server and directly query\n# it, maybe using ZMQ.\n\ndef ensure_unicode( t, encoding=\"utf8\" ):\n\tif IS_PYTHON3:\n\t\treturn t if isinstance(t, str) else str(t, encoding)\n\telse:\n\t\treturn t if isinstance(t, unicode) else t.decode(encoding)\n\ndef ensure_bytes( t, encoding=\"utf8\" ):\n\tif IS_PYTHON3:\n\t\treturn t if isinstance(t, bytes) else bytes(t, encoding)\n\telse:\n\t\treturn t\n\n# -----------------------------------------------------------------------------\n#\n# GRAMMAR\n#\n# -----------------------------------------------------------------------------\n\nSYMBOL_NAME = \"\\??([\\w\\d_-]+::)?[\\w\\d_-]+\"\nSYMBOL_ID_CLS = \"(\\#%s|\\.%s)+\" % (SYMBOL_NAME, SYMBOL_NAME)\nSYMBOL_ATTR = \"(%s)(=('[^']+'|\\\"[^\\\"]+\\\"|([^),]+)))?\" % (SYMBOL_NAME)\nSYMBOL_ATTRS = \"\\(%s(,%s)*\\)\" % (SYMBOL_ATTR, SYMBOL_ATTR)\nSYMBOL_CONTENT = \"@\\w[\\w\\d\\-_\\+]*\"\nSYMBOL_ELEMENT = \"<(%s(%s)?|%s)(%s)?(%s)?\\:?\" % (\n\tSYMBOL_NAME,\n\tSYMBOL_ID_CLS,\n\tSYMBOL_ID_CLS,\n\tSYMBOL_ATTRS,\n\tSYMBOL_CONTENT\n)\nRE_ATTRIBUTE = re.compile(SYMBOL_ATTR)\nRE_COMMENT = re.compile(\"^#.*$\")\nRE_EMPTY = re.compile(\"^\\s*$\")\nRE_DECLARATION = re.compile(\"^@(%s):?\" % (SYMBOL_NAME))\nRE_ELEMENT = re.compile(\"^%s\" % (SYMBOL_ELEMENT))\nRE_INLINE = re.compile(\"%s\" % (SYMBOL_ELEMENT))\nRE_INCLUDE = re.compile(\"^(\\s)*%include (.+)$\")\nRE_LEADING_TAB = re.compile(\"\\t*\")\nRE_LEADING_SPC = re.compile(\"[ ]*\")\nRE_SPACE = re.compile(\"[\\s\\n]\")\n\nT_ELEMENT = \"EL\"\nT_DECLARATION = \"DC\"\nT_EMBED = \"EM\"\n\n# -----------------------------------------------------------------------------\n#\n# FORMATTING\n#\n# -----------------------------------------------------------------------------\n\n# FIXME: This does not work. What we should have is\n# - compact: no leading or trailing whitepsace\nFORMAT_INLINE = \"i\"\nFORMAT_INLINE_BLOCK = \"ib\"\nFORMAT_SINGLE_LINE = \"sl\"\nFORMAT_PRESERVE = \"p\"\nFORMAT_NORMALIZE = \"n\"\nFORMAT_STRIP = \"s\"\nFORMAT_COMPACT = \"c\"\nFORMAT_WRAP = \"w\"\nFORMAT_OPTIONS = (\n\tFORMAT_INLINE,\n\tFORMAT_INLINE_BLOCK,\n\tFORMAT_SINGLE_LINE,\n\tFORMAT_PRESERVE,\n\tFORMAT_NORMALIZE,\n\tFORMAT_STRIP,\n\tFORMAT_COMPACT,\n)\n\n# Defaults for HTML documents\nHTML_DEFAULTS = {\n\t\"script\":\"i\".split(),\n\t\"link\":\"i\".split(),\n\t\"title\":\"sl n s\".split(),\n\t\"h1\":\"sl n s\".split(),\n\t\"h2\":\"sl n s\".split(),\n\t\"h3\":\"sl n s\".split(),\n\t\"h4\":\"sl n s\".split(),\n\t\"p\":\"n s c w\".split(),\n\t\"code\":\"n s c\".split(),\n\t\"pre\":\"p\".split(),\n\t\"div\":\"ib\".split()\n}\n\nHTML_EXCEPTIONS = {\n\t\"links\":dict(NO_CLOSING=True),\n\t\"br\" :dict(NO_CLOSING=True),\n\t\"img\" :dict(NO_CLOSING=True),\n\t\"path\" :dict(NO_CLOSING=True),\n\t\"ol\":{\n\t\t\"NOT_EMPTY\":\" \"\n\t},\n\t\"ul\":{\n\t\t\"NOT_EMPTY\":\" \"\n\t},\n\t\"a\":{\n\t\t\"NOT_EMPTY\":\" \"\n\t},\n\t\"script\":{\n\t\t\"NOT_EMPTY\":\" \"\n\t},\n\t\"span\":{\n\t\t\"NOT_EMPTY\":\" \"\n\t},\n\t\"li\":{\n\t\t\"NOT_EMPTY\":\"\"\n\t},\n\t\"canvas\":{\n\t\t\"NOT_EMPTY\":\" \"\n\t},\n\t\"textarea\":{\n\t\t\"NOT_EMPTY\":\" \"\n\t},\n\t\"iframe\":{\n\t\t\"NOT_EMPTY\":\" \"\n\t},\n\t\"div\":{\n\t\t\"NOT_EMPTY\":\" \"\n\t},\n\t\"td\":{\n\t\t\"NOT_EMPTY\":\" \"\n\t},\n\t\"th\":{\n\t\t\"NOT_EMPTY\":\" \"\n\t}\n}\n\n# -----------------------------------------------------------------------------\n#\n# OBJECT MODEL\n#\n# -----------------------------------------------------------------------------\n\nclass Text:\n\t\"\"\"Reprensents a text fragment within the HTML document.\"\"\"\n\tdef __init__(self, content):\n\t\tself.content = content\n\n\tdef contentAsLines( self ):\n\t\treturn [self.content]\n\nclass Element:\n\t\"\"\"Represents an element within the HTML document.\"\"\"\n\n\tdef __init__(self, name, attributes=None,isInline=False,isPI=False):\n\t\tself.name = name\n\t\tself.attributes = attributes or []\n\t\tself.content = []\n\t\tself.isInline = isInline\n\t\tself.mode = None\n\t\tself.isPI = isPI\n\t\tself.formatOptions = []\n\t\tif name[0] == \"?\":\n\t\t\tself.isPI = True\n\t\t\tself.name = name[1:]\n\n\tdef setMode( self, mode):\n\t\tself.mode = mode\n\n\tdef append(self,n):\n\t\tself.content.append(n)\n\n\tdef isTextOnly( self ):\n\t\tif len(self.content) == 0:\n\t\t\treturn True\n\t\telif len(self.content) == 1 and isinstance(self.content[0], Text) and self.content[0].content.find(\"\\n\") == -1:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef contentAsLines( self ):\n\t\tres = []\n\t\tfor e in self.content:\n\t\t\tif type(e) in (str,str):\n\t\t\t\tres.append(e)\n\t\t\telse:\n\t\t\t\tres.extend(e.contentAsLines())\n\t\treturn res\n\n\tdef _attributesAsHTML(self):\n\t\t\"\"\"Returns the attributes as HTML\"\"\"\n\t\tr = []\n\t\tdef escape(v):\n\t\t\tif v.find('\"') == -1: v = '\"%s\"' % (v)\n\t\t\telif v.find(\"'\") == -1: v = \"'%s'\" % (v)\n\t\t\telse: v = '\"%s\"' % (v.replace('\"', '\\\\\"'))\n\t\t\treturn v\n\t\tfor name, value in self.attributes:\n\t\t\tif value is None:\n\t\t\t\tr.append(\"%s\" % (name))\n\t\t\telse:\n\t\t\t\tr.append(\"%s=%s\" % (name,escape(value)))\n\t\tr = \" \".join(r)\n\t\tif r: r= \" \"+r\n\t\treturn r\n\nclass Declaration(Element):\n\tdef __init__(self, name, attributes=None):\n\t\tElement.__init__(self,name,attributes)\n\n# -----------------------------------------------------------------------------\n#\n# FORMATTING FUNCTION (BORROWED FROM LAMBDAFACTORY MODELWRITER MODULE)\n#\n# -----------------------------------------------------------------------------\n\nRE_SPACES = re.compile(\"\\s\")\n\nclass Formatter:\n\t\"\"\"Formats the elements of the Pamela object model. A formatter really acts\n\tas a state machine, and keeps track of the various formatting hints bound to\n\tthe Pamela XML/HTML elements to render the document in the most appropriate\n\tway.\n\n\tIf you instanciate a formatter, you'll have access to the following\n\tattributes, which can influence the generated text:\n\n\t - 'indent=0'\n\t - 'indentValue=\" \"'\n\t - 'textWidth=80'\n\t - 'defaults=HTML_DEFAULT'\n\n\t\"\"\"\n\n\tdef __init__( self ):\n\t\t\"\"\"Creates a new formatter.\"\"\"\n\t\tself.indent = 0\n\t\tself.indentValue = \" \"\n\t\tself.textWidth = 80\n\t\t# FIXME\n\t\tself.defaults = {}\n\t\tself.defaults = HTML_DEFAULTS\n\t\tself.flags = [[]]\n\t\tself.useProcessCache = True\n\n\tdef setDefaults( self, element, formatOptions=()):\n\t\t\"\"\"Sets the formatting defaults for the given element name.\"\"\"\n\t\tassert type(element) in (str, str)\n\t\tassert type(formatOptions) in (list, tuple)\n\t\tfor f in formatOptions:\n\t\t\tassert f in FORMAT_OPTIONS, \"Unknown formatting option: %s\" % (f)\n\t\tself.defaults[element] = list(formatOptions)\n\n\tdef getDefaults( self, elementName ):\n\t\t\"\"\"Gets the formatting defaults for the given element name.\"\"\"\n\t\treturn self.defaults.get(elementName) or ()\n\n\tdef pushFlags( self, *flags ):\n\t\t\"\"\"Pushes the given flags (as varargs) on the flags queue.\"\"\"\n\t\tself.flags.append([])\n\t\tfor _ in flags: self.setFlag(_)\n\n\tdef setFlag( self, flag ):\n\t\t\"\"\"Sets the given flag.\"\"\"\n\t\tif flag == FORMAT_SINGLE_LINE:\n\t\t\tself.setFlags(FORMAT_STRIP, FORMAT_NORMALIZE)\n\t\tif flag not in self.flags[-1]:\n\t\t\tself.flags[-1].append(flag)\n\n\tdef setFlags( self, *flags ):\n\t\t\"\"\"Set the given flags, given as varargs.\"\"\"\n\t\tfor _ in flags: self.setFlag(_)\n\n\tdef popFlags( self ):\n\t\t\"\"\"Pops the given flags from the flags queue.\"\"\"\n\t\tself.flags.pop()\n\n\tdef hasFlag( self, flag ):\n\t\t\"\"\"Tells if the given flag is currently defined.\"\"\"\n\t\tif flag == FORMAT_SINGLE_LINE:\n\t\t\tsingle_line = self.findFlag(flag)\n\t\t\tpreserve = self.findFlag(FORMAT_PRESERVE)\n\t\t\tif single_line > preserve: return True\n\t\t\telse: return False\n\t\telse:\n\t\t\treturn self.findFlag(flag) != -1\n\n\tdef getFlags( self ):\n\t\t\"\"\"Returns the list of defined flags, by order of definition (last flags\n\t\tare more recent.\"\"\"\n\t\tres = []\n\t\tfor flags in self.flags:\n\t\t\tres.extend(flags)\n\t\treturn res\n\n\tdef findFlag( self, flag ):\n\t\t\"\"\"Finds the level at which the given flag is defined. Returns -1 if it\n\t\tis not found.\"\"\"\n\t\tfor i in range(0, len(self.flags)):\n\t\t\tj = len(self.flags) - 1 - i\n\t\t\tif flag in self.flags[j]:\n\t\t\t\treturn j\n\t\treturn -1\n\n\t# -------------------------------------------------------------------------\n\t# MAIN FORMATTING OPERATIONS\n\t# -------------------------------------------------------------------------\n\n\tdef format( self, document, indent=0 ):\n\t\t\"\"\"Formats the given document, starting at the given indentation (0 by\n\t\tdefault).\"\"\"\n\t\tself.startWriting()\n\t\tself.indent = indent\n\t\tself._formatContent(document)\n\t\treturn self.endWriting()\n\n\tdef _formatContent( self, element ):\n\t\t\"\"\"Formats the content of the given element. This uses the formatting\n\t\toperations defined in this class.\"\"\"\n\t\ttext = []\n\t\t# NOTE: In this process we aggregate text elements, which are typically\n\t\t# one text element per line. This allows proper formatting\n\t\tfor e in element.content:\n\t\t\tif isinstance(e, Element):\n\t\t\t\tif text:\n\t\t\t\t\tself.writeText(\"\".join(text))\n\t\t\t\t\ttext = []\n\t\t\t\tself._formatElement(e)\n\t\t\telif isinstance(e, Text):\n\t\t\t\ttext.append(e.content)\n\t\t\telse:\n\t\t\t\traise Exception(\"Unsupported content type: %s\" % (e))\n\t\tif text:\n\t\t\t#text = \"\".join(map(lambda _:_.encode(\"utf-8\"), text))\n\t\t\ttext = \"\".join(text)\n\t\t\tif not element.isInline:\n\t\t\t\twhile text and text[-1] in \"\\n\\t \": text = text[:-1]\n\t\t\tself.writeText(text)\n\n\tdef _inlineCanSpanOneLine( self, element ):\n\t\t\"\"\"Tells wether the given element (when considered as an inline) can\n\t\tspan one single line. It can if only it has inlines that can span\n\t\tone line and text without EOLs as content.\"\"\"\n\t\tif isinstance(element, Text):\n\t\t\treturn element.content.find(\"\\n\") == -1\n\t\telse:\n\t\t\tfor c in element.content:\n\t\t\t\tif not self._inlineCanSpanOneLine(c):\n\t\t\t\t\treturn False\n\t\t\treturn True\n\n\tdef _formatElement( self, element ):\n\t\t\"\"\"Formats the given element and its content, by using the formatting\n\t\toperations defined in this class.\"\"\"\n\t\tattributes = element._attributesAsHTML()\n\t\texceptions = HTML_EXCEPTIONS.get(element.name)\n\t\tcontent = element.content\n\t\t# FIXME: Flags are not properly supported\n\t\tif exceptions:\n\t\t\tnot_empty = exceptions.get(\"NOT_EMPTY\")\n\t\t\tif not_empty != None and not content:\n\t\t\t\telement.content.append(Text(not_empty))\n\t\t# Does this element has any content ?\n\t\tif element.mode and element.mode.startswith(\"sugar\"):\n\t\t\tlines = element.contentAsLines()\n\t\t\timport pamela.web\n\t\t\tsource = u\"\".join(lines)\n\t\t\tt = time.time()\n\t\t\tres, _ = pamela.web.processSugar(source, \"\", cache=self.useProcessCache, includeSource=element.mode.endswith(\"+source\"))\n\t\t\tlogging.info(\"Parsed Sugar: {0} lines in {1:0.2f}s\".format(len(lines), time.time() - t))\n\t\t\telement.content = [Text(res)]\n\t\telif element.mode in (\"coffeescript\", \"coffee\"):\n\t\t\tlines = element.contentAsLines()\n\t\t\timport pamela.web\n\t\t\tsource = u\"\".join(lines)\n\t\t\tt = time.time()\n\t\t\tres, _ = pamela.web.processCoffeeScript(source, \"\", cache=self.useProcessCacheFalse)\n\t\t\tlogging.info(\"Parsed CoffeeScript: {0} lines in {1:0.2f}s\".format(len(lines), time.time() - t))\n\t\t\telement.content = [Text(res)]\n\t\telif element.mode in (\"typescript\", \"ts\"):\n\t\t\tlines = element.contentAsLines()\n\t\t\timport pamela.web\n\t\t\tsource = u\"\".join(lines)\n\t\t\tt = time.time()\n\t\t\tres, _ = pamela.web.processTypeScript(source, \"\", cache=self.useProcessCacheFalse)\n\t\t\tlogging.info(\"Parsed TypeScript: {0} lines in {1:0.2f}s\".format(len(lines), time.time() - t))\n\t\t\telement.content = [Text(res)]\n\t\telif element.mode in (\"clevercss\", \"ccss\"):\n\t\t\tlines = element.contentAsLines()\n\t\t\timport pamela.web\n\t\t\tsource = u\"\".join(lines)\n\t\t\tt = time.time()\n\t\t\tres, _ = pamela.web.processCleverCSS(source, \".\")\n\t\t\tlogging.info(\"Parsed CleverCSS: {0} lines in {1:0.2f}s\".format(len(lines), time.time() - t))\n\t\t\telement.content = [Text(res)]\n\t\telif element.mode in (\"pythoniccss\", \"pcss\"):\n\t\t\tlines = element.contentAsLines()\n\t\t\timport pamela.web\n\t\t\tsource = u\"\".join(lines)\n\t\t\tt = time.time()\n\t\t\tres, _ = pamela.web.processPythonicCSS(source, \".\")\n\t\t\tlogging.info(\"Parsed PythonicCSS: {0} lines in {1:0.2f}s\".format(len(lines), time.time() - t))\n\t\t\telement.content = [Text(res)]\n\t\telif element.mode == \"texto\":\n\t\t\tlines = element.contentAsLines()\n\t\t\timport texto\n\t\t\tsource = u\"\".join(lines)\n\t\t\tres = ensure_unicode(texto.toHTML(source))\n\t\t\telement.content = [Text(res)]\n\t\tif element.content:\n\t\t\tself.pushFlags(*self.getDefaults(element.name))\n\t\t\tif element.isPI:\n\t\t\t\tassert not attributes, \"Processing instruction cannot have attributes\"\n\t\t\t\tstart = \"\"\n\t\t\telse:\n\t\t\t\tstart = \"<%s%s>\" % (element.name, attributes)\n\t\t\t\tend = \"\" % (element.name)\n\t\t\tif self.hasFlag(FORMAT_INLINE):\n\t\t\t\tif self._inlineCanSpanOneLine(element):\n\t\t\t\t\tself.setFlag(FORMAT_SINGLE_LINE)\n\t\t\t# If the element is an inline, we enter the SINGLE_LINE formatting\n\t\t\t# mode, without adding an new line\n\t\t\t# FIXME: isInline is wlaways false\n\t\t\tif element.isInline:\n\t\t\t\tself.pushFlags(FORMAT_SINGLE_LINE)\n\t\t\t\tself.writeTag(start)\n\t\t\t\tself._formatContent(element)\n\t\t\t\tself.writeTag(end)\n\t\t\t\tself.popFlags()\n\t\t\t# Or maybe the element has a SINGLE_LINE flag, in which case we add a\n\t\t\t# newline inbetween\n\t\t\telif self.hasFlag(FORMAT_SINGLE_LINE) or element.isTextOnly():\n\t\t\t\tself.newLine()\n\t\t\t\tself.writeTag(start)\n\t\t\t\tself._formatContent(element)\n\t\t\t\tself.writeTag(end)\n\t\t\t# Otherwise it's a normal open/closed element\n\t\t\telse:\n\t\t\t\tself.newLine()\n\t\t\t\tself.writeTag(start)\n\t\t\t\tself.newLine()\n\t\t\t\tself.startIndent()\n\t\t\t\tself._formatContent(element)\n\t\t\t\tself.endIndent()\n\t\t\t\tself.ensureNewLine()\n\t\t\t\tself.writeTag(end)\n\t\t\tself.popFlags()\n\t\t# Otherwise it doesn't have any content\n\t\telse:\n\t\t\tif exceptions and exceptions.get(\"NO_CLOSING\"):\n\t\t\t\ttext = \"<%s%s>\" % (element.name, attributes)\n\t\t\telse:\n\t\t\t\ttext = \"<%s%s />\" % (element.name, attributes)\n\t\t\t# And if it's an inline, we don't add a newline\n\t\t\tif not element.isInline: self.newLine()\n\t\t\tself.writeTag(text)\n\n\tdef formatText( self, text ):\n\t\t\"\"\"Returns the given text properly formatted according to\n\t\tthis formatted configuration.\"\"\"\n\t\tif not self.hasFlag(FORMAT_PRESERVE):\n\t\t\tif self.hasFlag(FORMAT_NORMALIZE):\n\t\t\t\ttext = self.normalizeText(text)\n\t\t\tif self.hasFlag(FORMAT_STRIP):\n\t\t\t\ttext = self.stripText(text)\n\t\t\tif not self.hasFlag(FORMAT_SINGLE_LINE):\n\t\t\t\tcompact = self.hasFlag(FORMAT_COMPACT)\n\t\t\t\ttext = self.indentString(text, start=not compact, end=not compact)\n\t\treturn text\n\n\t# -------------------------------------------------------------------------\n\t# TEXT OUTPUT COMMANDS\n\t# -------------------------------------------------------------------------\n\n\tdef _isNewLine( self ):\n\t\t\"\"\"Tells wether the current line is a new line.\"\"\"\n\t\tif not self._result or not self._result[-1]: return False\n\t\treturn not self._result or self._result[-1][-1] == \"\\n\"\n\n\tdef _ensureNewLine( self ):\n\t\t\"\"\"Ensures that there is a new line.\"\"\"\n\t\tif not self._isNewLine():\n\t\t\tif not self._result:\n\t\t\t\tself._result.append(\"\")\n\t\t\telse:\n\t\t\t\tself._result[-1] = self._result[-1] + \"\\n\"\n\n\tdef startWriting( self ):\n\t\tself._result = []\n\n\tdef startIndent( self ):\n\t\tself.indent += 1\n\n\tdef endIndent( self ):\n\t\tassert self.indent > 0\n\t\tself.indent -= 1\n\t\tself._ensureNewLine()\n\n\tdef newLine( self ):\n\t\tself._ensureNewLine()\n\n\tdef ensureNewLine( self ):\n\t\tself._ensureNewLine()\n\n\tdef writeTag( self, tagText ):\n\t\tif self._isNewLine():\n\t\t\tself._result.append(self.indentAsSpaces() + tagText)\n\t\telse:\n\t\t\tself._result[-1] = self._result[-1] + tagText\n\n\tdef writeText( self, text ):\n\t\tresult = self._result\n\t\tif self.hasFlag(FORMAT_PRESERVE):\n\t\t\t#print \"APPEND \",repr(text)\n\t\t\tresult.append(text)\n\t\telse:\n\t\t\tif self._isNewLine():\n\t\t\t\tif self.hasFlag(FORMAT_WRAP):\n\t\t\t\t\t#print \"WRAP \",repr(self.wrapText(text))\n\t\t\t\t\tresult.append(self.wrapText(text))\n\t\t\t\telse:\n\t\t\t\t\t#print \"INDENT \",repr(self.indentAsSpaces() + text)\n\t\t\t\t\tresult.append( self.indentAsSpaces() + text)\n\t\t\telif result:\n\t\t\t\toffset = len(result[-1])\n\t\t\t\tif self.hasFlag(FORMAT_WRAP):\n\t\t\t\t\t#print \"APPEND WRAP \",repr(self.wrapText(text, len(result[-1])))\n\t\t\t\t\tresult[-1] = result[-1] + self.wrapText(text, len(result[-1]))\n\t\t\t\telse:\n\t\t\t\t\t#print \"APPEND \",repr(text)\n\t\t\t\t\tresult[-1] = result[-1] + text\n\t\t\telse:\n\t\t\t\tif self.hasFlag(FORMAT_WRAP):\n\t\t\t\t\tresult.append(self.wrapText(text, len(result[-1])))\n\t\t\t\telse:\n\t\t\t\t\tresult.append(text)\n\n\tdef endWriting( self ):\n\t\tres = \"\".join(self._result)\n\t\tdel self._result\n\t\treturn res\n\n\tdef _iterateOnWords( self, text ):\n\t\t\"\"\"Splits the given text into words (separated by ' ', '\\t' or '\\n') and\n\t\treturns an iterator on these words.\n\n\t\tThis function is used by 'wrapText'.\"\"\"\n\t\toffset = 0\n\t\tspace = None\n\t\tinline = None\n\t\twhile offset < len(text):\n\t\t\tspace = RE_SPACE.search(text, offset)\n\t\t\tinline = RE_INLINE.search(text, offset)\n\t\t\tif space:\n\t\t\t\tif inline and inline.start() < space.start():\n\t\t\t\t\tend = text.find(\">\", inline.end()) + 1\n\t\t\t\t\tyield text[offset:end]\n\t\t\t\t\toffset = end\n\t\t\t\telse:\n\t\t\t\t\tyield text[offset:space.start()]\n\t\t\t\t\toffset = space.end()\n\t\t\telse:\n\t\t\t\tyield text[offset:]\n\t\t\t\toffset = len(text)\n\t\tif space and space.end() == len(text) \\\n\t\tor inline and inline.end() == len(text):\n\t\t\tyield \"\"\n\n\tdef wrapText( self, text, offset=0, textWidth=80, indent=None ):\n\t\t\"\"\"Wraps the given text at the given 'textWidth', starting at the given\n\t\t'offset' with the given optional 'ident'.\"\"\"\n\t\twords = []\n\t\tfor word in self._iterateOnWords(text):\n\t\t\twords.append(word)\n\t\treturn \" \".join(words)\n\n\t# -------------------------------------------------------------------------\n\t# TEXT MANIPULATION OPERATIONS\n\t# -------------------------------------------------------------------------\n\n\tdef indentString( self, text, indent=None, start=True, end=False ):\n\t\t\"\"\"Indents the given 'text' with the given 'value' (which will be\n\t\tconverted to either spaces or tabs, depending on the formatter\n\t\tparameters.\n\n\t\tIf 'start' is True, then the start line will be indented as well,\n\t\totherwise it won't. When 'end' is True, a newline is inserted at\n\t\tthe end of the resulting text, otherwise not.\"\"\"\n\t\tif indent is None: indent = self.indent\n\t\tfirst_line = True\n\t\tresult = []\n\t\tprefix = self.indentAsSpaces(indent)\n\t\tlines = text.split(\"\\n\")\n\t\tline_i = 0\n\t\tfor line in lines:\n\t\t\tif not line and line_i == len(lines)-1:\n\t\t\t\tcontinue\n\t\t\tif first_line and not start:\n\t\t\t\tresult.append(line)\n\t\t\telse:\n\t\t\t\tresult.append(prefix + line)\n\t\t\tfirst_line = False\n\t\t\tline_i += 1\n\t\tresult = \"\\n\".join(result)\n\t\tif end: result += \"\\n\"\n\t\treturn result\n\n\tdef indentAsSpaces( self, indent=None, increment=0 ):\n\t\t\"\"\"Converts the 'indent' value to a string filled with spaces or tabs\n\t\tdepending on the formatter parameters.\"\"\"\n\t\tif indent is None: indent = self.indent\n\t\treturn self.indentValue * (indent + increment)\n\n\tdef normalizeText( self, text ):\n\t\t\"\"\"Replaces the tabs and eols by spaces, ignoring the value of tabs.\"\"\"\n\t\treturn RE_SPACES.sub(\" \", text)\n\n\tdef stripText( self, text ):\n\t\t\"\"\"Strips leading and trailing spaces or eols from this text\"\"\"\n\t\twhile text and text[0] in '\\t\\n ':\n\t\t\ttext = text[1:]\n\t\twhile text and text[-1] in '\\t\\n ':\n\t\t\ttext = text[:-1]\n\t\treturn text\n\n\tdef reformatText( self, text ):\n\t\t\"\"\"Reformats a text so that it fits a particular text width.\"\"\"\n\t\treturn text\n\n# -----------------------------------------------------------------------------\n#\n# JAVASCRIPT HTML FORMATTER\n#\n# -----------------------------------------------------------------------------\n\nclass JSHTMLFormatter( Formatter ):\n\t\"\"\"Formats the given Pamela document to a JavaScript source code\n\tusing the 'html.js' markup file.\"\"\"\n\n\tdef format( self, document, indent=0 ):\n\t\telements = [v for v in document.content if isinstance(v, Element)]\n\t\tassert len(elements) == len(document.content) == 1, \"JSHTMLFormatter can only be used with one element\"\n\t\treturn self._formatContent(elements[0])\n\n\tdef _formatContent( self, value ):\n\t\t\"\"\"Formats the content of the given element. This uses the formatting\n\t\toperations defined in this class.\"\"\"\n\t\t# FIXME: Should escape entities\n\t\tif isinstance( value, Text ):\n\t\t\treturn json.dumps(value.content)\n\t\telif isinstance( value, Element ):\n\t\t\telement = value\n\t\t\tif element.isPI: return \"\"\n\t\t\tres = [\"html.%s(\" % (element.name)]\n\t\t\tcnt = []\n\t\t\tif element.attributes:\n\t\t\t\tattr = []\n\t\t\t\tfor name, value in element.attributes:\n\t\t\t\t\tattr.append(\"%s:%s\" % (json.dumps(name), json.dumps(value)))\n\t\t\t\tcnt.append(\"{%s}\" % (\",\".join(attr)))\n\t\t\tfor child in element.content:\n\t\t\t\tcnt.append(self._formatContent(child))\n\t\t\tres.append(\",\".join(cnt))\n\t\t\tres.append(\")\")\n\t\t\treturn \"\".join(res)\n\t\telse:\n\t\t\tassert None, \"Unrecognized value type: \" + str(value)\n\n# -----------------------------------------------------------------------------\n#\n# WRITER CLASS\n#\n# -----------------------------------------------------------------------------\n\nclass Writer:\n\t\"\"\"The Writer class implements a simple SAX-like interface to create the\n\tresulting HTML/XML document. This is not API-compatible with SAX because\n\tPamela has slightly different information than what SAX offers, which requires\n\tspecific methods.\"\"\"\n\n\tdef __init__( self ):\n\t\tself.onDocumentStart()\n\n\tdef onDocumentStart( self ):\n\t\tself._modes = []\n\t\tself._content = []\n\t\tself._nodeStack = []\n\t\tself._document = Element(\"document\")\n\t\tself._override = None\n\t\tself._bemStack = []\n\n\tdef onDocumentEnd( self ):\n\t\treturn self._document\n\n\tdef onComment( self, line ):\n\t\tline = line.replace(\"\\n\", \" \").strip()\n\t\t# FIXME: Why is this disabled ?\n\t\t#comment = ET.Comment(line)\n\t\t#self._node().append(comment)\n\n\tdef onTextAdd( self, text ):\n\t\t\"\"\"Adds the given text fragment to the current element.\"\"\"\n\t\tself._node().append(Text(text))\n\n\tdef onElementStart( self, name, attributes=None,isInline=False ):\n\t\t# We extend the override if present\n\t\tif self._override:\n\t\t\t# FIXME: This would be much more elegant with an ordered key-value\n\t\t\t# pair set\n\t\t\tkeys = []\n\t\t\tclass_override = None\n\t\t\t# We look for the 'class' attribute, if any\n\t\t\tfor item in self._override:\n\t\t\t\tif item[0] == \"class\": class_override = item\n\t\t\t\tkeys.append(item[0])\n\t\t\t# We now add all the attributes not overridden\n\t\t\tfor key, value in attributes:\n\t\t\t\tif key not in keys:\n\t\t\t\t\tself._override.append([key,value])\n\t\t\t\t# We merge the class attribute if present\n\t\t\t\telif key == \"class\":\n\t\t\t\t\tif class_override[1]:\n\t\t\t\t\t\tclass_override[1] += \" \" + value\n\t\t\t\t\telse:\n\t\t\t\t\t\tclass_override[1] = value\n\t\t\tattributes = self._override\n\t\t# We expand BEM class attributes\n\t\t# NOTE: I'm implementing it so that it can manage multiple prefixes,\n\t\t# but I'm not sure if it's going to be actually useful.\n\t\tnew_attributes = []\n\t\tbem_prefixes = []\n\t\tfor attr in attributes:\n\t\t\tif attr[0] != \"class\":\n\t\t\t\tnew_attributes.append(attr)\n\t\t\t\tcontinue\n\t\t\tclass_attributes = attr[1].split()\n\t\t\tvalue = []\n\t\t\tfor i,_ in enumerate(class_attributes):\n\t\t\t\tif _.endswith(\"-\"):\n\t\t\t\t\tbem_prefixes.append(_[0:-1])\n\t\t\t\telif _.startswith(\"-\"):\n\t\t\t\t\t_ = self._getBEMName(_)\n\t\t\t\t\tvalue.append(_)\n\t\t\t\telse:\n\t\t\t\t\tvalue.append(_)\n\t\t\tattr[1] = \" \".join(value)\n\t\t# We only want 0 or 1 BEM prefixes\n\t\tassert len(bem_prefixes) <= 1\n\t\telement = Element(name,attributes=attributes,isInline=isInline)\n\t\t# We clear the override\n\t\tif self._override:\n\t\t\tself._override = None\n\t\tself._node().append(element)\n\t\tself._pushStack(element, bem_prefixes[0] if bem_prefixes else None)\n\n\tdef overrideAttributesForNextElement( self, attributes ):\n\t\tself._override = []\n\t\tself._override.extend(attributes)\n\n\tdef onElementEnd( self ):\n\t\tself._popStack()\n\n\tdef onDeclarationStart( self, name, attributes=None ):\n\t\telement = Declaration(name)\n\t\tself._pushStack(element)\n\n\tdef onDeclarationEnd( self ):\n\t\tself._popStack()\n\n\tdef _getBEMName( self, name ):\n\t\t\"\"\"Returns the BEM fully qualified name of the given class. This\n\t\tassumes that `name` starts with a dash.\"\"\"\n\t\tres = [name]\n\t\ti = len(self._bemStack) - 1\n\t\t# The BEM stack is either a BEM prefix, or None. We start at the\n\t\t# deepest level and walk back up. Whenever an element in the stack\n\t\t# does not start with an `-`, we break the loop.\n\t\t# NOTE: this algorithm only works if you have 0 or 1 BEM prefix\n\t\t# per node.\n\t\twhile i >= 0:\n\t\t\tprefix = self._bemStack[i]\n\t\t\tif prefix:\n\t\t\t\tres.insert(0, prefix)\n\t\t\t\t# We break the loop if the prefix DOES NOT start with -\n\t\t\t\tif prefix[0] != \"-\":\n\t\t\t\t\tbreak\n\t\t\ti -= 1\n\t\t# We simply join the resulting array into a string\n\t\treturn \"\".join(res)\n\n\tdef _pushStack( self, node, bemPrefixes=None ):\n\t\tnode.setMode(self.mode())\n\t\tself._nodeStack.append(node)\n\t\t# NOTE: Might just as well store the bem prefixes in the node?\n\t\tself._bemStack.append(bemPrefixes)\n\n\tdef _popStack(self):\n\t\tself._nodeStack.pop()\n\t\tself._bemStack.pop()\n\n\tdef _node( self ):\n\t\tif not self._nodeStack: return self._document\n\t\treturn self._nodeStack[-1]\n\n\tdef pushMode( self, name ):\n\t\tself._modes.append(name)\n\n\tdef popMode( self ):\n\t\tself._modes.pop()\n\n\tdef mode( self ):\n\t\tmodes = [x for x in self._modes if x]\n\t\tif modes:\n\t\t\treturn modes[-1]\n\t\telse:\n\t\t\treturn None\n\n# -----------------------------------------------------------------------------\n#\n# PARSER CLASS\n#\n# -----------------------------------------------------------------------------\n\nclass Parser:\n\t\"\"\"Implements a parser that will turn a Pamela document into an HTML\n\tdocument, returned as a string.\n\n\tThe main methods that you should use are\n\n\t- 'parseFile' to parse file identified by the given path\n\t- 'parseString' to parse a string given as parameter\n\n\tYou can configure the parser by using the following methods:\n\n\t- 'acceptTabsOnly', to tell that the parser will only accept tabs.\n\t- 'acceptSpacesOnly', to tell that the parser will only accept spaces.\n\t- 'acceptTabsAndSpaces', to tell that the parser will accept both tabs and\n\t spaces.\n\t- 'tabsWidth', to specify the width of a tab in spaces, which is only used\n\t when the parser accepts both tabs and spaces.\n\t\"\"\"\n\n\t@classmethod\n\tdef ExpandIncludes( cls, text=None, path=None ):\n\t\tlines = []\n\t\tparser = cls()\n\t\tsource_lines = None\n\t\tif text is None:\n\t\t\twith open(path) as f:\n\t\t\t\tsource_lines = [ensure_unicode(l) for l in f.readlines()]\n\t\telse:\n\t\t\tensure_unicode(text)\n\t\t\tsource_lines = text.split(\"\\n\")\n\t\tparser._paths.append(path or \".\")\n\t\tfor line in source_lines:\n\t\t\tm = RE_INCLUDE.match(line)\n\t\t\tif m:\n\t\t\t\tindent, line = parser._getLineIndent(line)\n\t\t\t\tparser._parseInclude(m, indent, lambda l:lines.append(ensure_unicode(l) if isinstance(l, str) else l))\n\t\t\telse:\n\t\t\t\tlines.append(line + u\"\\n\")\n\t\treturn u\"\".join(lines)\n\n\tdef __init__( self ):\n\t\tself._tabsOnly = False\n\t\tself._spacesOnly = False\n\t\tself._tabsWidth = 4\n\t\tself._elementStack = []\n\t\tself._writer = Writer()\n\t\tself._formatter = Formatter()\n\t\tself._paths = []\n\t\tself._defaults = {}\n\n\tdef setDefaults( self, defaults ):\n\t\tself._defaults = defaults\n\t\treturn self\n\n\tdef path( self ):\n\t\t\"\"\"Returns the current path of the file being parsed, if any\"\"\"\n\t\tif not self._paths or self._paths[-1] == \"--\":\n\t\t\treturn \".\"\n\t\telse:\n\t\t\treturn self._paths[-1]\n\n\tdef indent( self ):\n\t\tif self._elementStack:\n\t\t\treturn self._elementStack[-1][0]\n\t\telse:\n\t\t\treturn 0\n\n\tdef parseFile( self, path ):\n\t\t\"\"\"Parses the file with the given path, and return the corresponding\n\t\tHTML document.\"\"\"\n\t\tshould_close = False\n\t\tif path == \"--\":\n\t\t\tf = sys.stdin\n\t\telse:\n\t\t\t# FIXME: File exists and is readable\n\t\t\tf = open(path, \"r\")\n\t\t\tshould_close = True\n\t\tself._paths.append(path)\n\t\tself._writer.onDocumentStart()\n\t\tfor l in f.readlines():\n\t\t\tself._parseLine(ensure_unicode(l))\n\t\tif should_close: f.close()\n\t\tresult = self._formatter.format(self._writer.onDocumentEnd())\n\t\tself._paths.pop()\n\t\treturn result\n\n\tdef parseString( self, text, path=None ):\n\t\t\"\"\"Parses the given string and returns an HTML document.\"\"\"\n\t\tif path: self._paths.append(path)\n\t\ttry:\n\t\t\ttext = ensure_unicode(text)\n\t\texcept UnicodeEncodeError as e:\n\t\t\t# FIXME: What should we do?\n\t\t\tpass\n\t\tself._writer.onDocumentStart()\n\t\tfor line in text.split(\"\\n\"):\n\t\t\tself._parseLine(line + \"\\n\")\n\t\tres = self._formatter.format(self._writer.onDocumentEnd())\n\t\tif path: self._paths.pop()\n\t\treturn res\n\n\tdef _isInEmbed( self, indent=None ):\n\t\t\"\"\"Tells if the current element is an embed element (like\n\t\tCSS,PHP,etc)\"\"\"\n\t\tif not self._elementStack:\n\t\t\treturn False\n\t\telif indent is None:\n\t\t\treturn self._elementStack[-1][1] == T_EMBED\n\t\telse:\n\t\t\treturn self._elementStack[-1][1] == T_EMBED and self._elementStack[-1][0] < indent\n\n\tdef _parseLine( self, line ):\n\t\t\"\"\"Parses the given line of text.\n\t\tThis is an internal method that you should not really use directly.\"\"\"\n\t\t# FIXME: This function is WAY TOO BIG, it should be broken down in\n\t\t# _parse\n\t\toriginal_line = line\n\t\tindent, line = self._getLineIndent(line)\n\t\t# First, we make sure we close the elements that may be outside of the\n\t\t# scope of this\n\t\t# FIXME: Empty lines may have an indent < than the current element they\n\t\t# are bound to\n\t\tis_empty = RE_EMPTY.match(line)\n\t\tif is_empty:\n\t\t\t# FIXME: When you have an empty line followed by content which is\n\t\t\t# text with same or greeater indent, the empty line should be taken\n\t\t\t# into account. Same for elements with greater indent.\n\t\t\tif self._isInEmbed():\n\t\t\t\tline_with_indent = \"\\n\"\n\t\t\t\tif len(line) > (self.indent()+4)/4:\n\t\t\t\t\tline_with_indent = original_line[(self.indent()+4)/4:]\n\t\t\t\tself._writer.onTextAdd(line_with_indent)\n\t\t\t\treturn\n\t\t\telse:\n\t\t\t\treturn\n\t\tis_comment = RE_COMMENT.match(line)\n\t\tif is_comment and not self._isInEmbed(indent):\n\t\t\t# FIXME: Integrate this\n\t\t\treturn\n\t\t\treturn self._writer.onComment(line)\n\t\t# Is it an include element (%include ...)\n\t\tif self._parseInclude( RE_INCLUDE.match(original_line), indent ):\n\t\t\treturn\n\t\tself._gotoParentElement(indent)\n\t\t# Is the parent an embedded element ?\n\t\tif self._isInEmbed(indent):\n\t\t\tline_with_indent = original_line[int((self.indent()+4)/4):]\n\t\t\tself._writer.onTextAdd(line_with_indent)\n\t\t\treturn\n\t\t# Is it a declaration ?\n\t\tis_declaration = RE_DECLARATION.match(line)\n\t\tif is_declaration:\n\t\t\tself._pushStack(indent, T_DECLARATION)\n\t\t\tdeclared_name = is_declaration.group(1)\n\t\t\tself._writer.onDeclarationStart(declared_name)\n\t\t\treturn\n\t\t# Is it an element ?\n\t\tis_element = RE_ELEMENT.match(line)\n\t\t# It may be an inline element, like:\n\t\t# | \n\t\tif is_element:\n\t\t\tat_index = is_element.group().rfind(\"@\")\n\t\t\tparen_index = is_element.group().rfind(\")\")\n\t\t\tis_embed = (at_index > paren_index)\n\t\t\tclosing = line.find(\">\", is_element.end())\n\t\t\topening = line.find(\"<\", is_element.end())\n\t\t\tif closing == -1:\n\t\t\t\tinline_element = False\n\t\t\telif opening == -1:\n\t\t\t\tinline_element = True\n\t\t\telif closing < opening:\n\t\t\t\tinline_element = True\n\t\t\telse:\n\t\t\t\tinline_element = False\n\t\t\tif is_embed:\n\t\t\t\tinline_element = False\n\t\telse:\n\t\t\tinline_element = False\n\t\tif is_element and not inline_element:\n\t\t\t# The element is an embedded element, we use this to make sure we\n\t\t\t# don't interpret the content as Pamela\n\t\t\tif is_embed:\n\t\t\t\tlanguage = is_element.group()[at_index+1:]\n\t\t\t\tif language[-1] == \":\":language = language[:-1]\n\t\t\t\tself._pushStack(indent, T_EMBED, language)\n\t\t\telse:\n\t\t\t\tself._pushStack(indent, T_ELEMENT)\n\t\t\tgroup = is_element.group()[1:]\n\t\t\trest = line[len(is_element.group()):]\n\t\t\tname,attributes,embed, hints=self._parsePamelaElement(group)\n\t\t\t# Element is a single line if it ends with ':'\n\t\t\tself._writer.onElementStart(name, attributes, isInline=False)\n\t\t\tif group[-1] == \":\" and rest:\n\t\t\t\tself._parseContentLine(rest)\n\t\telse:\n\t\t\t# Otherwise it's data\n\t\t\tself._parseContentLine(line)\n\n\tdef _tokenize( self, text, escape=\"\\\"'\" ):\n\t\tres = []\n\t\to = 0\n\t\tend = len(text)\n\t\twhile o < end:\n\t\t\tescape_index = end + 1\n\t\t\tescape_index_end = -1\n\t\t\tescape_char = None\n\t\t\t# We look for the closest matching escape character\n\t\t\tfor char in escape:\n\t\t\t\t# We find the occurence of the escape char\n\t\t\t\ti = text.find(char,o)\n\t\t\t\t# If it is there and closer to the current offset than\n\t\t\t\t# the previous escape character\n\t\t\t\tif i != -1 and i < escape_index:\n\t\t\t\t\t# We look for the end\n\t\t\t\t\tj = text.find(char,i + 1)\n\t\t\t\t\t# If there is an end, we assign it as the current escape\n\t\t\t\t\tif j != -1:\n\t\t\t\t\t\tescape_index = i\n\t\t\t\t\t\tescape_index_end = j\n\t\t\t\t\t\tescape_char = char\n\t\t\t# If we did not find an escape char\n\t\t\tif escape_char == None:\n\t\t\t\tres.append(text[o:])\n\t\t\t\to = end\n\t\t\telse:\n\t\t\t\tif o < escape_index:\n\t\t\t\t\tres.append(text[o:escape_index])\n\t\t\t\tres.append(text[escape_index:escape_index_end+1])\n\t\t\t\to = escape_index_end+1\n\t\treturn res\n\n\tdef _parseIncludeSubstitutions( self, text ):\n\t\t\"\"\"A simple parser that extract (key,value) from a string like\n\t\t`KEY=VALUE,KEY=\"VALUE\\\"VALUE\",KEY='VALUE\\'VALUE'`\"\"\"\n\t\toffset = 0\n\t\tresult = [] + self._defaults.items()\n\t\twhile offset < len(text):\n\t\t\tequal = text.find(\"=\", offset)\n\t\t\tassert equal >= 0, \"Include subsitution without value: {0}\".format(text)\n\t\t\tname = text[offset:equal]\n\t\t\toffset = equal + 1\n\t\t\tif offset == len(text):\n\t\t\t\tvalue = \"\"\n\t\t\telif text[offset] in '\\'\"':\n\t\t\t\t# We test for quotes and escape it\n\t\t\t\tquote = text[offset]\n\t\t\t\tend_quote = text.find(quote, offset + 1)\n\t\t\t\twhile end_quote >= 0 and text[end_quote - 1] == \"\\\\\":\n\t\t\t\t\tend_quote = text.find(quote, end_quote + 1)\n\t\t\t\tvalue = text[offset+1:end_quote].replace(\"\\\\\" + quote, quote)\n\t\t\t\toffset = end_quote + 1\n\t\t\t\tif offset < len(text) and text[offset] == \",\": offset += 1\n\t\t\telse:\n\t\t\t\t# Or we look for a comma\n\t\t\t\tcomma = text.find(\",\", offset)\n\t\t\t\tif comma < 0:\n\t\t\t\t\tvalue = text[offset:]\n\t\t\t\t\toffset = len(text)\n\t\t\t\telse:\n\t\t\t\t\tvalue = text[offset:comma]\n\t\t\t\t\toffset = comma + 1\n\t\t\tresult.append((name.strip(), value))\n\t\treturn result\n\n\tdef _parseInclude( self, match, indent, parseLine=None ):\n\t\t\"\"\"An include rule is expressed as follows\n\t\t%include PATH {NAME=VAL,...} +.class...(name=val,name,val)\n\t\t\"\"\"\n\t\tif not match: return False\n\t\t# FIXME: This could be written better\n\t\tpath = match.group(2).strip()\n\t\tsubs = None\n\t\t# If there is a paren, we extract the replacement\n\t\tlparen = path.rfind(\"{\")\n\t\toffset = 0\n\t\tif lparen >= 0:\n\t\t\tsubs = {}\n\t\t\trparen = path.rfind(\"}\")\n\t\t\tif rparen > lparen:\n\t\t\t\tfor name, value in self._parseIncludeSubstitutions(path[lparen+1:rparen]):\n\t\t\t\t\tvalue = value.strip()\n\t\t\t\t\tif value and value[0] in [\"'\", '\"']: value = value[1:-1]\n\t\t\t\t\tsubs[name] = value\n\t\t\t\tpath = path[:lparen] + path[rparen+1:]\n\t\t# FIXME: The + will be swallowed if after paren\n\t\tplus = path.find(\"+\")\n\t\tif plus >= 0:\n\t\t\telement = \"div\" + path[plus+1:].strip()\n\t\t\tpath = path[:plus].strip()\n\t\t\t_, attributes, _, _ = self._parsePamelaElement(element)\n\t\t\tif self._writer:\n\t\t\t\tself._writer.overrideAttributesForNextElement(attributes)\n\t\tif path[0] in ['\"',\"'\"]:\n\t\t\tpath = path[1:-1]\n\t\telse:\n\t\t\tpath = path.strip()\n\t\t# Now we load the file\n\t\tlocal_dir = os.path.dirname(os.path.abspath(os.path.normpath(self.path())))\n\t\tlocal_path = os.path.normpath(os.path.join(local_dir, path))\n\t\tif os.path.exists(local_path):\n\t\t\tpath = local_path\n\t\telif os.path.exists(local_path + \".paml\"):\n\t\t\tpath = local_path + \".paml\"\n\t\telif os.path.exists(path):\n\t\t\tpath = path\n\t\telif os.path.exists(path + \".paml\"):\n\t\t\tpath = path + \".paml\"\n\t\tif not os.path.exists(path):\n\t\t\terror_line = \"ERROR: File not found %s\" % (local_path)\n\t\t\tif parseLine:\n\t\t\t\tparseLine(error_line)\n\t\t\telse:\n\t\t\t\treturn self._writer.onTextAdd(error_line)\n\t\telse:\n\t\t\tself._paths.append(path)\n\t\t\twith open(path,'rb') as f:\n\t\t\t\tfor l in f.readlines():\n\t\t\t\t\t# FIXME: This does not work when I use tabs instead\n\t\t\t\t\tl = ensure_unicode(l)\n\t\t\t\t\tp = int(indent/4)\n\t\t\t\t\t# We do the substituion\n\t\t\t\t\tif subs: l = string.Template(l).safe_substitute(**subs)\n\t\t\t\t\t(parseLine or self._parseLine) (p * \"\\t\" + l)\n\t\t\tself._paths.pop()\n\t\treturn True\n\n\tdef _pushStack(self, indent, type, mode=None):\n\t\tself._elementStack.append((indent, type))\n\t\tself._writer.pushMode(mode)\n\n\tdef _popStack(self):\n\t\tself._elementStack.pop()\n\t\tself._writer.popMode()\n\n\tdef _parseContentLine( self, line ):\n\t\t\"\"\"Parses a line that is data/text that is part of an element\n\t\tcontent.\"\"\"\n\t\toffset = 0\n\t\t# We look for elements in the content\n\t\twhile offset < len(line):\n\t\t\telement = RE_INLINE.search(line, offset)\n\t\t\tif not element:\n\t\t\t\tbreak\n\t\t\tclosing = line.find(\">\", element.end())\n\t\t\t# Elements must have a closing\n\t\t\tif closing == -1:\n\t\t\t\traise Exception(\"Unclosed inline tag: '%s'\" % (line))\n\t\t\t# We prepend the text from the offset to the eleemnt\n\t\t\ttext = line[offset:element.start()]\n\t\t\tif text:\n\t\t\t\tself._writer.onTextAdd(text)\n\t\t\t# And we append the element itself\n\t\t\tgroup = element.group()[1:]\n\t\t\tname,attributes,embed, hints=self._parsePamelaElement(group)\n\t\t\tself._writer.onElementStart(name, attributes, isInline=True)\n\t\t\ttext = line[element.end():closing]\n\t\t\tif text: self._writer.onTextAdd(text)\n\t\t\tself._writer.onElementEnd()\n\t\t\toffset = closing + 1\n\t\t# We add the remaining text\n\t\tif offset < len(line):\n\t\t\ttext = line[offset:]\n\t\t\t# We remove the trainling EOL at the end of the line. This might not\n\t\t\t# be the best way to do it, though.\n\t\t\tif text and text[-1] == \"\\n\": text = text[:-1] + \" \"\n\t\t\tif text: self._writer.onTextAdd(text)\n\n\tdef _parsePamelaElement( self, element ):\n\t\t\"\"\"Parses the declaration of a Pamela element, which is like the\n\t\tfollowing examples:\n\n\t\t>\thtml\n\t\t>\ttitle:\n\t\t>\tbody#main.body(onclick=load)|c:\n\n\t\tbasically, it is what lies between '<' and the ':' (or '\\n'), which can\n\t\tbe summmed up as:\n\n\t\t>\t(#ID | NAME #ID?) .CLASS* ATTRIBUTES? |HINTS? :?\n\n\t\twhere attributes is a command-separated sequence of this, surrounded by\n\t\tparens:\n\n\t\t>\tNAME=(VALUE|'VALUE'|\"VALUE\")\n\n\t\tThis function returns a triple (name, attributes, hints)\n\t\trepresenting the parsed element. Attributes are stored as an ordered\n\t\tlist of couples '(name, value'), hints are given as a list of strings.\"\"\"\n\t\toriginal = element\n\t\tif element[-1] == \":\": element = element[:-1]\n\t\t# We look for the attributes list\n\t\tparens_start = element.find(\"(\")\n\t\tat_start = element.rfind(\"@\")\n\t\tif parens_start != -1:\n\t\t\tparens_end = element.rfind(\")\")\n\t\t\tif at_start < parens_end: at_start = -1\n\t\t\tattributes_list = element[parens_start+1:parens_end]\n\t\t\tif attributes_list[-1] == \")\": attributes_list = attributes_list[:-1]\n\t\t\tattributes = self._parsePamelaAttributes(attributes_list)\n\t\t\telement = element[:parens_start]\n\t\telse:\n\t\t\tattributes = []\n\t\t# Useful functions to manage attributes\n\t\tdef has_attribute( name, attributes ):\n\t\t\tfor a in attributes:\n\t\t\t\tif a[0] == name: return a\n\t\t\treturn None\n\t\tdef set_attribute( name, value, attribtues ):\n\t\t\tfor a in attributes:\n\t\t\t\tif a[0] == name:\n\t\t\t\t\ta[1] = value\n\t\t\t\t\treturn\n\t\t\tattributes.append([name,value])\n\t\tdef append_attribute( name, value, attributes, prepend=False ):\n\t\t\ta = has_attribute(name, attributes)\n\t\t\tif a:\n\t\t\t\tif prepend:\n\t\t\t\t\ta[1] = value + \" \" + a[1]\n\t\t\t\telse:\n\t\t\t\t\ta[1] = a[1] + \" \" + value\n\t\t\telse:\n\t\t\t\tset_attribute(name, value, attributes)\n\t\t# We look for the classes\n\t\tif at_start != -1:\n\t\t\tembed = element[at_start+1:]\n\t\t\telement = element[:at_start]\n\t\telse:\n\t\t\tembed = None\n\t\tclasses = element.split(\".\")\n\t\tif len(classes) > 1:\n\t\t\telement = classes[0]\n\t\t\tclasses = classes[1:]\n\t\t\tclasses = \" \".join( classes)\n\t\t\tappend_attribute(\"class\", classes, attributes, prepend=True)\n\t\telse:\n\t\t\telement = classes[0]\n\t\teid = element.split(\"#\")\n\t\t# FIXME: If attributes or ids are already defined, we should look for it\n\t\t# and do something appropriate\n\t\tif len(eid) > 1:\n\t\t\tassert len(eid) == 2, \"More than one id given: %s\" % (original)\n\t\t\tif has_attribute(\"id\", attributes):\n\t\t\t\traise Exception(\"Id already given as element attribute\")\n\t\t\tattributes.insert(0,[\"id\", eid[1]])\n\t\t\telement = eid[0]\n\t\telse:\n\t\t\telement = eid[0]\n\t\t# handle '::' syntax for namespaces\n\t\telement = element.replace(\"::\",\":\")\n\t\treturn (element, attributes, embed, [])\n\n\tdef _parsePamelaAttributes( self, attributes ):\n\t\t\"\"\"Parses a string representing Pamela attributes and returns a list of\n\t\tcouples '[name, value]' representing the attributes.\"\"\"\n\t\tresult = []\n\t\toriginal = attributes\n\t\twhile attributes:\n\t\t\tmatch = RE_ATTRIBUTE.match(attributes)\n\t\t\tassert match, \"Given attributes are malformed: %s\" % (attributes)\n\t\t\tname = match.group(1)\n\t\t\tvalue = match.group(4)\n\t\t\t# handles '::' syntax for namespaces\n\t\t\tname = name.replace(\"::\",\":\")\n\t\t\tif value and value[0] == value[-1] and value[0] in (\"'\", '\"'):\n\t\t\t\tvalue = value[1:-1]\n\t\t\tresult.append([name, value])\n\t\t\tattributes = attributes[match.end():]\n\t\t\tif attributes:\n\t\t\t\tassert attributes[0] == \",\", \"Attributes must be comma-separated: %s\" % (attributes)\n\t\t\t\tattributes = attributes[1:]\n\t\t\t\tassert attributes, \"Trailing comma with no remaining attributes: %s\" % (original)\n\t\treturn result\n\n\tdef _gotoParentElement( self, currentIndent ):\n\t\t\"\"\"Finds the parent element that has an identation lower than the given\n\t\t'currentIndent'.\"\"\"\n\t\twhile self._elementStack and self._elementStack[-1][0] >= currentIndent:\n\t\t\tself._popStack()\n\t\t\tself._writer.onElementEnd()\n\n\tdef _getLineIndent( self, line ):\n\t\t\"\"\"Returns the line indentation as a number. It takes into account the\n\t\tfact that tabs may be requried or not, and also takes into account the\n\t\t'tabsWith' property.\"\"\"\n\t\ttabs = RE_LEADING_TAB.match(line)\n\t\tspaces = RE_LEADING_SPC.match(line)\n\t\tif self._tabsOnly and spaces:\n\t\t\traise Exception(\"Tabs are expected, your lines are indented with spaces\")\n\t\tif self._spacesOnly and tabs:\n\t\t\traise Exception(\"Spaces are expected, your lines are indented with tabs\")\n\t\tif tabs and len(tabs.group()) > 0:\n\t\t\treturn len(tabs.group()) * self._tabsWidth, line[len(tabs.group()):]\n\t\telif spaces and len(spaces.group()) > 0:\n\t\t\treturn len(spaces.group()), line[len(spaces.group()):]\n\t\telse:\n\t\t\treturn 0, line\n\n# -----------------------------------------------------------------------------\n#\n# COMMAND-LINE INTERFACE\n#\n# -----------------------------------------------------------------------------\n\ndef parse( text, path=None, format=\"html\" ):\n\tparser = Parser()\n\tif format == \"js\": parser._formatter = JSHTMLFormatter()\n\treturn parser.parseString(text, path=path)\n\ndef run( arguments, input=None ):\n\tparser = Parser()\n\tif not arguments:\n\t\tinput_file = \"--\"\n\telif arguments[0] == \"--to-html\":\n\t\tinput_file = arguments[1]\n\telif arguments[0] == \"--to-js\":\n\t\tparser._formatter = JSHTMLFormatter()\n\t\tinput_file = arguments[1]\n\telse:\n\t\tinput_file = arguments[0]\n\treturn parser.parseFile(input_file)\n\n# -----------------------------------------------------------------------------\n#\n# MAIN\n#\n# -----------------------------------------------------------------------------\n\nif __name__ == \"__main__\":\n\tif hasattr(logging, \"IS_REPORTER\"):\n\t\tlogging.register(logging.StderrReporter())\n\tsys.stdout.write( run(sys.argv[1:]).encode(\"utf-8\") )\n\n# EOF - vim: tw=80 ts=4 sw=4 noet\n\n","sub_path":"Sources/pamela/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":42765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"629910954","text":"\"\"\"Templating URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.9/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Add an import: from blog import urls as blog_urls\n 2. Import the include() function: from django.conf.urls import url, include\n 3. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.conf.urls.static import static\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\nfrom django.conf import settings\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.ExampleView.as_view(), name='start'),\n url(r'^bullets/', views.BulletsView.as_view(), name='bullets'),\n url(r'^bullet/(?P\\d+)', views.BulletView.as_view(), name='bullet_url'),\n url(r'^users/', views.UsersView.as_view(), name='users'),\n url(r'^user/(?P\\d+)/$', views.UserView.as_view(), name='user_url'),\n url(\n r'^user/(?P\\d+)/follows/(?P\\d+)$',\n views.user_follows,\n name='user_flw'),\n url(\n r'^user/(?P\\d+)/unfollows/(?P\\d+)$',\n views.user_unfollows,\n name='user_uflw'),\n url(r'^signup/', views.registration, name='signup'),\n url(r'^post_bullet/', views.post_bullet, name='post_bullet'),\n url(r'^login/', views.authorization, name='login'),\n url(r'^logout/', views.exit, name='logout'),\n]\n\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\nurlpatterns += staticfiles_urlpatterns()\n","sub_path":"bulletin/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"267122144","text":"import math\n\n\ndef testdf(i):\n logi = math.log(2, 10) * i\n diff = (logi - int(logi))\n return diff\n\n\ndef algo():\n i = 90\n rank = 0\n previ = 0\n lowerbound = math.log(1.23, 10)\n upperbound = math.log(1.24, 10)\n\n while rank < 678910:\n diff = testdf(i)\n if diff >= upperbound:\n i += 93\n elif diff < lowerbound:\n i += 196\n else:\n rank += 1\n previ = i\n i += 196\n\n return previ\n","sub_path":"euler/p0686.py","file_name":"p0686.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"474027324","text":"# coding=utf-8\n\nfrom django.contrib.auth.models import User\nfrom inventory.models import UserProfile\nfrom django import template\n\nregister = template.Library()\n\n#显示头像\n@register.filter(name='show_avatar')\ndef show_avatar(value):\n if value.is_authenticated:\n if UserProfile.objects.get(user=value):\n #user不是超级用户但是已经注册\n avatar = UserProfile.objects.get(user=value).picture\n elif value.is_superuser:\n #user是超级用户但是没有注册\n newuser = UserProfile(\n user_id = value.id,\n width_field = 100,\n height_field = 100\n )\n newuser.save()\n avatar = newuser.picture\n else:\n avatar = None\n return avatar.url\n\n#替换first_tag里的横线为空格\n@register.filter(name='replace_midline')\ndef replace_midline(value):\n if '-' in value:\n value = value.replace('-', ' ')\n return value","sub_path":"inventory/templatetags/myfilters.py","file_name":"myfilters.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"491601522","text":"import re\n\nclass Token:\n NUM = 'NUM'\n PLUS = 'PLUS'\n MINUS = 'MINUS'\n MUL = 'MUL'\n DIV = 'DIV'\n LPR = 'LPR'\n RPR = 'RPR'\n \n token_regexp = [\n (NUM, '([1-9][0-9]*)|0'),\n (PLUS, '\\+'),\n (MINUS, '\\-'),\n (MUL, '\\*'),\n (DIV, '\\/'),\n (LPR, '\\('),\n (RPR, '\\)'),\n ]\n\nclass Scanner:\n def __init__(self, input_file):\n self.input_string = input_file.read()\n self.current_char_index = 0\n self.current_token = self.get_token()\n \n def skip_white_space(self):\n if (self.current_char_index >= len(self.input_string)-1):\n return\n while self.input_string[self.current_char_index].isspace():\n self.current_char_index += 1\n \n def get_token(self):\n self.skip_white_space()\n token, prefix = None, ''\n for (t, r) in Token.token_regexp:\n match = re.match(r, self.input_string[self.current_char_index:])\n if match != None and match.end() > len(prefix):\n token, prefix = t, match.group()\n self.current_char_index += len(prefix)\n return token, prefix\n \n def lookahead(self):\n return self.current_token[0]\n \n def consume(self, *tokens):\n current = self.current_token\n if len(self.input_string[self.current_char_index:]) == 0:\n self.current_token = ('eof', '$')\n else:\n self.current_token = self.get_token()\n if current[0] in tokens:\n return current\n else:\n return (None, '')\n \n\nclass Parser:\n def __init__(self, ts):\n self.scanner = ts\n self.prog()\n \n def prog(self):\n self.expr()\n \n def expr(self):\n print('expr')\n if self.scanner.lookahead() in ['LPR', 'PLUS', 'MINUS', 'NUM']:\n self.term()\n self.expr_tail()\n \n def term(self):\n print('term')\n if self.scanner.lookahead() in ['LPR', 'PLUS', 'MINUS', 'NUM']:\n self.factor()\n self.term_tail()\n \n def expr_tail(self):\n print('expr_tail')\n if self.scanner.lookahead() == 'PLUS':\n self.match('PLUS')\n self.term()\n self.expr_tail()\n elif self.scanner.lookahead() == 'MINUS':\n self.match('MINUS')\n self.term()\n self.expr_tail()\n else:\n if self.scanner.lookahead() in ['eof', 'RPR']:\n pass\n else:\n self.invalid_input()\n \n def factor(self):\n print('factor')\n if self.scanner.lookahead() == 'LPR':\n self.match('LPR')\n self.expr()\n self.match('RPR')\n elif self.scanner.lookahead() == 'PLUS':\n self.match('PLUS')\n self.match('NUM')\n elif self.scanner.lookahead() == 'MINUS':\n self.match('MINUS')\n self.match('NUM')\n else:\n self.match('NUM')\n \n \n def term_tail(self):\n print('term_tail')\n if self.scanner.lookahead() == 'MUL':\n self.match('MUL')\n self.factor()\n self.term_tail()\n elif self.scanner.lookahead() == 'DIV':\n self.match('DIV')\n self.factor()\n self.term_tail()\n else:\n if self.scanner.lookahead() in ['eof', 'PLUS', 'MINUS', 'RPR']:\n pass\n else:\n self.invalid_input()\n \n def invalid_input(self):\n if self.current_token[0] != None:\n pass\n print('Invalid input')\n \n def match(self, token):\n self.current_token = self.scanner.consume(token)\n \n\n\ndef main():\n fp = open('107BA1_B.txt', 'r')\n token_stream = Scanner(fp)\n Parser(token_stream)\n \nif __name__=='__main__':\n main()","sub_path":"attack01/新增資料夾/107BA1_B.py","file_name":"107BA1_B.py","file_ext":"py","file_size_in_byte":3924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"361557967","text":"import crochet\ncrochet.setup()\n\nfrom flask import Flask , render_template, jsonify, request, redirect, url_for\nfrom scrapy import signals\nfrom scrapy.crawler import CrawlerRunner\nfrom scrapy.signalmanager import dispatcher\nimport time\nimport os\n\nimport sqlite3 as sql \n\n# Importing our Scraping Function from the amazon_scraping file\n\nfrom crawlshop.crawlshop.spiders.amazon_scraping import ReviewspiderSpider\n\n# Creating Flask App Variable\n\napp = Flask(__name__)\n\noutput_data = []\ncrawl_runner = CrawlerRunner()\n\n# By Deafult Flask will come into this when we run the file\n@app.route('/')\ndef index():\n\treturn render_template(\"index.html\") # Returns index.html file in templates folder.\n\n\n# After clicking the Submit Button FLASK will come into this\n@app.route('/', methods=['POST'])\ndef submit():\n if request.method == 'POST':\n s = request.form['url'] # Getting the Input Amazon Product URL\n global baseURL\n baseURL = s\n \n # This will remove any existing file with the same name so that the scrapy will not append the data to any previous file.\n if os.path.exists(\"\"): \n os.remove(\"\")\n\n return redirect(url_for('scrape')) # Passing to the Scrape function\n\n\n@app.route(\"/scrape\")\ndef scrape():\n global baseURL\n global output_data\n \n # Getting the unique table name from the input URL.\n table_name = baseURL.split(\"?\")[0]\n \n # Creating a connection to database\n conn = sql.connect('database.db')\n\n # Creating an object of the Database to perform the operations.\n c = conn.cursor()\n \n # This will extract the count of tables with name=''\n # It can only be zero or one.\n c.execute('''SELECT count(name) FROM sqlite_master WHERE name='%s' AND type='table' '''%table_name)\n\n if(c.fetchone()[0]==0):\n\n # Passing the URL for Scraping\n scrape_with_crochet(baseURL=baseURL) # Passing that URL to our Scraping Function\n time.sleep(10) # Pause the function while the scrapy spider is running\n # Scraped Data is appended to the output_list\n\n # Creating the table with name = \n # Note: table_name will be unique for each product\n conn.execute('''CREATE TABLE '%s' (names TEXT, reviewerLink TEXT, reviewTitles TEXT, reviewBody TEXT, verifiedPurchase TEXT, postDate TEXT, starRating TEXT, helpful TEXT, nextPage TEXT)''' %table_name)\n\n # Appending the data into the table from the output_list\n for x in output_data:\n c.execute('''INSERT INTO '%s' (names, reviewerLink, reviewTitles, reviewBody, verifiedPurchase, postDate, starRating, helpful, nextPage) VALUES (?,?,?,?,?,?,?,?,?)''' %table_name ,(x[\"names\"], x[\"reviewerLink\"], x[\"reviewTitles\"], x[\"reviewBody\"], x[\"verifiedPurchase\"], x[\"postDate\"], x[\"starRating\"], x[\"helpful\"], x[\"nextPage\"]))\n\n conn.commit()\n conn.close()\n\n print(\"Table and Records created Successfully!\")\n\n else: # The code will come here if it finds the URL data in the DB\n conn.row_factory = sql.Row\n cur = conn.cursor()\n \n # Selecting everything from the table inside the DB.\n cur.execute(''' SELECT * from '%s' '''%table_name)\n\n # Fetching the data from the cur object.\n rows = cur.fetchall()\n \n # Storing the fetched data into the global output_data list.\n output_data = [dict(i) for i in rows]\n\n conn.close()\n\n print(\"Data Fetched Successfully!\")\n \n return jsonify(output_data) # Returns the scraped data after being running for 20 seconds.\n\n\n@crochet.run_in_reactor\ndef scrape_with_crochet(baseURL):\n # This will connect to the dispatcher that will kind of loop the code between these two functions.\n dispatcher.connect(_crawler_result, signal=signals.item_scraped)\n \n # This will connect to the ReviewspiderSpider function in our scrapy file and after each yield will pass to the crawler_result function.\n eventual = crawl_runner.crawl(ReviewspiderSpider, category = baseURL)\n return eventual\n\n#This will append the data to the output data list.\ndef _crawler_result(item, response, spider):\n output_data.append(dict(item))\n\n\nif __name__== \"__main__\":\n app.run(debug=True)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"517978186","text":"\"\"\"\nCreated on 6 Nov 2017\n\n@author: Bruno Beloff (bruno.beloff@southcoastscience.com)\n\nhttps://xy1eszuu23.execute-api.us-west-2.amazonaws.com/staging/topicMessages?\ntopic=south-coast-science-dev/production-test/loc/1/gases&startTime=2018-03-31T10:45:50Z&endTime=2018-03-31T10:46:50Z\n\"\"\"\n\nfrom scs_core.aws.client.rest_client import RESTClient\nfrom scs_core.aws.data.message import MessageCollection\n\n\n# --------------------------------------------------------------------------------------------------------------------\n\nclass MessageManager(object):\n \"\"\"\n classdocs\n \"\"\"\n\n # ----------------------------------------------------------------------------------------------------------------\n\n def __init__(self, http_client, api_key, verbose=False):\n \"\"\"\n Constructor\n \"\"\"\n self.__rest_client = RESTClient(http_client, api_key)\n self.__verbose = verbose\n\n\n # ----------------------------------------------------------------------------------------------------------------\n\n def find_for_topic(self, topic, start_date, end_date):\n request_path = '/staging/topicMessages'\n params = {'topic': topic, 'startTime': start_date.utc().as_iso8601(), 'endTime': end_date.utc().as_iso8601()}\n\n # request...\n self.__rest_client.connect()\n\n try:\n jdict = self.__rest_client.get(request_path, params)\n\n # messages...\n collection = MessageCollection.construct_from_jdict(jdict)\n\n messages = collection.items\n finally:\n self.__rest_client.close()\n\n return messages\n\n\n # ----------------------------------------------------------------------------------------------------------------\n\n def __str__(self, *args, **kwargs):\n return \"MessageManager:{rest_client:%s, verbose:%s}\" % (self.__rest_client, self.__verbose)\n","sub_path":"src/scs_core/aws/manager/message_manager.py","file_name":"message_manager.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"257197614","text":"import floppyforms as forms\nimport models\n\n\nclass FictiveForm(forms.ModelForm):\n\tdef clean_arms(self):\n\t\tdata = self.cleaned_data['arms']\n\t\tif data > 10:\n\t\t\traise forms.ValidationError(\"Un objet fictif ne peut avoir plus de 10 bras.\")\n\t\treturn data\n\n\tclass Meta:\n\t\tmodel = models.Fictive\n\t\tfields = ('name', 'description', 'red', 'arms', 'creation', 'email', 'grade')\n\t\twidgets = {'creation': forms.TextInput(attrs={'ui-date': ''}),\n\t\t\t\t\t'name': forms.TextInput(attrs={'required': ''})}\n\n\nfrom django.forms.models import modelformset_factory\n\n\nclass PartialFictiveForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = models.Fictive\n\t\tfields = ('name', 'red', 'arms', 'email')\n\t\twidgets = {'name': forms.TextInput(attrs={'required': ''})}\n\n\nFictiveFormSet = modelformset_factory(models.Fictive, form=PartialFictiveForm, extra=0)","sub_path":"fictive/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"380679038","text":"# Copyright 2019 ETH Zurich\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 os\nimport sys\nimport time\n\nimport django\n\nTIMEOUT = 60\n\n\ndef main(argv):\n as_ids = argv[1:]\n trigger_deployment(as_ids)\n print(\"Await confirmation that config has been deployed\")\n wait_until_deployed(as_ids)\n\n\ndef trigger_deployment(as_ids):\n import scionlab.tasks\n\n for h in _needs_deployment(as_ids):\n assert h.managed\n assert h.ssh_host\n scionlab.tasks.deploy_host_config(h)\n print(\"Deployment enqueued for %s\" % h)\n\n\ndef wait_until_deployed(as_ids):\n timeout = time.time() + TIMEOUT\n outstanding = _needs_deployment(as_ids)\n while time.time() < timeout and outstanding:\n time.sleep(1)\n outstanding = _needs_deployment(as_ids)\n\n if outstanding:\n print(\"Timout while waiting for confirmation of deployment from hosts:\\n\", outstanding)\n else:\n print(\"Deployment successful\")\n\n\ndef _needs_deployment(as_ids):\n from scionlab.models.core import Host\n return list(Host.objects.needs_config_deployment().filter(AS__as_id__in=as_ids))\n\n\nif __name__ == '__main__':\n os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'scionlab.settings.development')\n django.setup()\n main(sys.argv)\n","sub_path":".circleci/actions/push-deploy.py","file_name":"push-deploy.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"147949350","text":"import tkinter as Tk\nimport socket\nimport sys\nfrom tkinter import ttk\nfrom tkinter import messagebox\n\n\nclass Check_grade(Tk.Toplevel):\n \"\"\"Constructor\"\"\"\n\n def __init__(self, page):\n self.tl = Tk.Toplevel.__init__(self)\n self.main_page_frame = page\n self.protocol(\"WM_DELETE_WINDOW\", self.disable_event)\n screen_width = self.winfo_screenwidth()\n screen_height = self.winfo_screenheight()\n width = 550\n height = 270\n x = (screen_width / 2) - (width / 2)\n y = (screen_height / 2) - (height / 2)\n self.geometry('%dx%d+%d+%d' % (width, height, x, y))\n self.resizable(0, 0)\n self.title(\"Moil System\")\n\n self.frame_welcome = Tk.Frame(self)\n self.frame_welcome.pack()\n self.label = Tk.Label(self.frame_welcome, bg=\"green\", width=\"400\", height=\"1\", text=\"STUDENT GRADE VIEWER\", font=(\"calibri\", 16, \"bold\"))\n self.label.pack()\n\n self.frame_wel = Tk.Frame(self)\n self.frame_wel.pack()\n # self.label = Tk.Label(self.frame_wel, height=\"1\", text=\"請在下面輸入您的學號:\", font=(14))\n self.label = Tk.Label(self.frame_wel, height=\"1\", text=\"Please Write Your Student ID Bellow: \", font=14)\n self.label.pack(pady=10)\n self.frame1 = Tk.Frame(self)\n self.frame1.pack(pady=5)\n self.frame2 = Tk.Frame(self)\n self.frame2.pack(pady=5)\n self.frame3 = Tk.Frame(self)\n self.frame3.pack(pady=5)\n self.frame4 = Tk.Frame(self)\n self.frame4.pack(pady=5)\n\n self.course = Tk.StringVar()\n self.week = Tk.StringVar()\n self.assign = Tk.StringVar()\n\n self.ent = Tk.StringVar()\n self.entry = Tk.Entry(self.frame1, textvariable=self.ent, font=14)\n self.entry.grid(row=0, column=0)\n self.entry.insert(0, \"Write student ID here\")\n self.entry.bind(\"\", self.some_callback)\n\n list = ['Program_Language_A', 'Program_Language_B', 'Digital_Signal_Processing']\n self.droplist = Tk.OptionMenu(self.frame2, self.course, *list)\n self.droplist.config(width=15)\n self.course.set('Select Your Class')\n self.droplist.grid(row=0, column=0)\n\n list1 = ['Assignment1', 'Assignment2', 'Assignment3', 'Assignment4', 'Assignment5',\n 'Assignment6', 'Assignment7', 'Assignment8', 'Assignment9', 'Assignment10']\n self.droplist = Tk.OptionMenu(self.frame2, self.assign, *list1)\n self.droplist.config(width=20)\n self.assign.set('Select Your Assignment')\n self.droplist.grid(row=0, column=2)\n\n Tk.Button(self.frame4, text=\"CHECK RESULT\", bg=\"green\", command=self.student_ok, font=(\"calibri\", 12, \"bold\")).grid(row=0, column=0)\n Tk.Button(self.frame4, text=\"EXIT\", bg=\"red\", command=self.btn_exit, font=(\"calibri\", 12, \"bold\")).grid(row=0, column=1, padx=50 )\n\n self.listNodes = ttk.Treeview(self.frame3, selectmode=\"extended\", columns=(\"A\", \"B\", \"C\"), height=2)\n # self.listNodes.heading(\"#0\", text=\"No\")\n self.listNodes.column(\"#0\", minwidth=0, width=0)\n self.listNodes.heading(\"A\", text=\"Name\")\n self.listNodes.column(\"A\", minwidth=0, width=120)\n self.listNodes.heading(\"B\", text=\"Status\")\n self.listNodes.column(\"B\", minwidth=0, width=220)\n self.listNodes.heading(\"C\", text=\"Answer\")\n self.listNodes.column(\"C\", minwidth=0, width=180)\n self.listNodes.grid(row=0,column=0)\n\n list_week = ['Week1', 'Week2', 'Week3', 'Week4', 'Week5', 'Week6',\n 'Week7', 'Week8', 'Week9', 'Week10', 'Week11', 'Week12',\n 'Week13', 'Week14', 'Week15', 'Week16', 'Week17', 'Week18', ]\n\n self.drop_list_week = Tk.OptionMenu(self.frame2, self.week, *list_week)\n self.drop_list_week.config(height=1, font=(\"verdana\", 10))\n self.week.set('list_week')\n self.drop_list_week.grid(row=0, column=1, padx=10)\n\n self.main_socket()\n\n def some_callback(self, event):\n self.entry.delete(0, \"end\")\n return None\n\n def main_socket(self):\n self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n host = '192.168.100.238'\n port = 8000\n try:\n self.soc.connect((host, port))\n except:\n sys.exit()\n\n def student_ok(self):\n course = self.course.get()\n quiz = self.assign.get()\n message = \"grade\" + \" \" + self.course.get() + \\\n \" \" + self.entry.get().capitalize() + \" \" + self.week.get() + \\\n \" \" + \"grading_result\" + \" \" + self.assign.get()\n if self.entry.get() == \"Write student ID here\":\n messagebox.showwarning('', 'Please input your studentID !!')\n elif course == \"Select Your Class\":\n messagebox.showwarning('', 'Please input your Class !!')\n elif self.week.get() == 'list_week':\n messagebox.showwarning('', 'Please select which week want to show !!')\n elif quiz == 'Select Your Assignment':\n messagebox.showwarning('', 'Please select which assignment !!')\n elif message == 'quit':\n self.soc.send(b'--quit--')\n elif message == message:\n self.listNodes.delete(*self.listNodes.get_children())\n self.soc.sendall(message.encode('utf8'))\n receive = self.soc.recv(5120).decode('utf8')\n print(receive)\n if receive == \"connection error\":\n messagebox.showwarning('', 'Connection Error')\n elif receive == \"None\":\n messagebox.showwarning(\"error\", \"you're typing wrong Student ID\")\n else:\n x = receive.split(\",\")\n x1 = x[1]\n x2 = x[2]\n x3 = x[3]\n x1_oke = x1[2:-1]\n x3_oke = x3[:-1]\n x2_oke = x2\n self.listNodes.insert(\"\", \"end\", values=(x1_oke, x2_oke, x3_oke))\n\n # data = x2_oke\n # print(data)\n # if data == \"{STATE_0}\":\n # self.listNodes.insert(\"\", \"end\", values=(x1_oke, x2_oke, x3_oke))\n # messagebox.showinfo('info', 'Cant find your code, make sure you already submit assignment')\n # elif data== ' None ':\n # self.listNodes.insert(\"\", \"end\", values=(x1_oke, x2_oke, x3_oke))\n # messagebox.showinfo('info', 'cant find your source code')\n # elif data == \"{STATE_2} Ans too long\":\n # self.listNodes.insert(\"\", \"end\", values=(x1_oke, x2_oke, x3_oke))\n # messagebox.showinfo('info', 'your answer to long')\n # elif data == \"'{STATE_4} No Ans Output'\":\n # self.listNodes.insert(\"\", \"end\", values=(x1_oke, x2_oke, x3_oke))\n # messagebox.showinfo('info', 'No answer output, Your code have some error')\n # elif data == \"{STATE_5} New Line\":\n # self.listNodes.insert(\"\", \"end\", values=(x1_oke, x2_oke, x3_oke))\n # messagebox.showinfo('info', 'Your Answer in new line, code have some error')\n # elif data == \"{ !!! EXACT !!! }\":\n # self.listNodes.insert(\"\", \"end\", values=(x1_oke, x2_oke, x3_oke))\n # messagebox.showinfo('info', \"exactly, you're doing a good job !!!\")\n # else:\n # print(data)\n # self.listNodes.insert(\"\", \"end\", values=(x1_oke, x2_oke, x3_oke))\n # messagebox.showinfo('info', 'Answer incorrect, please follow the format of TA answer')\n else:\n messagebox.showwarning('', 'connection error')\n\n def btn_exit(self):\n self.soc.send(b'--quit--')\n sys.exit()\n\n def disable_event(self):\n pass\n","sub_path":"client-side/client/client/check_grade.py","file_name":"check_grade.py","file_ext":"py","file_size_in_byte":7849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"618049394","text":"#!/usr/bin/python3\n\ndef ni(num_knights,repeat_count,silly_word):\n print(\"We are the {0} knights who say {1}\".format(num_knights,silly_word))\n for i in range(repeat_count):\n print(silly_word, end=' ')\n print()\n\nvalues = ( 15, 5, 'ni!')\n\n# tedious way\nni(values[0],values[1],values[2])\n\n# pythonic way\nni(*values)\n","sub_path":"Classes/py3interm/EXAMPLES/arg_unpack_ex.py","file_name":"arg_unpack_ex.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"582639602","text":"# -*- coding:UTF-8 -*-\n\nimport socket\nimport requests\n\nimport RPi.GPIO as GPIO\nimport time\nfrom flask import Flask\n\nkey = 8\nspeed = 20 # 设置初始速度\napp: Flask = Flask(__name__)\n# 小车电机引脚定义\nIN1 = 20\nIN2 = 21\nIN3 = 19\nIN4 = 26\nENA = 16\nENB = 13\n\n# 设置GPIO口为BCM编码方式\nGPIO.setmode(GPIO.BCM)\n\n# 忽略警告信息\nGPIO.setwarnings(False)\n# 光敏电阻引脚定义\nLdrSensorLeft = 7\nLdrSensorRight = 6\n\n\n@app.route('/') # host page\ndef hello_world():\n return 'Hello World!'\n\n\n# 电机引脚初始化操作\ndef motor_init():\n global pwm_ENA\n global pwm_ENB\n GPIO.setup(ENA, GPIO.OUT, initial=GPIO.HIGH)\n GPIO.setup(IN1, GPIO.OUT, initial=GPIO.LOW)\n GPIO.setup(IN2, GPIO.OUT, initial=GPIO.LOW)\n GPIO.setup(ENB, GPIO.OUT, initial=GPIO.HIGH)\n GPIO.setup(IN3, GPIO.OUT, initial=GPIO.LOW)\n GPIO.setup(IN4, GPIO.OUT, initial=GPIO.LOW)\n GPIO.setup(key, GPIO.IN)\n GPIO.setup(LdrSensorLeft, GPIO.IN)\n GPIO.setup(LdrSensorRight, GPIO.IN)\n # 设置pwm引脚和频率为2000hz\n pwm_ENA = GPIO.PWM(ENA, 2000)\n pwm_ENB = GPIO.PWM(ENB, 2000)\n pwm_ENA.start(0)\n pwm_ENB.start(0)\n\n\n@app.route('/api/car/speed_up', methods=['get']) # 速度增加,最高为100\ndef speed_up():\n global speed\n if speed < 100:\n speed = speed + 5\n return str(speed)\n else:\n return 'It is already the highest speed.'\n\n\n@app.route('/api/car/speed_down', methods=['get']) # 速度减少,最低为0\ndef speed_down():\n global speed\n if speed > 0:\n speed = speed - 5\n return str(speed)\n else:\n return 'It is already the lowest speed.'\n\n\n@app.route('/api/car/run', methods=['get']) # 前进\ndef run():\n global speed\n GPIO.output(IN1, GPIO.HIGH)\n GPIO.output(IN2, GPIO.LOW)\n GPIO.output(IN3, GPIO.HIGH)\n GPIO.output(IN4, GPIO.LOW)\n pwm_ENA.ChangeDutyCycle(speed)\n pwm_ENB.ChangeDutyCycle(speed)\n time.sleep(1)\n\n\n@app.route('/api/car/back', methods=['get']) # 后退\ndef back():\n global speed\n GPIO.output(IN1, GPIO.LOW)\n GPIO.output(IN2, GPIO.HIGH)\n GPIO.output(IN3, GPIO.LOW)\n GPIO.output(IN4, GPIO.HIGH)\n pwm_ENA.ChangeDutyCycle(speed)\n pwm_ENB.ChangeDutyCycle(speed)\n time.sleep(1)\n\n\n@app.route('/api/car/left', methods=['get']) # 左转\ndef left():\n global speed\n GPIO.output(IN1, GPIO.LOW)\n GPIO.output(IN2, GPIO.LOW)\n GPIO.output(IN3, GPIO.HIGH)\n GPIO.output(IN4, GPIO.LOW)\n pwm_ENA.ChangeDutyCycle(speed)\n pwm_ENB.ChangeDutyCycle(speed)\n time.sleep(1)\n\n\n@app.route('/api/car/right', methods=['get']) # 右转\ndef right():\n global speed\n GPIO.output(IN1, GPIO.HIGH)\n GPIO.output(IN2, GPIO.LOW)\n GPIO.output(IN3, GPIO.LOW)\n GPIO.output(IN4, GPIO.LOW)\n pwm_ENA.ChangeDutyCycle(speed)\n pwm_ENB.ChangeDutyCycle(speed)\n time.sleep(1)\n\n\n@app.route('/api/car/spin_left', methods=['get']) # 原地左转\ndef spin_left():\n global speed\n GPIO.output(IN1, GPIO.LOW)\n GPIO.output(IN2, GPIO.HIGH)\n GPIO.output(IN3, GPIO.HIGH)\n GPIO.output(IN4, GPIO.LOW)\n pwm_ENA.ChangeDutyCycle(speed)\n pwm_ENB.ChangeDutyCycle(speed)\n time.sleep(3)\n\n\n@app.route('/api/car/spin_right', methods=['get']) # 原地右转\ndef spin_right():\n global speed\n GPIO.output(IN1, GPIO.HIGH)\n GPIO.output(IN2, GPIO.LOW)\n GPIO.output(IN3, GPIO.LOW)\n GPIO.output(IN4, GPIO.HIGH)\n pwm_ENA.ChangeDutyCycle(speed)\n pwm_ENB.ChangeDutyCycle(speed)\n time.sleep(3)\n\n\n@app.route('/api/car/stop', methods=['get']) # 小车停止\ndef brake():\n global speed\n GPIO.output(IN1, GPIO.LOW)\n GPIO.output(IN2, GPIO.LOW)\n GPIO.output(IN3, GPIO.LOW)\n GPIO.output(IN4, GPIO.LOW)\n pwm_ENA.ChangeDutyCycle(speed)\n pwm_ENB.ChangeDutyCycle(speed)\n time.sleep(2)\n\n\n@app.route('/api/act/findlight') # 寻光行走\ndef findlight():\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect(('8.8.8.8', 80))\n ip = s.getsockname()[0] # host ip\n # motor_init() # 初始化\n t1 = time.time()\n for i in range(1, 31):\n t2 = time.time()\n usetime = t2-t1\n if usetime < 30: # 设置最长30秒就停止\n # 遇到光线,寻光模块的指示灯灭,端口电平为HIGH\n # 未遇光线,寻光模块的指示灯亮,端口电平为LOW\n LdrSersorLeftValue = GPIO.input(LdrSensorLeft)\n LdrSersorRightValue = GPIO.input(LdrSensorRight)\n if LdrSersorLeftValue == True and LdrSersorRightValue == True:\n requests.get('http://' + ip + ':5000/api/car/run')\n # run() # 两侧均有光���信号为HIGH,光敏电阻指示灯灭,小车前进\n elif LdrSersorLeftValue == True and LdrSersorRightValue == False:\n requests.get('http://' + ip + ':5000/api/car/spin_left')\n # spin_left() # 左边探测到有光,有信号返回,向左转\n time.sleep(0.002)\n elif LdrSersorRightValue \\\n == True and LdrSersorLeftValue == False:\n requests.get('http://' + ip + ':5000/api/car/spin_right')\n # spin_right() # 右边探测到有光,有信号返回,向右转\n time.sleep(0.002)\n elif LdrSersorRightValue == False and LdrSersorLeftValue == False:\n requests.get('http://' + ip + ':5000/api/car/stop')\n # brake()\n\n\n# 延时2s\ntime.sleep(2)\n\nif __name__ == '__main__':\n motor_init() # 初始化\n app.run(\n host='0.0.0.0', # url\n port='5000', # 端口\n debug=True\n )\n pwm_ENA.stop()\n pwm_ENB.stop()\n GPIO.cleanup()\n","sub_path":"CarRun.py","file_name":"CarRun.py","file_ext":"py","file_size_in_byte":5662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"227014379","text":"## Supondo que a cotação do dólar esteja em R$ 3,25, salve esse\n## valor em uma variável e utilize-o para calcular quanto você teria\n## ao cambiar R$ 65,00 para dólares.\n\ndolar = 3.25\nreais = 65\n\nresultado = 65/ 3.25\n\nprint('voce podera compra', resultado, ' Dolares')\n","sub_path":"Exercicio 3/questao01.py","file_name":"questao01.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"163565208","text":"\"\"\"Get and render N words; then compare with the rendering done on the Wiktionary to catch errors.\"\"\"\nimport os\nfrom pathlib import Path\nfrom random import choice\nfrom typing import List\n\nfrom . import check_word, render\n\n\ndef main(locale: str, count: int) -> int:\n \"\"\"Entry point.\"\"\"\n\n output_dir = Path(os.getenv(\"CWD\", \"\")) / \"data\" / locale\n file = render.get_latest_json_file(output_dir)\n if not file:\n print(\">>> No dump found. Run with --parse first ... \", flush=True)\n return 1\n\n print(f\">>> Loading {file} ...\")\n all_words: List[str] = list(render.load(file).keys())\n\n errors = 0\n for n in range(count):\n word = choice(all_words)\n print(f\"\\n[{n + 1}/{count}] Checking {word!r}\", flush=True)\n errors += check_word.main(locale, word)\n\n if errors:\n print(\"\\n >>> TOTAL Errors:\", errors)\n\n return errors\n","sub_path":"wikidict/check_random_words.py","file_name":"check_random_words.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"136771410","text":"import copy\nimport os\nimport numpy as np\n\nfrom scipy.ndimage.filters import convolve\nfrom skimage.morphology import disk, dilation\nimport pickle\n\n\n\n\nclass CloudDetector:\n\n def __init__(self, threshold=0.4, average_over=1, dilation_size=1, model_filename=None):\n\n self.threshold = threshold\n self.average_over = average_over\n self.dilation_size = dilation_size\n\n if model_filename is not None:\n package_dir = os.path.dirname(__file__)\n model_filename = os.path.join(package_dir, 'models', model_filename)\n self.model_filename = model_filename\n print(self.model_filename)\n loaded_model = pickle.load(open(self.model_filename, \"rb\"))\n self.classifier = loaded_model\n if average_over > 0:\n self.conv_filter = disk(average_over) / np.sum(disk(average_over))\n\n if dilation_size > 0:\n self.dilation_filter = disk(dilation_size)\n\n \n\n def get_cloud_probability_maps(self, X):\n \n if X.shape[3] != 4:\n raise ValueError(\"Numper of channel!= 4\")\n if len(X.shape) != 4:\n raise ValueError('Array of input images has to be a 4-dimensional array of shape'\n '[n_images, n_pixels_y, n_pixels_x, n_bands]')\n pixels = X.reshape(-1,4)\n probabilities = self.classifier.predict_proba(pixels)\n return probabilities[:,1].reshape( X.shape[0], X.shape[1], X.shape[2])\n\n\n def get_cloud_masks(self, X,threshold=None):\n \n cloud_probs = self.get_cloud_probability_maps(X)\n \n threshold = self.threshold if threshold is None else threshold\n if self.average_over:\n cloud_masks = np.asarray([convolve(cloud_prob, self.conv_filter) > threshold\n for cloud_prob in cloud_probs], dtype=np.int8)\n else:\n cloud_masks = (cloud_probs > threshold).astype(np.int8)\n\n if self.dilation_size:\n cloud_masks = np.asarray([dilation(cloud_mask, self.dilation_filter) for cloud_mask in cloud_masks], dtype=np.int8)\n return cloud_masks\n\n\n\n\n","sub_path":"cloudless/CloudDetector.py","file_name":"CloudDetector.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"56344107","text":"class Solution:\n def countBinarySubstrings(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n result = 0\n prevCount = 0\n currentCount = 0\n currentChar = None\n for i in s:\n if currentChar != i:\n result += min(prevCount, currentCount)\n prevCount = currentCount\n currentCount = 1\n currentChar = i\n else:\n currentCount += 1\n result += min(currentCount, prevCount)\n\n return result\n\n","sub_path":"CountBinarySubstrings.py","file_name":"CountBinarySubstrings.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"49822555","text":"from django.contrib import admin\nfrom django.conf.urls import patterns, include, url\nfrom blogs import views\nadmin.autodiscover()\n\n\nurlpatterns = patterns('',\n url(r'^$', views.HomeView.as_view(), name='home'),\n url(r'^blogs/', include('blogs.urls', namespace='blogs')),\n url(r'^accounts/', include('accounts.urls', namespace='accounts')),\n url(r'^admin/', include(admin.site.urls)),\n)\n","sub_path":"potatoub1/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"634703238","text":"class User(object):\n\n def __init__(self, id):\n self.id = id\n self.firstname = \"Joe\"\n self.lastname = \"User\"\n self.address = \"123 Fake Street\"\n self.city = \"Blacksburg\"\n\n def update(self, update_dict):\n self.firstname = update_dict['firstname']\n self.lastname = update_dict['lastname']\n self.address = update_dict['address']\n self.city = update_dict['city']\n\n def to_dict(self):\n return {\n \"id\": self.id,\n \"firstname\": self.firstname,\n \"lastname\": self.lastname,\n \"address\": self.address,\n \"city\": self.city,\n }\n","sub_path":"jquery-jasmine-tdd-workshop-master/server/server/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"505792098","text":"import logging\nimport math\nimport os\nimport pybullet as p\nimport time\nimport torch\nimport enum\n\nimport numpy as np\nfrom arm_pytorch_utilities import math_utils\nfrom arm_pytorch_utilities import simulation\nfrom tampc import cfg\nfrom tampc.env.pybullet_env import PybulletEnv, ContactInfo, get_total_contact_force, get_lateral_friction_forces\nfrom tampc.env.env import TrajectoryLoader, handle_data_format_for_state_diff, EnvDataSource\nfrom tampc.env.pybullet_sim import PybulletSim\n\nlogger = logging.getLogger(__name__)\n\n\nclass BlockFace(enum.IntEnum):\n RIGHT = 0\n TOP = 1\n LEFT = 2\n BOT = 3\n\n\n_MAX_ALONG = 0.3 / 2 # half length of block\n_BLOCK_HEIGHT = 0.05\n_PUSHER_MID = 0.10\n_RADIUS_GYRATION = math.sqrt(((2 * _MAX_ALONG) ** 2 + (2 * _MAX_ALONG) ** 2) / 12)\nDIST_FOR_JUST_TOUCHING = _MAX_ALONG + 0.021 - 0.00001\n\n\ndef pusher_pos_for_touching(block_pos, block_yaw, from_center=DIST_FOR_JUST_TOUCHING, face=BlockFace.LEFT,\n along_face=0):\n \"\"\"\n Get pusher (x,y) for it to be adjacent the face of the block\n :param block_pos: (x,y) of the block\n :param block_yaw: rotation of the block in radians\n :param from_center: how perpendicular to the face to extend out in m\n :param face: which block face to be adjacent to\n :param along_face: how far up along the given face of the block the pusher is in m\n :return:\n \"\"\"\n if face == BlockFace.RIGHT:\n dxy = (from_center, along_face)\n elif face == BlockFace.TOP:\n dxy = (along_face, from_center)\n elif face == BlockFace.LEFT:\n dxy = (-from_center, along_face)\n else:\n dxy = (along_face, -from_center)\n\n # rotate by yaw to match (around origin since these are differences)\n dxy = math_utils.rotate_wrt_origin(dxy, block_yaw)\n pusher_pos = np.add(block_pos, dxy)\n return pusher_pos\n\n\ndef pusher_pos_along_face(block_pos, block_yaw, pusher_pos, face=BlockFace.LEFT):\n \"\"\"\n Get how far along the given face the pusher is (the reverse of the previous function essentially)\n :param block_pos: (x,y) of the block\n :param block_yaw: rotation of the block in radians\n :param pusher_pos: (x,y) of the pusher\n :param face: which block face to be adjacent to\n :return:\n \"\"\"\n dxy = np.subtract(pusher_pos, block_pos)\n # rotate back by yaw to get wrt origin\n dxy = math_utils.rotate_wrt_origin(dxy, -block_yaw)\n if face == BlockFace.RIGHT:\n from_center, along_face = dxy\n elif face == BlockFace.TOP:\n along_face, from_center = dxy\n elif face == BlockFace.LEFT:\n from_center, along_face = dxy\n from_center = - from_center\n else:\n along_face, from_center = dxy\n from_center = - from_center\n return along_face, from_center\n\n\nclass PushLoader(TrajectoryLoader):\n @staticmethod\n def _info_names():\n return ['reaction', 'model error', 'wall contact']\n\n def _process_file_raw_data(self, d):\n x = d['X']\n\n # separate option deciding whether to predict output of pusher positions or not\n state_col_offset = 0 if self.config.predict_all_dims else 2\n if self.config.predict_difference:\n y = PushAgainstWallEnv.state_difference(x[1:], x[:-1])\n else:\n y = x[1:, state_col_offset:]\n\n xu, y, r = self._apply_masks(d, x, y)\n\n return xu, y, r\n\n\nclass PushLoaderRestricted(PushLoader):\n \"\"\"\n When the environment restricts the pusher to be next to the block, so that our state is\n xb, yb, yaw, along\n \"\"\"\n\n def _process_file_raw_data(self, d):\n x = d['X']\n\n if self.config.predict_difference:\n y = PushAgainstWallStickyEnv.state_difference(x[1:], x[:-1])\n else:\n raise RuntimeError(\"Too hard to predict discontinuous normalized angles; use predict difference\")\n\n xu, y, cc = self._apply_masks(d, x, y)\n\n return xu, y, cc\n\n\nclass PushLoaderWithReaction(PushLoaderRestricted):\n \"\"\"\n Include reaction force as part of state that we need to predict\n \"\"\"\n\n def _process_file_raw_data(self, d):\n x = d['X']\n if x.shape[1] > PushWithForceDirectlyEnv.nx:\n x = x[:, :PushWithForceDirectlyEnv.nx]\n # from testing, it's better if these guys are delayed 1 time step (to prevent breaking causality)\n # ignore force in z\n r = d['reaction'][:, :2]\n if self.config.predict_difference:\n dpos = x[1:, :2] - x[:-1, :2]\n dyaw = math_utils.angular_diff_batch(x[1:, 2], x[:-1, 2])\n dalong = x[1:, 3] - x[:-1, 3]\n dr = r[1:] - r[:-1]\n y = np.concatenate((dpos, dyaw.reshape(-1, 1), dalong.reshape(-1, 1), dr), axis=1)\n else:\n raise RuntimeError(\"Too hard to predict discontinuous normalized angles; use predict difference\")\n\n x = np.concatenate((x, r), axis=1)\n xu, y, cc = self._apply_masks(d, x, y)\n\n return xu, y, cc\n\n\nclass PushLoaderPhysicalPusherWithReaction(PushLoaderRestricted):\n def _process_file_raw_data(self, d):\n x = d['X']\n if x.shape[1] != PushPhysicallyAnyAlongEnv.nx:\n raise RuntimeError(\n \"Incompatible dataset; expected nx = {} got nx = {}\".format(PushPhysicallyAnyAlongEnv.nx, x.shape[1]))\n\n if self.config.predict_difference:\n y = PushPhysicallyAnyAlongEnv.state_difference(x[1:], x[:-1])\n else:\n raise RuntimeError(\"Too hard to predict discontinuous normalized angles; use predict difference\")\n\n xu, y, cc = self._apply_masks(d, x, y)\n\n return xu, y, cc\n\n\nclass DebugVisualization(enum.IntEnum):\n FRICTION = 0\n WALL_ON_BLOCK = 1\n REACTION_ON_PUSHER = 2\n ACTION = 3\n BLOCK_ON_PUSHER = 4\n REACTION_IN_STATE = 5\n\n\nclass ReactionForceStrategy:\n MAX_OVER_CONTROL_STEP = 0\n MAX_OVER_MINI_STEPS = 1\n AVG_OVER_MINI_STEPS = 2\n MEDIAN_OVER_MINI_STEPS = 3\n\n\nclass PushAgainstWallEnv(PybulletEnv):\n nu = 2\n nx = 5\n ny = 3\n\n @staticmethod\n def state_names():\n return ['x robot (m)', 'y robot (m)', 'x block (m)', 'y block (m)', 'block rotation (rads)']\n\n @staticmethod\n def get_block_pose(state):\n return state[2:5]\n\n @staticmethod\n def get_pusher_pos(state, action=None):\n return state[0:2]\n\n @staticmethod\n @handle_data_format_for_state_diff\n def state_difference(state, other_state):\n \"\"\"Get state - other_state in state space\"\"\"\n dyaw = math_utils.angular_diff_batch(state[:, 4], other_state[:, 4])\n dpos = state[:, :4] - other_state[:, :4]\n return dpos, dyaw.reshape(-1, 1)\n\n @classmethod\n def state_cost(cls):\n return np.diag([0, 0, 1, 1, 0])\n\n @staticmethod\n def control_names():\n return ['d$x_r$', 'd$y_r$']\n\n @staticmethod\n def get_control_bounds():\n # depends on the environment; these are the limits for StickyEnv\n u_min = np.array([-0.03, 0.03])\n u_max = np.array([0.03, 0.03])\n return u_min, u_max\n\n @classmethod\n def control_cost(cls):\n return np.diag([1 for _ in range(cls.nu)])\n\n def __init__(self, goal=(1.0, 0.), init_pusher=(-0.25, 0), init_block=(0., 0.), init_yaw=0.,\n environment_level=0, sim_step_wait=None, mini_steps=100, wait_sim_steps_per_mini_step=20,\n max_pusher_force=20, debug_visualizations=None, state_cost_for_done=0.06,\n reaction_force_strategy=ReactionForceStrategy.MEDIAN_OVER_MINI_STEPS, **kwargs):\n \"\"\"\n :param goal:\n :param init_pusher:\n :param init_block:\n :param init_yaw:\n :param environment_level: what obstacles should show up in the environment\n :param sim_step_wait: how many seconds to wait between each sim step to show intermediate states\n (0.01 seems reasonable for visualization)\n :param mini_steps how many mini control steps to divide the control step into;\n more is better for controller and allows greater force to prevent sliding\n :param wait_sim_steps_per_mini_step how many sim steps to wait per mini control step executed;\n inversely proportional to mini_steps\n :param reaction_force_strategy how to aggregate measured reaction forces over control step into 1 value\n :param kwargs:\n \"\"\"\n super().__init__(**kwargs, default_debug_height=_BLOCK_HEIGHT)\n self.level = environment_level\n self.sim_step_wait = sim_step_wait\n # as long as this is above a certain amount we won't exceed it in freespace pushing if we have many mini steps\n self.max_pusher_force = max_pusher_force\n self.mini_steps = mini_steps\n self.wait_sim_step_per_mini_step = wait_sim_steps_per_mini_step\n self.reaction_force_strategy = reaction_force_strategy\n self.state_cost_for_done = state_cost_for_done\n\n # initial config\n self.goal = None\n self.initPusherPos = None\n self.initBlockPos = None\n self.initBlockYaw = None\n\n self._debug_visualizations = {\n DebugVisualization.FRICTION: False,\n DebugVisualization.REACTION_ON_PUSHER: False,\n DebugVisualization.WALL_ON_BLOCK: False,\n DebugVisualization.ACTION: True,\n DebugVisualization.BLOCK_ON_PUSHER: False,\n DebugVisualization.REACTION_IN_STATE: False,\n }\n if debug_visualizations is not None:\n self._debug_visualizations.update(debug_visualizations)\n\n # avoid the spike at the start of each mini step from rapid acceleration\n self._steps_since_start_to_get_reaction = 5\n self._clear_state_between_control_steps()\n\n self.set_task_config(goal, init_pusher, init_block, init_yaw)\n self._setup_experiment()\n # start at rest\n for _ in range(1000):\n p.stepSimulation()\n self.state = self._obs()\n\n # --- initialization and task configuration\n def _clear_state_between_control_steps(self):\n self._sim_step = 0\n self._mini_step_contact = {'full': np.zeros((self.mini_steps, 2)), 'mag': np.zeros(self.mini_steps)}\n self._contact_info = {}\n self._largest_contact = {}\n self._reaction_force = np.zeros(2)\n\n def set_task_config(self, goal=None, init_pusher=None, init_block=None, init_yaw=None):\n \"\"\"Change task configuration; assumes only goal position is specified #TOOD relax assumption\"\"\"\n if goal is not None:\n self._set_goal(goal)\n self._draw_goal()\n if init_block is not None:\n self._set_init_block_pos(init_block)\n if init_yaw is not None:\n self._set_init_block_yaw(init_yaw)\n if init_pusher is not None:\n self._set_init_pusher(init_pusher)\n\n def _set_goal(self, goal):\n # ignore the pusher position\n self.goal = np.array(tuple(goal) + tuple(goal) + (0.0,))\n\n def _set_init_pusher(self, init_pusher):\n self.initPusherPos = tuple(init_pusher) + (_PUSHER_MID,)\n\n def _set_init_block_pos(self, init_block_pos):\n self.initBlockPos = tuple(init_block_pos) + (0.03,)\n\n def _set_init_block_yaw(self, init_yaw):\n self.initBlockYaw = init_yaw\n\n def _setup_experiment(self):\n # add plane to push on (slightly below the base of the robot)\n self.planeId = p.loadURDF(\"plane.urdf\", [0, 0, 0], useFixedBase=True)\n self.pusherId = p.loadURDF(os.path.join(cfg.ROOT_DIR, \"pusher.urdf\"), self.initPusherPos)\n self.blockId = p.loadURDF(os.path.join(cfg.ROOT_DIR, \"block_big.urdf\"), self.initBlockPos,\n p.getQuaternionFromEuler([0, 0, self.initBlockYaw]))\n\n # adjust dynamics for better stability\n p.changeDynamics(self.planeId, -1, lateralFriction=0.3, spinningFriction=0.0, rollingFriction=0.0)\n\n self.walls = []\n wall_z = 0.05\n if self.level == 0:\n pass\n elif self.level in [1, 4, 5]:\n self.walls.append(p.loadURDF(os.path.join(cfg.ROOT_DIR, \"wall.urdf\"), [-0.55, -0.25, wall_z],\n p.getQuaternionFromEuler([0, 0, 0]), useFixedBase=True,\n globalScaling=0.8))\n elif self.level == 2:\n translation = 10\n self.walls.append(\n p.loadURDF(os.path.join(cfg.ROOT_DIR, \"wall.urdf\"), [-0.55 + translation, -0.25 + translation, wall_z],\n p.getQuaternionFromEuler([0, 0, 0]), useFixedBase=True,\n globalScaling=0.8))\n elif self.level in [3, 6]:\n self.walls.append(p.loadURDF(os.path.join(cfg.ROOT_DIR, \"wall.urdf\"), [-0.3, 0.25, wall_z],\n p.getQuaternionFromEuler([0, 0, -math.pi / 4]), useFixedBase=True,\n globalScaling=0.8))\n if self.level == 2:\n self.set_camera_position([10, 10])\n else:\n self.set_camera_position([0, 0])\n\n self._draw_goal()\n self.state = self._obs()\n self._draw_state()\n\n # set gravity\n p.setGravity(0, 0, -10)\n\n # set robot init config\n self.pusherConstraint = p.createConstraint(self.pusherId, -1, -1, -1, p.JOINT_FIXED, [0, 0, 1], [0, 0, 0],\n self.initPusherPos)\n\n # --- visualization (rarely overriden)\n def visualize_rollouts(self, states):\n \"\"\"In GUI mode, show how the sequence of states will look like\"\"\"\n if states is None:\n return\n # assume states is iterable, so could be a bunch of row vectors\n T = len(states)\n for t in range(T):\n pose = self.get_block_pose(states[t])\n c = (t + 1) / (T + 1)\n self._dd.draw_2d_pose('rx{}'.format(t), pose, (0, c, c))\n # clear previous rollout buffer\n self._dd.clear_visualization_after('rx', T)\n\n def visualize_goal_set(self, states):\n if states is None:\n return\n T = len(states)\n for t in range(T):\n pose = self.get_block_pose(states[t])\n c = (t + 1) / (T + 1)\n self._dd.draw_2d_pose('gs{}'.format(t), pose, (c, c, c))\n self._dd.clear_visualization_after('gs', T)\n\n def visualize_trap_set(self, trap_set):\n if trap_set is None:\n return\n T = len(trap_set)\n for t in range(T):\n c = (t + 1) / (T + 1)\n if len(trap_set[t]) is 2:\n state, action = trap_set[t]\n self._draw_action(action.cpu().numpy(), old_state=state.cpu().numpy(), debug=t + 1)\n else:\n state = trap_set[t]\n pose = self.get_block_pose(state)\n self._dd.draw_2d_pose('ts{}'.format(t), pose, (1, 0, c))\n self._dd.clear_visualization_after('ts', T)\n self._dd.clear_visualization_after('u', T + 1)\n\n def visualize_prediction_error(self, predicted_state):\n \"\"\"In GUI mode, show the difference between the predicted state and the current actual state\"\"\"\n pred_pose = self.get_block_pose(predicted_state)\n c = (0.5, 0, 0.5)\n self._dd.draw_2d_pose('ep', pred_pose, c)\n pose = self.get_block_pose(self.state)\n # use size to represent error in rotation\n angle_diff = abs(math_utils.angular_diff(pred_pose[2], pose[2]))\n pose[2] = _BLOCK_HEIGHT\n # draw line from current pose to predicted pose\n self._dd.draw_2d_line('el', pose, (pred_pose - pose)[:2], c, scale=20, size=angle_diff * 50)\n\n def clear_debug_trajectories(self):\n self._dd.clear_transitions()\n\n def _draw_goal(self):\n self._dd.draw_point('goal', self.get_block_pose(self.goal)[:2])\n\n def _draw_state(self):\n self._dd.draw_2d_pose('state', self.get_block_pose(self.state))\n\n def _draw_reaction_force(self, r, name, color=(1, 0, 1)):\n start = self._observe_pusher()\n self._dd.draw_2d_line(name, start, r, size=np.linalg.norm(r), scale=0.03, color=color)\n\n def draw_user_text(self, text, location_index=1, left_offset=1.0):\n if location_index is 0:\n raise RuntimeError(\"Can't use same location index (0) as cost\")\n self._dd.draw_text('user{}_{}'.format(location_index, left_offset), text, location_index, left_offset)\n\n # --- set current state\n def set_state(self, state, action=None, block_id=None):\n assert state.shape[0] == self.nx\n if block_id is None:\n block_id = self.blockId\n prev_block_pose = p.getBasePositionAndOrientation(self.blockId)\n zb = prev_block_pose[0][2]\n\n block_pose = self.get_block_pose(state)\n # keep previous height rather than reset since we don't know what's the height at ground level\n p.resetBasePositionAndOrientation(block_id, (block_pose[0], block_pose[1], zb),\n p.getQuaternionFromEuler([0, 0, block_pose[2]]))\n\n self.state = state\n self._draw_state()\n if action is not None:\n pusher_pos = self.get_pusher_pos(state, action)\n p.resetBasePositionAndOrientation(self.pusherId, (pusher_pos[0], pusher_pos[1], _PUSHER_MID),\n p.getQuaternionFromEuler([0, 0, 0]))\n self._draw_action(action, old_state=state)\n\n # --- observing state from simulation\n def _obs(self):\n \"\"\"Observe current state from simulator\"\"\"\n x, y, z = self._observe_pusher()\n return np.array((x, y) + self._observe_block())\n\n def _observe_block(self):\n blockPose = p.getBasePositionAndOrientation(self.blockId)\n xb = blockPose[0][0]\n yb = blockPose[0][1]\n roll, pitch, yaw = p.getEulerFromQuaternion(blockPose[1])\n return xb, yb, yaw\n\n def _observe_pusher(self):\n pusherPose = p.getBasePositionAndOrientation(self.pusherId)\n return pusherPose[0]\n\n def _observe_reaction_force(self):\n \"\"\"Return representative reaction force for simulation steps up to current one since last control step\"\"\"\n if self.reaction_force_strategy is ReactionForceStrategy.AVG_OVER_MINI_STEPS:\n return self._mini_step_contact['full'].mean(axis=0)\n if self.reaction_force_strategy is ReactionForceStrategy.MEDIAN_OVER_MINI_STEPS:\n median_mini_step = np.argsort(self._mini_step_contact['mag'])[self.mini_steps // 2]\n return self._mini_step_contact['full'][median_mini_step]\n if self.reaction_force_strategy is ReactionForceStrategy.MAX_OVER_MINI_STEPS:\n max_mini_step = np.argmax(self._mini_step_contact['mag'])\n return self._mini_step_contact['full'][max_mini_step]\n else:\n return self._reaction_force[:2]\n\n def _observe_additional_info(self, info, visualize=True):\n pass\n\n def _observe_info(self, visualize=True):\n info = {}\n\n # number of wall contacts\n info['wc'] = 0\n if self.level > 0:\n for wallId in self.walls:\n contactInfo = p.getContactPoints(self.blockId, wallId)\n info['wc'] += len(contactInfo)\n\n # block velocity\n v, va = p.getBaseVelocity(self.blockId)\n info['bv'] = np.linalg.norm(v)\n info['bva'] = np.linalg.norm(va)\n\n # pusher velocity\n v, va = p.getBaseVelocity(self.pusherId)\n info['pv'] = np.linalg.norm(v)\n info['pva'] = np.linalg.norm(va)\n\n # block-pusher distance\n x, y, _ = self._observe_pusher()\n xb, yb, theta = self._observe_block()\n\n along, from_center = pusher_pos_along_face((xb, yb), theta, (x, y))\n info['pusher dist'] = from_center - DIST_FOR_JUST_TOUCHING\n info['pusher along'] = along\n\n self._observe_additional_info(info, visualize)\n self._sim_step += 1\n\n for key, value in info.items():\n if key not in self._contact_info:\n self._contact_info[key] = []\n self._contact_info[key].append(value)\n\n def _observe_raw_reaction_force(self, info, reaction_force, visualize=True):\n reaction_force[2] = 0\n # save reaction force\n name = 'r'\n info[name] = reaction_force\n reaction_force_size = np.linalg.norm(reaction_force)\n # see if we should save it as the reaction force for this mini-step\n mini_step, step_since_start = divmod(self._sim_step, self.wait_sim_step_per_mini_step)\n if step_since_start is self._steps_since_start_to_get_reaction:\n self._mini_step_contact['full'][mini_step] = reaction_force[:2]\n self._mini_step_contact['mag'][mini_step] = reaction_force_size\n if self.reaction_force_strategy is not ReactionForceStrategy.MAX_OVER_CONTROL_STEP and \\\n self._debug_visualizations[DebugVisualization.REACTION_ON_PUSHER] and visualize:\n self._draw_reaction_force(reaction_force, name, (1, 0, 1))\n # update our running count of max force\n if reaction_force_size > self._largest_contact.get(name, 0):\n self._largest_contact[name] = reaction_force_size\n self._reaction_force = reaction_force\n if self.reaction_force_strategy is ReactionForceStrategy.MAX_OVER_CONTROL_STEP and \\\n self._debug_visualizations[DebugVisualization.REACTION_ON_PUSHER] and visualize:\n self._draw_reaction_force(reaction_force, name, (1, 0, 1))\n\n def _aggregate_info(self):\n info = {key: np.stack(value, axis=0) for key, value in self._contact_info.items() if len(value)}\n info['reaction'] = self._observe_reaction_force()\n info['wall_contact'] = info['wc'].max()\n return info\n\n # --- control helpers (rarely overridden)\n def evaluate_cost(self, state, action=None):\n diff = self.state_difference(state, self.goal)\n diff = diff.reshape(-1)\n cost = diff @ self.Q @ diff\n done = cost < self.state_cost_for_done\n if action is not None:\n cost += action @ self.R @ action\n return cost, done\n\n def _finish_action(self, old_state, action):\n \"\"\"Evaluate action after finishing it; step should not modify state after calling this\"\"\"\n self.state = np.array(self._obs())\n\n # track trajectory\n prev_block = self.get_block_pose(old_state)\n new_block = self.get_block_pose(self.state)\n self._dd.draw_transition(prev_block, new_block)\n\n # render current pose\n self._draw_state()\n\n cost, done = self.evaluate_cost(self.state, action)\n self._dd.draw_text('cost', '{0:.3f}'.format(cost), 0)\n\n # summarize information per sim step into information for entire control step\n info = self._aggregate_info()\n\n # prepare for next control step\n self._clear_state_between_control_steps()\n\n return cost, done, info\n\n # --- control (commonly overridden)\n def _move_pusher(self, end):\n p.changeConstraint(self.pusherConstraint, end, maxForce=self.max_pusher_force)\n\n def _move_and_wait(self, eePos, steps_to_wait=50):\n # execute the action\n self._move_pusher(eePos)\n p.stepSimulation()\n for _ in range(steps_to_wait):\n self._observe_info()\n p.stepSimulation()\n if self.mode is p.GUI and self.sim_step_wait:\n time.sleep(self.sim_step_wait)\n\n def step(self, action):\n old_state = self._obs()\n d = action\n # set end effector pose\n z = self.initPusherPos[2]\n eePos = [old_state[0] + d[0], old_state[1] + d[1], z]\n\n # execute the action\n self._move_and_wait(eePos)\n cost, done, info = self._finish_action(old_state, action)\n\n return np.copy(self.state), -cost, done, info\n\n def reset(self):\n # reset robot to nominal pose\n p.resetBasePositionAndOrientation(self.pusherId, self.initPusherPos, [0, 0, 0, 1])\n p.resetBasePositionAndOrientation(self.blockId, self.initBlockPos,\n p.getQuaternionFromEuler([0, 0, self.initBlockYaw]))\n # set robot init config\n if self.pusherConstraint:\n p.removeConstraint(self.pusherConstraint)\n self.pusherConstraint = p.createConstraint(self.pusherId, -1, -1, -1, p.JOINT_FIXED, [0, 0, 1], [0, 0, 0],\n self.initPusherPos)\n self._clear_state_between_control_steps()\n # start at rest\n for _ in range(1000):\n p.stepSimulation()\n self.state = self._obs()\n self._dd.draw_2d_pose('x0', self.get_block_pose(self.state), color=(0, 1, 0))\n return np.copy(self.state)\n\n\nclass PushAgainstWallStickyEnv(PushAgainstWallEnv):\n \"\"\"\n Pusher in this env is forced to stick to the block; control is how much to slide along the side of the block and\n how much to push perpendicularly into the adjacent face\n \"\"\"\n nu = 2\n nx = 4\n ny = 4\n MAX_SLIDE = 0.3\n MAX_INTO = 0.01\n\n @staticmethod\n def state_names():\n return ['x block (m)', 'y block (m)', 'block rotation (rads)', 'pusher along face (m)']\n\n @staticmethod\n def get_block_pose(state):\n return state[:3]\n\n @staticmethod\n def get_pusher_pos(state, action=None):\n along = state[3]\n pos = pusher_pos_for_touching(state[:2], state[2], from_center=DIST_FOR_JUST_TOUCHING, face=BlockFace.LEFT,\n along_face=along * _MAX_ALONG)\n return pos\n\n @staticmethod\n @handle_data_format_for_state_diff\n def state_difference(state, other_state):\n dyaw = math_utils.angular_diff_batch(state[:, 2], other_state[:, 2])\n dpos = state[:, :2] - other_state[:, :2]\n dalong = state[:, 3] - other_state[:, 3]\n return dpos, dyaw.reshape(-1, 1), dalong.reshape(-1, 1)\n\n @staticmethod\n def state_distance(state_difference):\n state_difference[:, 2] *= _RADIUS_GYRATION\n return state_difference[:, :3].norm(dim=1)\n\n @classmethod\n def state_cost(cls):\n return np.diag([10, 10, 0, 0.01])\n\n @staticmethod\n def control_names():\n return ['d$p$', 'd push forward (m)']\n\n @staticmethod\n def get_control_bounds():\n u_min = np.array([-1, 0])\n u_max = np.array([1, 1])\n return u_min, u_max\n\n @classmethod\n def control_cost(cls):\n return np.diag([0.01 for _ in range(cls.nu)])\n\n def __init__(self, init_pusher=0, face=BlockFace.LEFT, **kwargs):\n # initial config\n self.face = face\n super().__init__(init_pusher=init_pusher, **kwargs)\n\n def _set_goal(self, goal):\n # ignore the pusher position\n self.goal = np.array(tuple(goal) + (0.0, 0))\n\n def _set_init_pusher(self, init_pusher):\n pos = pusher_pos_for_touching(self.initBlockPos[:2], self.initBlockYaw, face=self.face,\n along_face=init_pusher * _MAX_ALONG)\n super()._set_init_pusher(pos)\n\n def _obs(self):\n xb, yb, yaw = self._observe_block()\n x, y, z = self._observe_pusher()\n along, from_center = pusher_pos_along_face((xb, yb), yaw, (x, y), self.face)\n # debugging to make sure we're quasi-static and adjacent to the block\n # logger.debug(\"dist between pusher and block %f\", from_center - DIST_FOR_JUST_TOUCHING)\n return xb, yb, yaw, along / _MAX_ALONG\n\n def step(self, action):\n old_state = self._obs()\n # first action is difference in along\n d_along = action[0] * self.MAX_SLIDE\n # second action is how much to go into the perpendicular face (>= 0)\n d_into = max(0, action[1]) * self.MAX_INTO\n\n from_center = DIST_FOR_JUST_TOUCHING - d_into\n # restrict sliding of pusher along the face (never to slide off)\n along = np.clip(old_state[3] + d_along, -1, 1)\n # logger.debug(\"along %f dalong %f\", along, d_along)\n pos = pusher_pos_for_touching(old_state[:2], old_state[2], from_center=from_center, face=self.face,\n along_face=along * _MAX_ALONG)\n # set end effector pose\n z = self.initPusherPos[2]\n eePos = np.concatenate((pos, (z,)))\n\n # execute the action\n self._move_and_wait(eePos)\n\n cost, done, info = self._finish_action(old_state, action)\n\n return np.copy(self.state), -cost, done, info\n\n\nclass PushWithForceDirectlyEnv(PushAgainstWallStickyEnv):\n \"\"\"\n Pusher in this env is abstracted and always sticks to the block; control is how much to slide along the side of the\n block, the magnitude of force to push with, and the angle to push wrt the block\n \"\"\"\n nu = 3\n nx = 4\n ny = 4\n MAX_PUSH_ANGLE = math.pi / 4 # 45 degree on either side of normal\n MAX_SLIDE = 0.3 # can slide at most 30/200 = 15% of the face in 1 move\n MAX_FORCE = 20\n\n @staticmethod\n def control_names():\n return ['d$p$', 'f push magnitude', '$\\\\beta$ push direction']\n\n @staticmethod\n def get_control_bounds():\n # depends on the env to perform normalization\n u_min = np.array([-1, 0, -1])\n u_max = np.array([1, 1, 1])\n return u_min, u_max\n\n def __init__(self, init_pusher=0, **kwargs):\n # initial config\n self.along = init_pusher\n super().__init__(init_pusher=init_pusher, face=BlockFace.LEFT, **kwargs)\n\n def _set_init_pusher(self, init_pusher):\n self.along = init_pusher\n super()._set_init_pusher(init_pusher)\n\n def _setup_experiment(self):\n super()._setup_experiment()\n # disable collision since we're applying a force directly on the block (pusher is for visualization for now)\n p.setCollisionFilterPair(self.pusherId, self.blockId, -1, -1, 0)\n\n def _draw_action(self, action, old_state=None, debug=0):\n old_state = self._obs()\n d_along, f_mag, f_dir = self._unpack_action(action)\n f_dir_world = f_dir + old_state[2]\n start = self._observe_pusher()\n start[2] = _BLOCK_HEIGHT\n pointer = math_utils.rotate_wrt_origin((f_mag / self.MAX_FORCE, 0), f_dir_world)\n if debug:\n self._dd.draw_2d_line('u{}'.format(debug), start, pointer, (1, debug / 10, debug / 10), scale=0.4)\n else:\n self._dd.draw_2d_line('u', start, pointer, (1, 0, 0), scale=0.4)\n\n def _obs(self):\n xb, yb, yaw = self._observe_block()\n return np.array((xb, yb, yaw, self.along))\n\n def _observe_additional_info(self, info, visualize=True):\n # assume there's 4 contact points between block and plane\n info['bp'] = np.zeros((4, 2))\n # push of plane onto block\n contactInfo = p.getContactPoints(self.blockId, self.planeId)\n # get reaction force on pusher\n reaction_force = [0, 0, 0]\n for i, contact in enumerate(contactInfo):\n if visualize and self._debug_visualizations[DebugVisualization.FRICTION]:\n self._dd.draw_contact_friction('bp{}'.format(i), contact)\n info['bp'][i] = (contact[ContactInfo.LATERAL1_MAG], contact[ContactInfo.LATERAL2_MAG])\n fy, fx = get_lateral_friction_forces(contact)\n reaction_force = [sum(i) for i in zip(reaction_force, fy, fx)]\n\n if self.level > 0:\n # assume at most 4 contact points\n info['bw'] = np.zeros(4)\n for wallId in self.walls:\n contactInfo = p.getContactPoints(self.blockId, wallId)\n for i, contact in enumerate(contactInfo):\n name = 'w{}'.format(i)\n info['bw'][i] = contact[ContactInfo.NORMAL_MAG]\n\n f_contact = get_total_contact_force(contact)\n reaction_force = [sum(i) for i in zip(reaction_force, f_contact)]\n\n # only visualize the largest contact\n if abs(contact[ContactInfo.NORMAL_MAG]) > abs(self._largest_contact.get(name, 0)):\n self._largest_contact[name] = contact[ContactInfo.NORMAL_MAG]\n if visualize and self._debug_visualizations[DebugVisualization.WALL_ON_BLOCK]:\n self._dd.draw_contact_point(name, contact)\n\n self._observe_raw_reaction_force(info, reaction_force, info)\n\n def _keep_pusher_adjacent(self):\n state = self._obs()\n pos = pusher_pos_for_touching(state[:2], state[2], from_center=DIST_FOR_JUST_TOUCHING, face=self.face,\n along_face=self.along * _MAX_ALONG)\n z = self.initPusherPos[2]\n eePos = np.concatenate((pos, (z,)))\n self._move_pusher(eePos)\n\n def _unpack_action(self, action):\n # normalize action such that the input can be within a fixed range\n # first action is difference in along\n d_along = action[0] * self.MAX_SLIDE\n # second action is push magnitude\n f_mag = max(0, action[1] * self.MAX_FORCE)\n # third option is push angle (0 being perpendicular to face)\n f_dir = np.clip(action[2], -1, 1) * self.MAX_PUSH_ANGLE\n return d_along, f_mag, f_dir\n\n def step(self, action):\n old_state = self._obs()\n if self._debug_visualizations[DebugVisualization.ACTION]:\n self._draw_action(action)\n\n d_along, f_mag, f_dir = self._unpack_action(action)\n\n # execute action\n ft = math.sin(f_dir) * f_mag\n fn = math.cos(f_dir) * f_mag\n\n # repeat action so that each resulting step can be larger\n for _ in range(self.mini_steps):\n # apply force on the left face of the block at along\n p.applyExternalForce(self.blockId, -1, [fn, ft, 0], [-_MAX_ALONG, self.along * _MAX_ALONG, 0], p.LINK_FRAME)\n p.stepSimulation()\n\n # also move the pusher along visually\n self._keep_pusher_adjacent()\n for t in range(self.wait_sim_step_per_mini_step):\n self._observe_info()\n\n p.stepSimulation()\n if self.mode is p.GUI and self.sim_step_wait:\n time.sleep(self.sim_step_wait)\n\n # apply the sliding along side after the push settles down\n self.along = np.clip(old_state[3] + d_along, -1, 1)\n self._keep_pusher_adjacent()\n\n for _ in range(20):\n p.stepSimulation()\n if self.mode is p.GUI and self.sim_step_wait:\n time.sleep(self.sim_step_wait)\n\n cost, done, info = self._finish_action(old_state, action)\n\n return np.copy(self.state), -cost, done, info\n\n\nREACTION_Q_COST = 0.0\n\n\nclass PushWithForceDirectlyReactionInStateEnv(PushWithForceDirectlyEnv):\n \"\"\"\n Same as before, but have reaction force inside the state\n \"\"\"\n nu = 3\n nx = 6\n ny = 6\n\n @staticmethod\n def state_names():\n return ['$x_b$ (m)', '$y_b$ (m)', '$\\\\theta$ (rads)', '$p$ (m)', '$r_x$ (N)', '$r_y$ (N)']\n\n @staticmethod\n @handle_data_format_for_state_diff\n def state_difference(state, other_state):\n dyaw = math_utils.angular_diff_batch(state[:, 2], other_state[:, 2])\n dpos = state[:, :2] - other_state[:, :2]\n dalong = state[:, 3] - other_state[:, 3]\n dreaction = state[:, 4:6] - other_state[:, 4:6]\n return dpos, dyaw.reshape(-1, 1), dalong.reshape(-1, 1), dreaction\n\n @classmethod\n def state_cost(cls):\n return np.diag([10, 10, 0, 0.01, REACTION_Q_COST, REACTION_Q_COST])\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n # we render this directly when rendering state so no need to double count\n self._debug_visualizations[DebugVisualization.REACTION_ON_PUSHER] = False\n\n def _set_goal(self, goal_pos):\n # want 0 reaction force\n self.goal = np.array(tuple(goal_pos) + (0, 0) + (0, 0))\n\n def visualize_prediction_error(self, predicted_state):\n super().visualize_prediction_error(predicted_state)\n if self._debug_visualizations[DebugVisualization.REACTION_IN_STATE]:\n self._draw_reaction_force(predicted_state[4:6], 'pr', (0.5, 0, 0.5))\n\n def _draw_state(self):\n super()._draw_state()\n # NOTE this is visualizing the reaction from the previous action, rather than the current action\n if self._debug_visualizations[DebugVisualization.REACTION_IN_STATE]:\n self._draw_reaction_force(self.state[3:5], 'sr', (0, 0, 0))\n\n def _obs(self):\n state = super()._obs()\n state = np.concatenate((state, self._observe_reaction_force()))\n return state\n\n\nclass PushPhysicallyAnyAlongEnv(PushAgainstWallStickyEnv):\n \"\"\"\n Pusher in this env is abstracted and always sticks to the block; control is change in position of pusher\n in block frame, and where along the side of the block to push\n \"\"\"\n nu = 3\n nx = 5\n ny = 5\n MAX_PUSH_ANGLE = math.pi / 4 # 45 degree on either side of normal\n MAX_PUSH_DIST = _MAX_ALONG / 4 # effectively how many moves of pushing straight to move a half block\n\n @staticmethod\n def state_names():\n return ['$x_b$ (m)', '$y_b$ (m)', '$\\\\theta$ (rads)', '$r_x$ (N)', '$r_y$ (N)']\n\n @staticmethod\n def get_pusher_pos(state, action=None):\n along = 0 if action is None else action[0]\n pos = pusher_pos_for_touching(state[:2], state[2], from_center=DIST_FOR_JUST_TOUCHING, face=BlockFace.LEFT,\n along_face=along * _MAX_ALONG)\n return pos\n\n @staticmethod\n @handle_data_format_for_state_diff\n def state_difference(state, other_state):\n dyaw = math_utils.angular_diff_batch(state[:, 2], other_state[:, 2])\n dpos = state[:, :2] - other_state[:, :2]\n dreaction = state[:, 3:5] - other_state[:, 3:5]\n return dpos, dyaw.reshape(-1, 1), dreaction\n\n @classmethod\n def state_cost(cls):\n return np.diag([10, 10, 0, REACTION_Q_COST, REACTION_Q_COST])\n\n @staticmethod\n def control_names():\n return ['$p$', 'd push distance', '$\\\\beta$ push angle (wrt normal)']\n\n @classmethod\n def control_cost(cls):\n return np.diag([0, 1, 0])\n\n @staticmethod\n def get_control_bounds():\n u_min = np.array([-1, 0, -1])\n u_max = np.array([1, 1, 1])\n return u_min, u_max\n\n @staticmethod\n @handle_data_format_for_state_diff\n def control_similarity(u1, u2):\n # TODO should probably keep the API numpy only\n u1 = torch.stack((u1[:, 0], u1[:, 2]), dim=1)\n u2 = torch.stack((u2[:, 0], u2[:, 2]), dim=1)\n return torch.cosine_similarity(u1, u2, dim=-1).clamp(0, 1)\n\n def _set_goal(self, goal_pos):\n self.goal = np.array(tuple(goal_pos) + (0,) + (0, 0))\n\n def visualize_prediction_error(self, predicted_state):\n super().visualize_prediction_error(predicted_state)\n if self._debug_visualizations[DebugVisualization.REACTION_IN_STATE]:\n self._draw_reaction_force(predicted_state[3:5], 'pr', (0.5, 0, 0.5))\n\n def _draw_state(self):\n super()._draw_state()\n # NOTE this is visualizing the reaction from the previous action, rather than the instantaneous reaction\n if self._debug_visualizations[DebugVisualization.REACTION_IN_STATE]:\n self._draw_reaction_force(self.state[3:5], 'sr', (0, 0, 0))\n\n def _draw_action(self, action, old_state=None, debug=0):\n if old_state is None:\n old_state = self._obs()\n push_along, push_dist, push_dir = self._unpack_action(action)\n start = pusher_pos_for_touching(old_state[:2], old_state[2], from_center=DIST_FOR_JUST_TOUCHING, face=self.face,\n along_face=push_along)\n start = np.concatenate((start, (_BLOCK_HEIGHT,)))\n pointer = math_utils.rotate_wrt_origin((push_dist, 0), push_dir + old_state[2])\n if debug:\n self._dd.draw_2d_line('u{}'.format(debug), start, pointer, (1, debug / 30, debug / 10), scale=5)\n else:\n self._dd.draw_2d_line('u', start, pointer, (1, 0, 0), scale=5)\n\n def _obs(self):\n state = np.concatenate((self._observe_block(), self._observe_reaction_force()))\n return state\n\n def _observe_additional_info(self, info, visualize=True):\n reaction_force = [0, 0, 0]\n\n contactInfo = p.getContactPoints(self.pusherId, self.blockId)\n info['npb'] = len(contactInfo)\n for i, contact in enumerate(contactInfo):\n f_contact = get_total_contact_force(contact, False)\n reaction_force = [sum(i) for i in zip(reaction_force, f_contact)]\n\n name = 'r{}'.format(i)\n if abs(contact[ContactInfo.NORMAL_MAG]) > abs(self._largest_contact.get(name, 0)):\n self._largest_contact[name] = contact[ContactInfo.NORMAL_MAG]\n if visualize and self._debug_visualizations[DebugVisualization.BLOCK_ON_PUSHER]:\n self._dd.draw_contact_point(name, contact, False)\n\n self._observe_raw_reaction_force(info, reaction_force, visualize)\n\n def _unpack_action(self, action):\n push_along = action[0] * (_MAX_ALONG * 0.98) # avoid corner to avoid leaving contact\n push_dist = action[1] * self.MAX_PUSH_DIST\n push_dir = action[2] * self.MAX_PUSH_ANGLE\n return push_along, push_dist, push_dir\n\n def step(self, action):\n action = np.clip(action, *self.get_control_bounds())\n # normalize action such that the input can be within a fixed range\n old_state = self._obs()\n push_along, push_dist, push_dir = self._unpack_action(action)\n\n pos = pusher_pos_for_touching(old_state[:2], old_state[2], from_center=DIST_FOR_JUST_TOUCHING, face=self.face,\n along_face=push_along)\n start_ee_pos = np.concatenate((pos, (self.initPusherPos[2],)))\n self._dd.draw_point('start eepos', start_ee_pos, color=(0, 0.5, 0.8))\n\n # first get to desired starting push position (should experience no reaction force during this move)\n # self._move_and_wait(start_ee_pos, steps_to_wait=50)\n # alternatively reset pusher (this avoids knocking the block over)\n p.resetBasePositionAndOrientation(self.pusherId, start_ee_pos, p.getQuaternionFromEuler([0, 0, 0]))\n\n if self._debug_visualizations[DebugVisualization.ACTION]:\n self._draw_action(action)\n\n dx = np.cos(push_dir) * push_dist\n dy = np.sin(push_dir) * push_dist\n pos = pusher_pos_for_touching(old_state[:2], old_state[2], from_center=DIST_FOR_JUST_TOUCHING - dx,\n face=self.face, along_face=push_along + dy)\n final_ee_pos = np.concatenate((pos, (self.initPusherPos[2],)))\n self._dd.draw_point('final eepos', final_ee_pos, color=(0, 0.5, 0.5))\n\n # execute push with mini-steps\n for step in range(self.mini_steps):\n intermediate_ee_pos = interpolate_pos(start_ee_pos, final_ee_pos, (step + 1) / self.mini_steps)\n self._move_and_wait(intermediate_ee_pos, steps_to_wait=self.wait_sim_step_per_mini_step)\n\n cost, done, info = self._finish_action(old_state, action)\n\n return np.copy(self.state), -cost, done, info\n\n\ndef interpolate_pos(start, end, t):\n return t * end + (1 - t) * start\n\n\nclass InteractivePush(PybulletSim):\n def __init__(self, env: PushAgainstWallEnv, ctrl, save_dir='pushing', **kwargs):\n super(InteractivePush, self).__init__(env, ctrl, save_dir=save_dir, **kwargs)\n\n def _setup_experiment(self):\n self.ctrl.set_goal(self.env.goal)\n return simulation.ReturnMeaning.SUCCESS\n\n\nclass PushDataSource(EnvDataSource):\n loader_map = {PushAgainstWallEnv: PushLoader,\n PushAgainstWallStickyEnv: PushLoaderRestricted,\n PushWithForceDirectlyEnv: PushLoaderRestricted,\n PushWithForceDirectlyReactionInStateEnv: PushLoaderWithReaction,\n PushPhysicallyAnyAlongEnv: PushLoaderPhysicalPusherWithReaction, }\n\n @staticmethod\n def _default_data_dir():\n return \"pushing\"\n\n @staticmethod\n def _loader_map(env_type):\n return PushDataSource.loader_map.get(env_type, None)\n","sub_path":"tampc/env/block_push.py","file_name":"block_push.py","file_ext":"py","file_size_in_byte":44240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"396085673","text":"import asyncio\nimport random\nfrom myLib import *\nfrom keepAlive import *\nfrom bfxapi import Client\n\n#sleep time (s)\noneRoundTime = 600;\n\nlastRoundOffer = -1\nsymbol = 'UST'\nminRate = 0.00045\ntwo_threshold = 0.00053\nseven_threshold = 0.0007\nadjustClock = 0\n# adjust every period*10min \nadjustPeriod = 3\n#decay every half an hour\n#0.99^12 = 0.886\n#0.99^6 = 0.94\n#0.98^6 = 0.885\n#0.98^12 = 0.78\ndecay_rate = 0.98\n#estimate lend it 3 hour at most\n\nasync def adjust_offer(user, symbol):\n offers = await funding_offers(user, symbol)\n for offer in offers:\n old_id = offer.id\n old_rate = offer.rate\n old_amount = offer.amount\n await cancel_funding(user, old_id)\n await asyncio.sleep(2)\n #adjust rate 0.98^6 = 0.885\n rate = old_rate * decay_rate\n period = periodCalc(symbol, rate)\n if period < 2:\n print(\"rate too low. Not to create offer\")\n return\n await create_funding(user, symbol, old_amount, rate, period)\n return\n \n# get avg of market low & frr +max% ~ -min%\nasync def floatRate(symbol, min = 0, max = 1):\n frr = await getFRR(symbol)\n market = await lendBookAvg(symbol)\n print(\"frr : \",frr)\n print(\"cur market low : \", market)\n floating = random.randint(min*100,max*100)/100\n percent = 1 + floating/100\n return (frr+market) * percent / 2\n \n \nasync def lend(user, symbol, remain):\n mOffer = minOffer(symbol)\n if mOffer == -1:\n print(\"min offer of\",symbol,'not defined')\n return\n if remain < mOffer:\n print(\"avaliable money not enough\")\n return\n # offer amount \n amount = mOffer\n if remain < mOffer*2:\n amount = remain\n #rate\n rate = await floatRate(symbol)\n period = periodCalc(symbol, rate)\n if period < 2:\n print(\"rate too low. Not to create offer\")\n return\n await create_funding(user, symbol, amount, rate, period)\n await asyncio.sleep(1)\n return\n\n\ndef periodCalc(symbol, rate):\n if rate < minRate:\n return -1\n if rate < two_threshold:\n return 2\n if rate < seven_threshold:\n return 7\n return 30\n \n#########################################\n\ndef readAccounts():\n file = open('./data.txt',mode='r')\n data = file.read().splitlines()\n for line in data:\n acc = line.split(';')\n user = Client(API_KEY=acc[0],API_SECRET=acc[1],logLevel='DEBUG')\n users.append(user)\n \n\n \n\nasync def main():\n while True:\n\n global adjustClock\n adjustClock = adjustClock+1\n adjustClock = adjustClock%adjustPeriod;\n #update market price\n global lastRoundOffer\n lastRoundOffer = await lendBookAvg(symbol)\n #await lendBook(symbol)\n\n for user in users:\n remain = await get_avaliable_money(user,symbol)\n print('avaliable',symbol,remain)\n if adjustClock == 0:\n print(\"##adjust offers...##\")\n #just adjust every 6 turn (1 hour)\n #adjust offer\n await adjust_offer(user, symbol)\n #lend\n while remain > minOffer(symbol):\n await lend(usymbol, remain)\n remain = await get_avaliable_money(user, symbol)\n \n \n #update web\n await updateWeb(users)\n\n # sleep a while before do next round\n print(\"###########################\")\n\n await asyncio.sleep(oneRoundTime)\n\nusers = []\nreadAccounts()\nkeep_alive()\nt = asyncio.ensure_future(main())\nasyncio.get_event_loop().run_forever()\n","sub_path":"mainBot.py","file_name":"mainBot.py","file_ext":"py","file_size_in_byte":3255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"618861750","text":"# Storage tanks\n# Assumes 36 ft tall tank w/ 1 million gallon capacity = 27778 gallons per foot\n# Assumes 16 inch diam transfer piping\ntank1 = tank.Tank(\"Tank 1\", level=36.0, fluid_density=DENSITY, spec_gravity=SPEC_GRAVITY, outlet_diam=16, outlet_slope=0.25)\ntank1.static_tank_press = tank1.level\ntank1.gravity_flow(tank1.pipe_diam, tank1.pipe_slope, tank1.pipe_coeff)\n\ntank2 = tank.Tank(\"Tank 2\", level=36.0, fluid_density=DENSITY, spec_gravity=SPEC_GRAVITY, outlet_diam=16, outlet_slope=0.25)\ntank2.static_tank_press = tank2.level\ntank2.gravity_flow(tank2.pipe_diam, tank2.pipe_slope, tank2.pipe_coeff)\n","sub_path":"275-Langs/Python/Learn Programming in Python with Cody Jackson/Chapter 9/components(part3).py","file_name":"components(part3).py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"93617201","text":"\n\ndef memoize(f):\n\tmem = {}\n\tdef g(x):\n\t\tif x not in mem:\n\t\t\tmem[x] = f(x)\n\t\treturn mem[x]\n\treturn g\n\n@memoize\ndef fib(n):\n\tif n == 0:\n\t\treturn 0\n\tif n == 1:\n\t\treturn 1\n\telse:\n\t\treturn fib(n-1) + fib(n-2)\n\n\n\nprint(fib(100))\n","sub_path":"Tools/memo.py","file_name":"memo.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"509966942","text":"stations = ['Schagen', 'Heerhugowaard', 'Alkmaar', 'Castricum', 'Zaandam', 'Amsterdam Sloterdijk', 'Amsterdam Centraal',\n 'Amsterdam Amstel', 'Utrecht Centraal', \"’s-Hertogenbosch\", 'Eindhoven', 'Weert', 'Roermond', 'Sittard',\n 'Maastricht']\n\ndef inlezen_beginstation(stations):\n while True:\n station = input ('Geef uw beginstation: ')\n if station in stations:\n beginstation = station\n break\n else:\n print ('Deze trein komt niet in ' + str (station))\n return station\n\ndef inlezen_eindstation(stations, beginstation):\n while True:\n eindstation = input ('Geef uw eindstation: ')\n if eindstation in stations:\n index_begin = stations.index (beginstation)\n index_eindstation = stations.index (eindstation)\n if index_begin < index_eindstation:\n break\n else:\n print ('Dit station ligt niet op het komende traject')\n else:\n print ('Dit station ligt niet op het traject')\n return eindstation\n\ndef omroepen_reis(stations, beginstation, eindstation):\n afstand = stations.index (eindstation) - stations.index (beginstation)\n print ('Het beginstation ' + str (beginstation) + ' is het ' + str (stations.index (beginstation) + 1) + 'e station in het traject.')\n print ('Het eindstation ' + str (eindstation) + ' is het ' + str (stations.index (eindstation) + 1) + 'e station in het traject.')\n print ('De afstand bedraagt ' + str (afstand) + ' station(s)')\n print ('De prijs van een kaartje bedraagt: ' + str (afstand * 5) + ' Euro.')\n print ('Jij stapt in de trein in: ' + str (beginstation))\n for station in stations:\n if stations.index (station) > stations.index (beginstation) and stations.index (station) < stations.index (\n eindstation):\n print (' -' + str (station))\n print ('Jij stapt uit in: ' + str (eindstation))\n\nbeginstation = inlezen_beginstation (stations)\neindstation = inlezen_eindstation (stations, beginstation)\nomroepen_reis (stations, beginstation, eindstation)\n","sub_path":"PycharmProjects/PROG/Les 8/Ns Final Assignment.py","file_name":"Ns Final Assignment.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"597527069","text":"\"\"\"Day 14: Docking Data\n\nInterface with a docking computer doing bit masking to store values\nin memory.\n\"\"\"\n\nfrom itertools import product\nfrom typing import Generator, Union, List\n\nclass MaskCommand:\n \"\"\"A command that parses and sets the mask for subsequent memory\n setting commands to be filtered through.\n\n Properties:\n bits (list(int)): The original bit-string of 1's, 0's, and X's.\n and_ (int): A value to be `&`-ed with memory values to set some\n bits to 0 no matter what\n or_ (int): A value to be `|`-ed with memory values to set some\n bits to 1 no matter what\n floating (list(int)): Indices where X's live, to help with\n generating floating bits.\n \"\"\"\n def __init__(self, s: str):\n self.bits = s\n self.and_ = 0\n self.or_ = 0\n self.floating: list(int) = []\n for i, c in enumerate(s):\n if c == '0':\n self.and_ |= (1 << (35 - i))\n elif c == '1':\n self.or_ |= (1 << (35 - i))\n elif c == 'X':\n self.floating.append(i)\n self.and_ = (~self.and_) & 0xFFFFFFFFF\n\n @staticmethod\n def generate_binary(digits: int) -> Generator[str, None, None]:\n \"\"\"Generates strings of binary digits for all values between\n 0 and 2**(digits)-1 (i.e. all possible sequences of 1's and 0's.)\n \"\"\"\n for i in range(1 << digits):\n yield f\"{i:0{digits}b}\"\n\n def v2_addresses(self, command: Union['MaskCommand', 'SetCommand']) -> Generator[List[str], None, None]:\n \"\"\"Generates addresses following V2 guidelines.\n \n Performs an OR between the command's address and the mask, and\n then generates every possible string made up of 1's and 0's in\n place of all the floating bits (X's).\n\n The OR assumes X's take precedence.\n\n e.g. 110X0X (after the OR) would yield 110000, 110001, 110100,\n and 110101.\n \"\"\" \n merged = [c_bit if m_bit == '0' else m_bit\n for (m_bit, c_bit) in zip(self.bits, command.bits)]\n for comb in MaskCommand.generate_binary(len(self.floating)):\n for index, bit in zip(self.floating, comb):\n merged[index] = bit\n yield merged\n\n\nclass SetCommand:\n \"\"\"A command to set memory to some value. Stores the address and\n value to be stored there. Used for both V1 and V2, so includes both\n and integer version of the address and the bits for compatability.\n\n Properties:\n value (int): The value to be stored.\n address (int): The location in memory to store the value.\n bits (str): A string representation of the 0's and 1's that\n make up the binary value for the address. (36 bits wide).\n \"\"\"\n def __init__(self, address: str, value: str):\n self.value = int(value)\n self.address = int(address)\n self.bits = f\"{self.address:036b}\"\n\n\ndef parse(filename: str) -> List[Union[MaskCommand, SetCommand]]:\n \"\"\"Parse the input file into a list of commands.\"\"\"\n commands = []\n with open(filename, \"r\") as f:\n for line in f:\n if line.startswith(\"mask\"):\n commands.append(MaskCommand(line[7:]))\n else:\n parts = line.split()\n commands.append(SetCommand(parts[0][4:-1], parts[-1]))\n return commands\n\n\ndef part1(commands: List[Union[MaskCommand, SetCommand]]) -> int:\n \"\"\"Find the sum of all values in memory after running all commands\n following the V1 spec.\n \"\"\"\n memory = dict()\n mask = None\n for command in commands:\n if isinstance(command, MaskCommand):\n mask = command\n else:\n new_value = (command.value & mask.and_) | mask.or_\n memory[command.address] = new_value\n \n return sum(memory.values())\n\n\ndef part2(commands: List[Union[MaskCommand, SetCommand]]) -> int:\n \"\"\"Find the sum of all values in memory after running all commands\n following the V2 spec.\n \"\"\"\n memory = dict()\n mask = None\n for command in commands:\n if isinstance(command, MaskCommand):\n mask = command\n else:\n for address in mask.v2_addresses(command):\n memory[\"\".join(address)] = command.value\n return sum(memory.values())\n\n\nif __name__ == \"__main__\":\n assert 165 == part1(parse(\"data/day14_test.txt\"))\n assert 208 == part2(parse(\"data/day14_test2.txt\"))\n print(\"All tests passed.\")\n commands = parse(\"data/day14.txt\")\n print(part1(commands))\n print(part2(commands))","sub_path":"src/Day14.py","file_name":"Day14.py","file_ext":"py","file_size_in_byte":4649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"26895801","text":"\n\nfrom abc import ABCMeta, abstractmethod\nimport threading\nimport urllib.request\nimport os\nimport re\n\nmailRegex = re.compile(r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+', re.I)\n\nfrom bs4 import BeautifulSoup\n# 伪装成FireFox\ndef request(url):\n req = urllib.request.Request(url)\n req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0');\n page = urllib.request.urlopen(req)\n soup = BeautifulSoup(page)\n\n return soup\n\n# 清���无用内容\ndef trim(soup, classes=[], tagNames=[]):\n \n if soup == None:\n return \n \n # 过滤指定无用标签\n for tagName in tagNames:\n tags = soup(tagName)\n trimContent(tags)\n \n # 过滤带有无用class的标签\n for class_ in classes:\n tags = soup('div', {'class':class_})\n trimContent(tags)\n \n return soup\n\n# clear process\ndef trimContent(tags):\n if tags != None:\n for tag in tags:\n tag.decompose()\n\n\ndef mergeData(writeFile,pages):\n \n file=open(writeFile, 'wb')\n file.write(bytes('','utf8'))\n \n for index in range(1,pages+1):\n data=open('temp/temp'+str(index)+'.html', 'rb')\n file.write(data.read())\n data.close()\n os.remove('temp/temp'+str(index)+'.html')\n \n file.close()\n \ndef getTempFile(index):\n if not os.path.exists(\"temp\"):\n os.mkdir(\"temp\")\n file = open('temp/temp' + str(index) + '.html', 'w', encoding='utf8')\n return file\n\nclass Core:\n __metaclass__ = ABCMeta\n \n @abstractmethod\n def work(self,url,index,model):pass\n \n\n# 爬虫工作线程\nclass SpiderThread(threading.Thread):\n index = 1\n model=1\n url=''\n core=''\n \n def __init__(self, index,url,model,core):\n threading.Thread.__init__(self)\n self.index=index\n self.url = url\n self.model=model\n self.core=core\n \n def run(self):\n self.core.work(self.url,self.index,self.model)\n\nclass Spider:\n threads=[]\n \n def __init__(self,core):\n \n if core is None:\n raise Exception(\"参数是必须的!\")\n \n if isinstance(core, Core):\n self.core=core\n else:\n raise Exception(\"传递的参数必须是Core类型!\")\n \n def startThread(self,index,url,model):\n ths = SpiderThread(index,url,model,self.core)\n ths.start()\n self.threads.append(ths)\n \n def block(self):\n for subThread in self.threads:\n subThread.join()","sub_path":"spider_core.py","file_name":"spider_core.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"551634776","text":"import sys\nimport argparse\nfrom Bio import SeqIO\nfrom Bio.SeqIO import FastaIO\n\ndef parseArgument():\n # Parse the input\n parser=argparse.ArgumentParser(description=\\\n \"Make the reverse complements of all sequences in a fasta file\")\n parser.add_argument(\"--fastaFileName\", required=True,\\\n help='Name of the original fasta file')\n parser.add_argument(\"--outputFileName\", required=True,\\\n help='fasta file where the sequences that are the reverse complements will be written')\n options = parser.parse_args()\n return options\n\ndef reverseComplementFasta(options):\n\t# Make the reverse complements of all sequences in a fasta file\n\tseqRecordRCList = []\n\toutputFile = open(options.outputFileName, 'w+')\n\tfastaOut = FastaIO.FastaWriter(outputFile, wrap=None)\n\tfor seqRecord in SeqIO.parse(options.fastaFileName,\"fasta\"):\n\t\t# Iterate through the sequences and get the reverse complement of each\n\t\tseqRecordRC = seqRecord.reverse_complement()\n\t\tseqRecordRC.id = seqRecord.id + \"_RC\"\n\t\tseqRecordRCList.append(seqRecordRC)\n\tfastaOut.write_file(seqRecordRCList)\n\nif __name__ == \"__main__\":\n options = parseArgument()\n reverseComplementFasta(options)\n","sub_path":"evaluationScriptsCortexLiverModels/reverseComplementFasta.py","file_name":"reverseComplementFasta.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"436557531","text":"from meshu.models import Meshu, MeshuImage, UserProfile, Order, ShippingInfo\nfrom django.contrib import admin\n\n# How Meshus are displayed\nclass MeshuImageInline(admin.TabularInline):\n\tmodel = MeshuImage\n\textra = 2\n\nclass MeshuInline(admin.TabularInline):\n\tmodel = Meshu\n\textra = 1\n\nclass MeshuAdmin(admin.ModelAdmin):\n\tfieldsets = [\n\t\t(None, {\n 'fields': ('user_profile', 'title', 'description', 'location_data', 'svg', 'theta', 'renderer', 'metadata', 'product', 'thumbnail')\n }),\n\t]\n\tinlines = [ MeshuImageInline, ]\n\n\traw_id_fields = ('user_profile', )\n\tlist_display = ('title', 'date_created', 'renderer', 'user_profile')\n\nadmin.site.register(Meshu, MeshuAdmin)\n\n\n# How Orders are displayed\nclass OrderMiniInline(admin.StackedInline):\n\tmodel = Order\n\traw_id_fields = (\"user_profile\",)\n\textra = 0\n\n\tfieldsets = [\n\t\t('Double Check', {\n\t\t\t'fields': ('special_instructions', 'postcard_note', 'tracking')\n\t\t}),\n\t\t('Order Details', {\n\t\t\t'fields': ('status', 'product', 'material', 'color')\n\t\t})\n\t]\n\nclass OrderInline(admin.StackedInline):\n\tmodel = Order\n\traw_id_fields = (\"user_profile\",)\n\textra = 0\n\nclass OrderAdmin(admin.ModelAdmin):\n\tfieldsets = [\n\t\t('Order', {\n\t\t\t'fields': ('user_profile', 'meshu', 'product', 'material', 'color', 'postcard_note',)\n\t\t}),\n\t\t('Order Details', {\n\t\t\t'fields': ('status', 'amount', 'metadata', 'special_instructions', 'coupon',)\n\t\t}),\n\t\t('Shipping', {\n\t\t\t'fields': ('shipping',)\n\t\t}),\n\t\t('Order Shipped Status', {\n\t\t\t'classes': ['collapse'],\n\t\t\t'fields': ['postcard_ordered', 'ship_date', 'tracking']\n\t\t})\n\t]\n\n\traw_id_fields = ('meshu', 'user_profile', )\n\tlist_display = ('__unicode__', 'user_profile','shipping', 'meshu', 'product', 'amount', 'status', 'date_created')\n\nadmin.site.register(Order, OrderAdmin)\n\nclass UserProfileAdmin(admin.ModelAdmin):\n\tinlines = [OrderMiniInline]\n\tlist_display = ('user_email', 'amount_meshus', 'amount_orders', 'date_joined')\n\nadmin.site.register(UserProfile, UserProfileAdmin)\n\n\nclass ShippingInfoAdmin(admin.ModelAdmin):\n\tmodel = ShippingInfo\n\textra = 0\n\n\tfieldsets = [\n\t\t('Contact', {\n\t\t\t'fields': ('contact',)\n\t\t}),\n\t\t('Shipping Information', {\n\t\t\t'fields': ['shipping_name', 'shipping_address', 'shipping_address_2', 'shipping_city', 'shipping_zip', 'shipping_state', 'shipping_region', 'shipping_country']\n\t\t})\n\t]\n\n\tinlines = [OrderMiniInline]\n\nadmin.site.register(ShippingInfo, ShippingInfoAdmin)\n","sub_path":"meshu/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"304931476","text":"from __future__ import absolute_import\n\nfrom .base import ModelLoader\nfrom ..models.cifar10 import (nin_bn_model, vgg_model, densenet_model,\n resnet_model)\n\nclass NiNBN(ModelLoader):\n\n def __call__(self):\n return nin_bn_model(l2_reg=self.l2)\n\n def default_args(self):\n args = super(NiNBN, self).default_args()\n args['batch_size'] = 64\n return args\n\nclass VGGBN(ModelLoader):\n\n def __call__(self):\n return vgg_model(l2_reg=self.l2)\n\n def default_args(self):\n args = super(VGGBN, self).default_args()\n args['batch_size'] = 128\n args['l2'] = 5e-4\n return args\n\nclass Densenet(ModelLoader):\n def __init__(self, args):\n super(Densenet, self).__init__(args)\n self.params = []\n for a in args['model'][1:]:\n try:\n b = int(a)\n except ValueError:\n b = float(a)\n\n self.params.append(b)\n\n def __call__(self):\n return densenet_model(*self.params, l2_reg=self.l2)\n\n def default_args(self):\n args = super(Densenet, self).default_args()\n args['batch_size'] = 64\n args['epochs'] = 300\n args['schedule'] = 'step_densenet'\n return args\n\nclass Resnet(ModelLoader):\n def __init__(self, args):\n super(Resnet, self).__init__(args)\n self.params = []\n for a in args['model'][1:]:\n try:\n b = int(a)\n except ValueError:\n b = a == 'True'\n\n self.params.append(b)\n\n def __call__(self):\n return resnet_model(*self.params)\n\n def default_args(self):\n args = super(Resnet, self).default_args()\n args['batch_size'] = 64\n args['epochs'] = 164\n args['schedule'] = 'step_resnet'\n return args\n","sub_path":"rme/loaders/cifar10.py","file_name":"cifar10.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"211911652","text":"from ..lang.prex import (\n Analysis,\n Lexer,\n Parser,\n AZeroOrMoreQuantifier,\n AOneOrMoreQuantifier,\n AZeroOrOneQuantifier,\n)\nfrom ..nfa.graph import (\n NFA,\n Symbol,\n)\nfrom prex.prnml import (\n model as prnml,\n)\nfrom prex.util import (\n memoized,\n keydefaultdict,\n)\nimport io\nimport re\nimport pathlib\nfrom collections import defaultdict\n\n\nclass NFAConstructor(Analysis):\n def __init__(self, location_prefix):\n super().__init__()\n self.location_prefix = location_prefix\n self._nfa = NFA()\n self.location_number = 0\n\n def _get_loc(self):\n loc = self._nfa.location(\n f'{self.location_prefix}_{self.location_number}'\n )\n self.location_number += 1\n return loc\n\n def _get_symbol_domain(self, exclude=set()):\n raise NotImplementedError\n\n def get_nfa(self):\n return self._nfa\n\n def caseASimpleAtom(self, node, in_loc, out_loc):\n symbols = node.getSymbol().apply(self)\n\n for symbol in symbols:\n self._nfa.transition(\n in_loc,\n out_loc,\n symbol\n ).attach()\n\n return out_loc\n\n def caseASequenceAtom(self, node, in_loc, out_loc):\n in_ = in_loc\n for atom in node.getAtoms()[:-1]:\n out = self._get_loc()\n in_ = atom.apply(self, in_, out)\n node.getAtoms()[-1].apply(self, in_, out_loc)\n\n return out_loc\n\n def caseAAnyAtom(self, node, in_loc, out_loc):\n for symbol in self._get_symbol_domain():\n self._nfa.transition(\n in_loc,\n out_loc,\n symbol\n ).attach()\n\n return out_loc\n\n def caseAAlternativeAtom(self, node, in_loc, out_loc):\n node.getLeft().apply(self, in_loc, out_loc)\n node.getRight().apply(self, in_loc, out_loc)\n\n return out_loc\n\n def caseAQuantifiedAtom(self, node, in_loc, out_loc):\n node.getAtom().apply(self, in_loc, out_loc)\n\n quantifier = node.getQuantifier()\n if isinstance(quantifier, AZeroOrMoreQuantifier):\n # Add loop\n self._nfa.epsilon_transition(out_loc, in_loc).attach()\n # Add a bypass transition\n self._nfa.epsilon_transition(in_loc, out_loc).attach()\n elif isinstance(quantifier, AOneOrMoreQuantifier):\n # Add loop\n self._nfa.epsilon_transition(out_loc, in_loc).attach()\n elif isinstance(quantifier, AZeroOrOneQuantifier):\n # Add a bypass transition\n self._nfa.epsilon_transition(in_loc, out_loc).attach()\n else:\n raise RuntimeError('Unknown quantifier')\n\n return out_loc\n\n def caseANegativeSetAtom(self, node, in_loc, out_loc):\n symbols = set()\n for child in node.getSymbols():\n child_symbols = child.apply(self)\n symbols.update(child_symbols)\n # Add a transition for every symbol in the domain,\n # not in the negative set\n for symbol in self._get_symbol_domain(exclude=symbols):\n self._nfa.transition(\n in_loc,\n out_loc,\n symbol\n ).attach()\n\n return out_loc\n\n def caseAPositiveSetAtom(self, node, in_loc, out_loc):\n symbols = set()\n for child in node.getSymbols():\n child_symbols = child.apply(self)\n symbols.update(child_symbols)\n # Add a transition for every symbol in the set\n for symbol in symbols:\n self._nfa.transition(\n in_loc,\n out_loc,\n symbol\n ).attach()\n\n return out_loc\n\n escape_expander = re.compile(r'\\\\(.)')\n\n def caseALiteralSymbolType(self, node):\n return self.escape_expander.sub(\n r'\\1',\n node.getWord().getText()\n )\n\n def parse_ast(self, ast):\n if ast is None:\n # Empty query\n only_node = self._get_loc()\n start = only_node\n end = only_node\n else:\n # Transform the AST\n start = self._get_loc()\n end = self._get_loc()\n ast.apply(self, start, end)\n\n self._nfa.initial = start\n self._nfa.final = end\n\n return self._nfa\n\n\nclass SequenceAtomReverser(Analysis):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.inverted = set()\n\n def caseASequenceAtom(self, node, *args, **kwargs):\n # Reverse and set a flag,\n # so multipass stages with this mixin don't mess up\n if node not in self.inverted:\n node._atoms_ = node._atoms_[::-1]\n self.inverted.add(node)\n return super().caseASequenceAtom(node, *args, **kwargs)\n\n\nclass Constructing(SequenceAtomReverser, NFAConstructor):\n def __init__(self, name_label_map):\n super().__init__('C')\n self.name_label_map = name_label_map\n self.Symbol = memoized(Symbol)\n self.get_symbol = lambda value: self.Symbol(self._nfa, value)\n\n def _get_symbol_domain(self, exclude=set()):\n # Exclude is a set of strings\n exclude_strings = {elem.value.name for elem in exclude}\n keys = self.name_label_map.keys() - exclude_strings\n labels = [self.name_label_map[key] for key in keys]\n return [self.get_symbol(label) for label in labels]\n\n def caseASimpleSymbol(self, node):\n label_text = node.getSymbolType().apply(self)\n label = self.name_label_map[label_text]\n return [self.get_symbol(label)]\n\n def caseATupleSymbol(self, node):\n raise NotImplementedError()\n\n\nclass Destructing(NFAConstructor):\n def __init__(self, name_label_map):\n super().__init__('D')\n self.name_label_map = name_label_map\n self.Symbol = memoized(Symbol)\n self.get_symbol = lambda value: self.Symbol(self._nfa, value)\n\n def _get_symbol_domain(self, exclude=set()):\n # Exclude is a set of strings\n exclude_strings = {elem.value.name for elem in exclude}\n keys = self.name_label_map.keys() - exclude_strings\n labels = [self.name_label_map[key] for key in keys]\n return [self.get_symbol(label) for label in labels]\n\n def caseASimpleSymbol(self, node):\n label_text = node.getSymbolType().apply(self)\n label = self.name_label_map[label_text]\n return [self.get_symbol(label)]\n\n def caseATupleSymbol(self, node):\n raise NotImplementedError\n\n\nclass Network(NFAConstructor):\n def __init__(self, router_name_location_map, pda):\n super().__init__('N')\n self.router_name_location_map = router_name_location_map\n self.pda = pda\n self.Symbol = memoized(Symbol)\n self.get_symbol = lambda value: self.Symbol(self._nfa, value)\n\n def _get_symbol_domain(self, exclude=set()):\n # Exclude is a set of strings\n exclude_strings = {elem.value.name[0].name for elem in exclude}\n keys = self.router_name_location_map.keys() - exclude_strings\n locations = []\n key_locations = [self.router_name_location_map[key] for key in keys]\n for locs in key_locations:\n locations.extend(locs)\n return [self.get_symbol(location) for location in locations]\n\n def _match_symbols(self, symbols, in_loc, out_loc):\n eps_chain_symbols = [symbol for symbol in symbols\n if len(symbol.value.name[2]) == 0]\n chain_symbols = [symbol for symbol in symbols\n if len(symbol.value.name[2]) != 0]\n for symbol in eps_chain_symbols:\n self._nfa.transition(\n in_loc,\n out_loc,\n symbol\n ).attach()\n for symbol in chain_symbols:\n self._nfa.transition(\n in_loc,\n in_loc,\n symbol\n ).attach()\n\n return out_loc\n\n def caseASimpleSymbol(self, node):\n router_name = node.getSymbolType().apply(self)\n locations = self.router_name_location_map[router_name]\n return [self.get_symbol(location) for location in locations]\n\n def caseATupleSymbol(self, node):\n raise NotImplementedError()\n\n def caseASimpleAtom(self, node, in_loc, out_loc):\n symbols = node.getSymbol().apply(self)\n\n return self._match_symbols(symbols, in_loc, out_loc)\n\n def caseAAnyAtom(self, node, in_loc, out_loc):\n symbols = self._get_symbol_domain()\n\n return self._match_symbols(symbols, in_loc, out_loc)\n\n def caseANegativeSetAtom(self, node, in_loc, out_loc):\n exclude_symbols = set()\n for child in node.getSymbols():\n child_symbols = child.apply(self)\n exclude_symbols.update(child_symbols)\n # Add a transition for every symbol in the domain,\n # not in the negative set\n symbols = self._get_symbol_domain(exclude=exclude_symbols)\n\n return self._match_symbols(symbols, in_loc, out_loc)\n\n def caseAPositiveSetAtom(self, node, in_loc, out_loc):\n symbols = set()\n for child in node.getSymbols():\n child_symbols = child.apply(self)\n symbols.update(child_symbols)\n\n return self._match_symbols(symbols, in_loc, out_loc)\n\n def parse_ast(self, ast):\n super().parse_ast(ast)\n\n # Add new start and end locations,\n # which read pda.initial and pda.final, respectively\n start_node = self._get_loc()\n end_node = self._get_loc()\n old_start_node = self._nfa.initial\n old_end_node = self._nfa.final\n self._nfa.transition(\n start_node,\n old_start_node,\n self.get_symbol(self.pda.initial)\n ).attach()\n self._nfa.transition(\n old_end_node,\n end_node,\n self.get_symbol(self.pda.final)\n ).attach()\n self._nfa.initial = start_node\n self._nfa.final = end_node\n\n return self._nfa\n\n\ndef parse_query(query, label_domain, pda):\n if isinstance(query, str):\n lexer = Lexer(io.StringIO(query))\n elif isinstance(query, io.IOBase):\n lexer = Lexer(query)\n elif isinstance(query, pathlib.Path):\n with query.open('rt')as f:\n lexer = Lexer(io.StringIO(f.read()))\n else:\n raise RuntimeError('query must be str or IOBase')\n parser = Parser(lexer)\n query_ast = parser.parse().getPQuery()\n\n name_label_map = {value.name: value for value in label_domain}\n name_label_map = keydefaultdict(lambda x: prnml.Label(x), **name_label_map)\n # First element of the location tuple is the router\n router_name_location_map = defaultdict(list)\n\n for location in pda.locations:\n if isinstance(location.name, str):\n continue\n router_name_location_map[location.name[0].name].append(location)\n\n router_name_location_map = dict(router_name_location_map)\n\n c = Constructing(name_label_map)\n n = Network(router_name_location_map, pda)\n d = Destructing(name_label_map)\n\n nfa_c = c.parse_ast(query_ast.getConstructing())\n nfa_n = n.parse_ast(query_ast.getNetwork())\n nfa_d = d.parse_ast(query_ast.getDestructing())\n\n return nfa_c, nfa_n, nfa_d\n","sub_path":"prex/middleware/query_to_nfa.py","file_name":"query_to_nfa.py","file_ext":"py","file_size_in_byte":11260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"513344426","text":"\nimport string\n\n#predefined lists\nletters_list=list(string.ascii_lowercase)\ndigits_list=list(range(10))\nignore_list = [\"-\", \"'\",\"[\"]\nend_char=\"]\"\n\n\n#Returns the list of triples parsed from file input \ndef parse_file(file_name):\n with open(fname) as f:\n file_input = f.readlines()\n \n \n return file_input\n #return output\n\ndef process_room_record(record):\n #print('Record: ',record)\n encountered_letters=[]\n encountered_letters_counts=[]\n room_id=[]\n checksum=[]\n reading_checksum=False\n room_name=[]\n for l in record:\n #print(\"Processing letter \", l, \":\")\n if l in ignore_list:\n if reading_checksum==False:\n room_name.append(l)\n pass\n elif l in letters_list:\n if not reading_checksum:\n room_name.append(l) \n if l in encountered_letters:\n ind=encountered_letters.index(l)\n encountered_letters_counts[ind]=encountered_letters_counts[ind]+1\n else:\n encountered_letters.append(l)\n encountered_letters_counts.append(1)\n else:\n checksum.append(l)\n elif l==end_char:\n break \n elif int(l) in digits_list:\n reading_checksum=True\n room_id.append(l)\n else:\n break\n \n room_name = ''.join(room_name)\n #room_id = int(room_id)\n #print('Room name: ', room_name) \n #encountered_letters_copy=encountered_letters.copy()\n \n #DIAG\n #print(\"encountered letters:\",encountered_letters)\n #print(\"encountered letter counts:\",encountered_letters_counts)\n #print(\"room ID:\",room_id)\n #print(\"checksum:\",checksum)\n \n #verify checksum\n #-went through the list and:\n # -when encountering larger number, note it and start new array of val indexes\n # -when encountering the same number, add its index to the array\n # -if one member of index array, just find the right letter and add it to the constructed checksum\n # -if multiple occurrences, sort those letters alphabetically, and add them to the the constructed checksum\n # -if constructed checksum corresponds to the provided checksum, room is real -> add the room number to the total\n \n \n constructed_checksum=[]\n \n while encountered_letters_counts:\n \n max_val=0\n max_val_index_array=[]\n \n for i in range(len(encountered_letters_counts)):\n \n #if new maximum, note it & clear and init index aray\n if encountered_letters_counts[i]>max_val:\n max_val=encountered_letters_counts[i]\n max_val_index_array.clear()\n max_val_index_array.append(i) \n #if existing maximum, just add it to the array\n elif encountered_letters_counts[i]==max_val:\n max_val_index_array.append(i)\n \n \n #now we have a maximum value and array of indexes of it's occurrences \n #we need to sort the corresponding letters alphabetically\n \n max_val_letters=[]\n \n #fill in the max_val_letters array\n for i in max_val_index_array:\n max_val_letters.append(encountered_letters[i])\n \n #print (\"Max_val_letters: \", max_val_letters)\n \n #remove the values from the original array \n for i in max_val_letters:\n encountered_letters.remove(i)\n encountered_letters_counts.remove(max_val)\n \n #finally, sort the max_val_letters array alphabetically and add it to constructed_checksum \n max_val_letters.sort()\n for i in max_val_letters:\n constructed_checksum.append(i)\n \n #print (\"Constructed checksum: \", constructed_checksum)\n #print (\"Part checksum: \", constructed_checksum[:5])\n \n if constructed_checksum[:5]==checksum:\n #print(\"Real room!\")\n room_id = ''.join(room_id)\n room_id = int(room_id)\n #print(encountered_letters_copy)\n rotation_number=room_id%26\n rotated_room_name=alphabet_rotation(room_name, rotation_number)\n print('***********************')\n print('Room name: ', room_name)\n print('Rotated room name: ', rotated_room_name)\n print('Room ID: ', room_id)\n return room_id\n else:\n return 0\n\ndef process_rooms_intput(input):\n sum_of_real_room_id=0\n for i in input:\n sum_of_real_room_id=sum_of_real_room_id+process_room_record(i)\n return sum_of_real_room_id\n\ndef alphabet_rotation(str, shift):\n alphabet=string.ascii_lowercase\n shifted_alphabet = alphabet[shift:] + alphabet[:shift]\n dash='-'\n space=' '\n alphabet=alphabet+dash\n shifted_alphabet=shifted_alphabet+space \n table = str.maketrans(alphabet, shifted_alphabet)\n return str.translate(table)\n \n#parse record\n#take next char\n#if dash or ', ignore it\n#if a letter, check whether it's already in the letter_list - if yes, just increase it's counter, if no, add it and set the counter to 1\n#if a number, add to id part\n#if '[', put next 5 chars to a checksum\n#sector id processing\n#if '[', read letters until ']' and add them to checksum\n#after the checksum is read, verify the record is valid - if so, add the room id to the sum \n# ========================================== program\n\n#Get the output\nfname='/media/stor_main/!0_Projekty/!0_Dev/AdventOfCode2016/input04.txt'\ninput=parse_file(fname)\n\nsum=process_rooms_intput(input)\nprint(sum)\n#id_sum=0\n#print(\"Record 0: \", input[0])\n#a=process_room_record(input[0])\n\n#str='a'\n#print(int(str)+1)\nstr='a-b-c-x'\nshift=2\n\nprint(alphabet_rotation(str, shift))\n#print(a)\n#print(a+1)\n#for i in input:\n# id_sum=id_sum+process_room_record(i) \n \n \n \n#Part B\n#https://stackoverflow.com/questions/8886947/caesar-cipher-function-in-python","sub_path":"Day04b/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"532244673","text":"import torch\nimport numpy as np\nimport pickle\nfrom torch.utils.data import DataLoader\nimport pandas as pd\nimport json\n\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\n\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\n\ndef padder(ix_document, pad_len):\n \n seq_lens = []\n \n padded_all = []\n \n for doc in ix_document:\n \n if len(doc) == 0 :\n \n pass\n \n if (len(doc) < pad_len) & (len(doc) > 0):\n\n length = len(doc)\n \n diff = pad_len - len(doc)\n\n add_pad = [0]*diff\n\n padded = doc + add_pad\n\n elif len(doc) == pad_len:\n\n padded = doc\n \n length = len(doc)\n\n elif len(doc) > pad_len:\n\n padded = doc[:pad_len]\n \n length = pad_len\n \n padded_all.append(padded)\n seq_lens.append(length)\n \n return padded_all, seq_lens\n\n\nclass dataholder():\n \n def __init__(self, directory, dataset, B_SIZE = 32):\n \n \"\"\"\n Dataholder class (for non-bert instances)\n Accepts as input the data directory : directory\n The dataset : dataset\n and batch size: B_SIZE\n \"\"\"\n \n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n\n \n self.directory = directory\n self.dataset = dataset\n self.batch_size = B_SIZE\n self.hidden_dim = 64\n self.embedding_dim = 300\n \n all_data = pickle.load(open(directory + dataset + \"/data.p\", \"rb\"))\n \n self.w2ix = all_data.w2ix\n self.vocab_size = len(self.w2ix) \n \n self.mask_list = []\n self.mask_tokens = [\"\", \"\", \"\", \".\"]\n \n for item in self.mask_tokens:\n \n if item in self.w2ix:\n \n self.mask_list.append(self.w2ix[item])\n \n self.pretrained_embeds = all_data.pretrained_embeds\n \n \n # In[4]:\n \n \n x_train, y_train = zip(*all_data.train)\n x_dev, y_dev = zip(*all_data.dev)\n x_test, y_test = zip(*all_data.test)\n \n print(\"\\nVocab size:\", len(self.w2ix),\n \"\\nTraining size:\", len(y_train),\n \"\\nDev size:\", len(y_dev),\n \"\\nTest size:\", len(y_test))\n \n # In[5]:\n \n self.output_size= len(np.unique(y_train))\n \n print(\"\\nOutput dimension: \", self.output_size, \"\\n\")\n \n \n self.sequence_length = all_data.sequence_length()\n \n if dataset == \"mimicanemia\":\n \n \tself.sequence_length = 2200\n \n print(\"--Sequence length :\", self.sequence_length, \"\\n\")\n \n # In[10]:\n \n from modules.utils import padder\n \n x_train_pad, train_lengths = padder(x_train, pad_len = self.sequence_length)\n x_dev_pad, dev_lengths = padder(x_dev, pad_len = self.sequence_length)\n x_test_pad, test_lengths = padder(x_test, pad_len = self.sequence_length)\n \n \n # In[11]:\n \n x_train_pad = torch.LongTensor(x_train_pad)#.to(device)\n x_dev_pad = torch.LongTensor(x_dev_pad)#.to(device)\n x_test_pad = torch.LongTensor(x_test_pad)#.to(device)\n train_lengths = torch.LongTensor(train_lengths)#.to(device)\n dev_lengths = torch.LongTensor(dev_lengths)#.to(device)\n test_lengths = torch.LongTensor(test_lengths)#.to(device)\n y_train = torch.LongTensor(y_train)#.to(device)\n y_dev = torch.LongTensor(y_dev)#.to(device)\n y_test = torch.LongTensor(y_test)#.to(device)\n \n \n # In[12]:\n \n \n training_prebatch = list(zip(x_train_pad, train_lengths, y_train))\n dev_prebatch = list(zip(x_dev_pad, dev_lengths, y_dev))\n testing_prebatch = list(zip(x_test_pad, test_lengths, y_test))\n \n \n training_prebatch = sorted(training_prebatch, key = lambda x : x[1], reverse = False)\n dev_prebatch = sorted(dev_prebatch, key = lambda x : x[1], reverse = False)\n testing_prebatch = sorted(testing_prebatch, key = lambda x : x[1], reverse = False)\n \n # In[13]:\n \n ### removing sos and eos only sentences\n \n train_prebatch = [x for x in training_prebatch if x[1] > 2]\n dev_prebatch = [x for x in dev_prebatch if x[1] > 2]\n test_prebatch = [x for x in testing_prebatch if x[1] > 2]\n \n \n self.training = DataLoader(train_prebatch, batch_size = self.batch_size, \n shuffle = True, pin_memory = False)\n \n self.development = DataLoader(dev_prebatch, batch_size = self.batch_size, \n shuffle = False, pin_memory = False)\n \n \n self.testing = DataLoader(test_prebatch, batch_size = self.batch_size, \n shuffle = False, pin_memory = False)\n \n\n\ndef bertify(x, not_include = [\"\", \"\"]):\n \n bertification = []\n \n for word in x.split():\n \n if word == \"\":\n \n word = '[UNK]'\n \n bertification.append(word)\n \n elif word in not_include:\n \n pass\n \n else:\n \n bertification.append(word)\n \n return \" \".join(bertification)\n \ndef bert_padder(x, max_len):\n \n if len(x) < max_len:\n \n x += [0]*(int(max_len) - len(x))\n \n elif len(x) > max_len:\n\n x = x[:max_len - 1]\n x += [102]\n\n return x\n\nimport nltk\nfrom nltk.corpus import stopwords\nnltk.download('stopwords')\n\ndef mimic_halfer(x):\n\n stopwordlist = stopwords.words(\"english\") + [\"qqq\", \"\", \":\", \")\", \"(\", \".\", \"/\"]\n\n cut_no_stop = [word for word in x.split() if not word in stopwordlist]\n \n revised = cut_no_stop[20:276] + cut_no_stop[-256:]\n\n return \" \".join(revised).lower()\n \nfrom tqdm.auto import tqdm\n\nclass dataholder_bert():\n \n def __init__(self, directory, dataset, B_SIZE = 8, bert_model = \"bert-base_uncased\"): \n \n self.directory = directory\n self.dataset = dataset\n self.batch_size = B_SIZE\n self.hidden_dim = 768 // 2\n self.embedding_dim = None\n self.pretrained_embeds = None\n self.mask_list = [101, 102, 0]\n \n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n\n \n all_data = pd.read_csv(directory + dataset + \"/\" + dataset + \"_dataset.csv\")\n\n all_data[\"text\"] = all_data[\"text\"].astype(str)\n\n self.output_size = 2\n \n print(\"\\nOutput dimension: \", self.output_size, \"\\n\")\n \n from transformers import AutoTokenizer\n \n pretrained_weights = bert_model\n \n if dataset == \"mimicanemia\": bert_max_length = 512\n else: bert_max_length = 512\n \n tokenizer = AutoTokenizer.from_pretrained(pretrained_weights, attention_window = bert_max_length)\n \n self.vocab_size = tokenizer.vocab_size\n\n # treat mimic for long text\n if dataset == \"mimicanemia\":\n # mimic requires reshuffling\n all_data = all_data.sample(frac = 1.0, random_state = 100)\n # borrowed idea from Fine-tune BERT for Text Classification \n all_data[\"text\"] = all_data[\"text\"].apply(lambda x: mimic_halfer(x))\n \n # import pdb; pdb.set_trace();\n #remove sos and eos and replace unkn with bert symbols\n all_data[\"text\"] = all_data[\"text\"].apply(lambda x: bertify(x))\n # tokenize to maximum length the sequences and add the CLS token and ?SEP? at the enD??\n \n tqdm.pandas(desc=\"tokenizing\")\n all_data[\"text\"] = all_data[\"text\"].progress_apply(lambda x: tokenizer.encode_plus(x, max_length = bert_max_length,truncation = True)[\"input_ids\"])\n all_data[\"lengths\"] = all_data[\"text\"].apply(lambda x: len(x)) \n \n self.sequence_length = int(all_data.lengths.quantile(q = 0.95))\n \n if self.sequence_length < 50:\n \n self.sequence_length = 50\n \n if dataset == \"mimicanemia\":\n \n \tself.sequence_length = 512\n \n \n print(\"--Sequence length :\", self.sequence_length , \"\\n\")\n \n if self.sequence_length < 512:\n \n bert_max_length = self.sequence_length \n \n all_data[\"text_encoded\"] = all_data[\"text\"].apply(lambda x: bert_padder(x, bert_max_length))\n\n train_prebatch = all_data[all_data.exp_split == \"train\"][[\"text_encoded\", \"lengths\", \"label\"]].values.tolist()\n dev_prebatch = all_data[all_data.exp_split == \"dev\"][[\"text_encoded\", \"lengths\", \"label\"]].values.tolist()\n test_prebatch = all_data[all_data.exp_split == \"test\"][[\"text_encoded\", \"lengths\", \"label\"]].values.tolist()\n \n # ### keep non zero sequences\n \n \n train_prebatch = sorted(train_prebatch, key = lambda x : x[1], reverse = False)\n dev_prebatch = sorted(dev_prebatch, key = lambda x: x[1], reverse = False)\n test_prebatch = sorted(test_prebatch, key = lambda x: x[1], reverse = False)\n \n ### removing sos and eos only sentences\n \n train_prebatch = [x for x in train_prebatch if x[1] > 2]\n dev_prebatch = [x for x in dev_prebatch if x[1] > 2]\n test_prebatch = [x for x in test_prebatch if x[1] > 2]\n \n\n\n self.training = DataLoader(train_prebatch, batch_size = self.batch_size, \n shuffle = False, pin_memory = False)\n \n self.development = DataLoader(dev_prebatch, batch_size = self.batch_size, \n shuffle = False, pin_memory = False)\n \n \n self.testing = DataLoader(test_prebatch, batch_size = self.batch_size, \n shuffle = False, pin_memory = False)\n","sub_path":"modules/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"561020848","text":"#Chaper 1\n\n# __getitem__() -> 특별 메서드 (던더 getitem 으로 발음)\n# 특별 메서드는 interpreter 가 호출하기 위해 필요한 것임.\n\n# 1.1 카드 한벌 구현\nimport collections\n\nCard = collections.namedtuple('Card', ['rank', 'suit']) # 개별 카드를 나타내는 클래스 구현 ->Card(rank, suit) tuple 로 구현, global 변수\n\nclass FrenchDeck:\n ranks = [str(n) for n in range(2, 11)] + list('JQKA') # card number 구현 2~10, JQKA in rank 변수\n suits = 'Spades Diamonds Clubs Hearts'.split() # Card 무늬 표시, split 으로 각자 나눔\n\n def __init__(self): # Card 변수에서 입력된 값 사용하여 카드 변수 생성 ->chapter 2 지능형리스트 사용함. 데카르트곱!\n self._cards = [Card(rank, suit) for suit in self.suits\n for rank in self.ranks]\n\n def __len__(self): # 갖고 있는 카드의 수 반환\n return len(self._cards)\n\n def __getitem__(self, position): # 카드 indexing, 카드는 2~A 로 순서대로, Spade ~ 순서대로\n return self._cards[position]\n\n\n\nbeer_card = Card('7', 'Diamonds')\nprint (beer_card)\n\ndeck = FrenchDeck()\nprint (len(deck))\n\nprint(deck[0])\nprint(deck[1])\n\nfrom random import choice # random card 뽑기\nprint (choice(deck))\nprint (choice(deck))\nprint (choice(deck))\nprint (choice(deck))\n\n# 특별 메서드를 class 에 구현하면 굳이 메서드명을 외울 필요 없다 -> very good!\n# 파이썬에서 기능 별도 구현 필요없음\n\n\nfor card in deck:\n print (card)\n\nfor card in reversed(deck):\n print (card)\n\nprint (Card('Q', 'Hearts') in deck)\n\nprint (Card('J', 'Beasts') in deck)\n\nsuit_values = dict(Spades = 3, Hearts = 2, Diamonds = 1, Clubs = 0)\n# dictionary 표현할 때 {key:item} 으로 표현하지 않아도 이런 방법으로 표현 가능, 타자치기 더 쉬움!\n\ndef Spades_high(card): # card number 와 모양으로 card 별로 숫자 ranking\n rank_value = FrenchDeck.ranks.index(card.rank) # FrenchDeck class 로 선언된 카드의 rank 순서를 indexing 하여 value 매김\n return rank_value * len(suit_values) + suit_values[card.suit]\n # 숫자별로 indexing 한 것을 모양 종류에 곱하여 숫자에 ranking + 모양 별 가산점 부여\n\n\nfor card in sorted(deck, key=Spades_high):\n print (card)\n\n# for i in x: -> iter(x) 호출하는 것 -> x.__iter__() 호출하는 것임\n# 특별 메서드 호출이 필요할 경우 일반적으로 파이썬 내장함수를 호출하는 것이 더 좋음(len(), str(), iter() 등)\n# 사용자정의 속성을 만들 때 __xxx__ 는 피하는 것이 좋음\n\n# 1.2 수치형 흉내\n\nfrom math import hypot\n\nclass Vector:\n def __init__(self, x=0, y=0): # 그냥 self, x, y 로 주면 안되는 건지? x=0, y=0 으로 주는 이유는? x, y 변수가 numeric 이라서?\n self.x = x\n self.y = y\n\n def __repr__(self):\n return 'Vector(%r, %r)' % (self.x, self.y)\n '''왜 %r 을 사용하는가?%r 과 %s 는 모두 문자열을 출력함. %s -> str() but %r -> repr(), official string representation 함.\n http://satyajit.ranjeev.in/2012/03/14/python-repr-str.html\n When I use the built-in function str() to display today:\n\n>>> str(today)\n'2012-03-14 09:21:58.130922'\nYou can see that the date was displayed as a string in a way that the user can understand the date and time. Now lets see when I use the built-in function repr():\n\n>>> repr(today)\n'datetime.datetime(2012, 3, 14, 9, 21, 58, 130922)'\nYou can see that this also returned a string but the string was the “official” representation of a datetime object. What does official mean? Using the “official” string representation I can reconstruct the object:\n\n>>> eval('datetime.datetime(2012, 3, 14, 9, 21, 58, 130922)')\ndatetime.datetime(2012, 3, 14, 9, 21, 58, 130922)\n\nMost functions while trying to get the string representation use the __str__ function, \nif missing uses __repr__. Thus in a general every class you code must have a __repr__ and \nif you think it would be useful to have a string version of the object, \nas in the case of datetime create a __str__ function.'''\n\n def __abs__(self): # vector 크기 검출 -> 피타고라스 정리 이용하여 계산함 -> hypot 함수\n return hypot(self.x, self.y) # a = sqrt(x**2 +y**2), hypot 함수를 매일 호출해야 하므로 직접 수식을 써서 하면? 어차피 sqrt 등 필요'''\n\n def __bool__(self): # vector 의 크기가 0 이면 False 반환 -> bool 함수가 없으면 python은 len 함수 이용\n return bool(abs(self))\n\n def __add__(self, other): # vector 합\n x = self.x + other.x\n y = self.y + other.y\n return Vector(x, y)\n\n def __mul__(self, scalar): # vector scalar 곱, vector * 숫자는 가능하지만 숫자 * vector 는 불가능함. 교환법칙을 어겼음.\n return Vector(self.x * scalar, self.y * scalar)\n\n\n# Chapter 2\n\n#2.1 sequence -> container sequence(list, tuple, collections..) -> 객체 참조\n# 균일 sequence -> str, bytes, bytearray, memoryview, array.array -> 메모리 주소에 값을 직접 담음\n\n#2.2 list comprehension->가독성 굿, 가끔은 속도도 굿\n\n#version 1\nsymbols1 = \"!@#$%\"\ncodes = []\nfor symbol in symbols1:\n codes.append(ord(symbol))\n\n#version 2\nsymbols2 = \"!@#$%\"\ncodes2 = [ord(symbol) for symbol in symbols2]\n\n#-> version 2 가 가독성이 좋음\n# 반드시 사용할 리스트만 지능형 리스트로 만들자! 나중엔 더 복잡해질수도 있는 단점, 코드 짧게 해야 장점이 살아남\n#람다는 기능적으로 문제가 있다? 하지만 문제가 뭔지는 안나옴..\n#filter, map 함수를 사용하는 것보다 지능형 리스트가 더 깔끔하고 빠름\n\n#지능형 리스트를 이용한 데카르트 곱\ncolors = ['black', 'white']\nsizes = ['S', 'M', 'L']\ntshirts = [(color, size) for color in colors\n for size in sizes] # python 은 괄호 내 개행 무시함. 지능형 리스트에서 조건을 줄맞춰 써놓으면 뭐가 먼저 나올지 알아보기 편함\n\n#지능형 리스트는 리스트만 만듦\n\n# 제너레이터 표현식\n#지능형 리스트와 동일한 구문 사용, but 대괄호 대신 괄호\n# 제너레이터 표현식은 한번에 하나의 항목을 생성하므로 리스트를 불필요하게 생성하지 않음\nsymbols = \"!@#$%\"\ntuple(ord(symbol) for symbol in symbols)\nimport array\narray.array('I', (ord(symbol) for symbol in symbols))\n\n#2.3 tuple - 언팩킹 까지\n'''tuple 은 record 기능도 있음, for loop 에서 %s 등 쓸때 언팩킹도 가능함. 더미변수 쓸때는 _ 사용'''\n\n#튜플 언팩킹 = 반복형 언팩킹 = 한번에 하나의 항목을 생성함\n#병렬 할당할 때 하나의 변수에 하나씩 할당됨\n\n\n\n\n\n\n\n\n","sub_path":"1주차/.ipynb_checkpoints/김세준_Chapter 1-checkpoint.py","file_name":"김세준_Chapter 1-checkpoint.py","file_ext":"py","file_size_in_byte":6796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"85201074","text":"import json,re\n\nwith open('./jawiki-country.json','r',encoding='utf-8') as f:\n for line in f:\n line=json.loads(line)\n if line['title']=='イギリス':\n text=line['text']\n break\n\npattern='^\\{\\{基礎情報.*?$(.*?)^\\}\\}'\ntemp=re.findall(pattern,text,re.MULTILINE|re.DOTALL)\n#print(temp)\n\npattern = '^\\|(.+?)\\s*=\\s*(.+?)(?:(?=\\n\\|)|(?=\\n$))'\n#print(re.findall(pattern,temp[0],re.MULTILINE+re.DOTALL))\ndic=dict(re.findall(pattern,temp[0],re.MULTILINE+re.DOTALL))\ndef rm(t):\n p='\\'{2,5}'\n t=re.sub(p,'',t)\n p='\\[\\[(?:[^|]*?\\|)??([^|]*?)\\]\\]'\n t=re.sub(p,'\\1',t)\n return t\n\nresult={k:rm(v) for k,v in dic.items()}\nfor key,value in result.items():\n print(key+':'+value+'\\n')\n\n'''\nre.sub(pattern, repl, string, count=0, flags=0)\nstring 中に出現する最も左の重複しない pattern を置換 repl で置換することで得られる文字列を返します\n\n'''","sub_path":"ling/chapter03/knock27.py","file_name":"knock27.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"276300946","text":"import cv2\r\nimport numpy as np\r\nimport sqlite3\r\nimport os\r\n\r\nconnection = sqlite3.connect('database.db')\r\nc = connection.cursor()\r\nfacename = \"recognizer/trainingData.yml\"\r\nif not os.path.isfile(facename):\r\n print(\"Please train the data first\")\r\n exit(0)\r\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\r\ncamera = cv2.VideoCapture(0)\r\nrecognizer = cv2.face.LBPHFaceRecognizer_create()\r\nrecognizer.read(facename)\r\nwhile True:\r\n ret, image = camera.read()\r\n #image = cv2.flip(image, 1)\r\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n clahe = cv2.createCLAHE(clipLimit=2.0,tileGridSize=(8,8))\r\n clahe_image = clahe.apply(gray)\r\n faces = face_cascade.detectMultiScale(clahe_image, 1.3, 5)\r\n for (x, y, w, h) in faces:\r\n cv2.rectangle(image, (x, y), (x + w, y + h), (209, 206, 0), 1)\r\n ids, thresold = recognizer.predict(clahe_image[y:y + h, x:x + w])\r\n \r\n c.execute(\"select name from users where id =(?);\", (ids,))\r\n\r\n result = c.fetchall()\r\n name = result[0][0]\r\n if thresold < 50:\r\n cv2.putText(image, name, (x + 2, y + h - 5), cv2.FONT_HERSHEY_COMPLEX, 1, (238, 130, 238), 1)\r\n else:\r\n cv2.putText(image, 'No Match', (x + 2, y + h - 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 1)\r\n cv2.imshow('Face Detect', image)\r\n\r\n if cv2.waitKey(20) == ord('a'):\r\n break\r\ncamera.release()\r\ncv2.destroyAllWindows()\r\n","sub_path":"Detector.py","file_name":"Detector.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"293838630","text":"import json\r\nfrom jsonmerge import merge\r\nfrom os import listdir\r\nfrom os.path import isfile, join\r\nonlyfiles = [f for f in listdir('.') if isfile(join('.', f))]\r\ndata = []\r\nfinal_data = {'meals': {}}\r\nfor file in onlyfiles:\r\n if '.json' in file and not 'all_meals' in file and not 'farrand' in file and not 'village' in file and not 'c4c' in file:\r\n json1=open(file)\r\n data.append(json.load(json1))\r\n\r\nfinal_data = {}\r\nfinal_data['meals'] = []\r\nfor datum in data:\r\n for meal in datum['meals']:\r\n temp = meal\r\n final_data['meals'].append(meal)\r\n\r\nfor i, meal in enumerate(final_data['meals']):\r\n meal['idMeal'] = i+1\r\n\r\n\r\nwith open('all_meals.json', 'w') as outfile:\r\n json.dump(final_data, outfile)","sub_path":"restaurant/assets/dynamic_data/all_meals.py","file_name":"all_meals.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"154421801","text":"import numpy as np\nimport random\nimport re\nimport operator\nfrom hmmlearn import hmm\nfrom keras.preprocessing.sequence import pad_sequences\nfrom imblearn.over_sampling import SMOTE\nfrom collections import Counter\nfrom imblearn.under_sampling import ClusterCentroids\n\n\n###################################################################\n# read codebook from file\ndef loadCodeBook(codebook_filename):\n codebook = []\n with open(codebook_filename, \"r\") as filestream:\n for line in filestream:\n codebook.append(line.replace(\"\\n\", \"\"))\n return codebook\n\n\n###########################################################################################\ndef loadCodeBookFromTrainingFile(fileLocation):\n all_code_map = {}\n success_code_map = {}\n unsuccess_code_map = {}\n with open(fileLocation, \"r\") as filestream:\n for line in filestream:\n l = re.sub(r\"\\s+\", \"\", line).split(\",\")\n if l[len(l) - 1] == \"500\":\n for i in range(0, len(l) - 1):\n success_code_map[l[i]] = l[i]\n all_code_map[l[i]] = l[i]\n elif l[len(l) - 1] == \"400\":\n for i in range(0, len(l) - 1):\n unsuccess_code_map[l[i]] = l[i]\n all_code_map[l[i]] = l[i]\n\n success_sorted_map = sorted(success_code_map.items(), key=operator.itemgetter(0))\n unsuccess_sorted_map = sorted(unsuccess_code_map.items(), key=operator.itemgetter(0))\n all_sorted_map = sorted(all_code_map.items(), key=operator.itemgetter(0))\n\n success_map = []\n unsuccess_map = []\n all_map = []\n\n for key, value in all_sorted_map:\n all_map.append(key)\n for key, value in success_sorted_map:\n success_map.append(key)\n for key, value in unsuccess_sorted_map:\n unsuccess_map.append(key)\n\n return all_map, success_map, unsuccess_map\n\n\n###########################################################################################\ndef loadData(fileLocation, codebook, flag):\n code_to_int = dict((c, i) for i, c in enumerate(codebook))\n seq = []\n seq_label = []\n lengths = []\n map = {}\n with open(fileLocation, \"r\") as filestream:\n for line in filestream:\n l = re.sub(r\"\\s+\", \"\", line).split(\",\")\n if (flag == 1 and l[len(l) - 1] == \"500\") or (flag == 0 and l[len(l) - 1] == \"400\"):\n for i in range(0, len(l) - 1):\n seq.append([code_to_int[l[i]]])\n map[l[i]] = l[i]\n lengths.append(len(l) - 1)\n seq_label.append(l[len(l) - 1])\n elif flag == 2:\n var_len = 0\n for i in range(0, len(l) - 1):\n if l[i] in code_to_int.keys():\n seq.append([code_to_int[l[i]]])\n map[l[i]] = l[i]\n var_len += 1\n lengths.append(var_len)\n seq_label.append(l[len(l) - 1])\n\n # sorted_map = sorted(map.items(), key=operator.itemgetter(0))\n # for key, value in sorted_map:\n # print key\n return np.array(seq), np.array(seq_label), np.array(lengths)\n\n\n############################################################################################\ndef getHMMModel(n_states, n_observations, sequences, seq_lengths):\n start_probability = np.ones(n_states)\n start_probability = start_probability / n_states\n\n transition_probability = np.ones(n_states * n_states).reshape(n_states, n_states)\n transition_probability = transition_probability / n_states\n\n emission_probability = np.ones(n_states * n_observations).reshape(n_states, n_observations)\n emission_probability = emission_probability / n_observations\n\n # create model and set initial values\n model = hmm.MultinomialHMM(n_components=n_states, random_state=42)\n model.startprob_ = start_probability\n model.transmat_ = transition_probability\n model.emissionprob_ = emission_probability\n\n # fit model\n model = model.fit(sequences, seq_lengths)\n return model\n\n\n#############################################################################################\ndef getMacroAveragePerformance(actual, predicted):\n precision = 0.0\n recall = 0.0\n f_measure = 0.0\n accuracy = 0.0\n\n labels = [\"500\", \"400\", \"400\", \"500\"]\n\n for k in [0, 2]:\n\n tp = 0\n fp = 0\n tn = 0\n fn = 0\n\n for i in range(0, len(actual)):\n if actual[i] == predicted[i] and actual[i] == labels[k]:\n tp += 1\n elif actual[i] != predicted[i] and actual[i] == labels[k]:\n fn += 1\n elif actual[i] == predicted[i] and actual[i] == labels[k + 1]:\n tn += 1\n elif actual[i] != predicted[i] and actual[i] == labels[k + 1]:\n fp += 1\n\n local_precision = (float(tp) / (tp + fp))\n local_recall = (float(tp) / (tp + fn))\n local_f_measure = (float(2 * local_precision * local_recall) / (local_precision + local_recall))\n accuracy = (float(tp + tn) / (tp + fp + tn + fn))\n\n # for checking calculation\n # print tp, fp, tn, fn\n # print local_accuracy, local_precision, local_recall, local_f_measure\n\n precision += local_precision\n recall += local_recall\n f_measure += local_f_measure\n\n return accuracy, precision / 2, recall / 2, f_measure / 2\n\n\n#############################################################################################\ndef getMicroAveragePerformance(actual, predicted):\n precision = 0.0\n recall = 0.0\n f_measure = 0.0\n accuracy = 0.0\n\n total_sample = len(actual)\n\n labels = [\"500\", \"400\", \"400\", \"500\"]\n\n for k in [0, 2]:\n\n tp = 0\n fp = 0\n tn = 0\n fn = 0\n\n for i in range(0, len(actual)):\n if actual[i] == predicted[i] and actual[i] == labels[k]:\n tp += 1\n elif actual[i] != predicted[i] and actual[i] == labels[k]:\n fn += 1\n elif actual[i] == predicted[i] and actual[i] == labels[k + 1]:\n tn += 1\n elif actual[i] != predicted[i] and actual[i] == labels[k + 1]:\n fp += 1\n\n local_precision = (float(tp) / (tp + fp))\n local_recall = (float(tp) / (tp + fn))\n local_f_measure = (float(2 * local_precision * local_recall) / (local_precision + local_recall))\n accuracy = (float(tp + tn) / (tp + fp + tn + fn))\n\n # for checking calculation\n # print tp, fp, tn, fn\n # print local_accuracy, local_precision, local_recall, local_f_measure\n\n precision += (local_precision * (float(tp + fn) / total_sample))\n recall += (local_recall * (float(tp + fn) / total_sample))\n f_measure += (local_f_measure * (float(tp + fn) / total_sample))\n\n return accuracy, precision, recall, f_measure\n\n\n#############################################################################################\ndef createTrainAndTestFile(data, kFolds, training_filename, testing_filename):\n foldSize = len(data) / kFolds\n random.shuffle(data)\n\n test = data[:foldSize]\n train = data[foldSize:]\n with open(training_filename, \"w\") as output:\n for x in train:\n output.write(x)\n with open(testing_filename, \"w\") as output:\n for x in test:\n output.write(x)\n\n\n#############################################################################################\ndef readAllData(data_filename):\n data = []\n with open(data_filename, \"r\") as filestream:\n for line in filestream:\n data.append(line)\n return data\n\n\n#############################################################################################\ndef AUC(y_true, y_pred):\n not_y_pred = np.logical_not(y_pred)\n y_int1 = y_true * y_pred\n y_int0 = np.logical_not(y_true) * not_y_pred\n TP = np.sum(y_pred * y_int1)\n FP = np.sum(y_pred) - TP\n TN = np.sum(not_y_pred * y_int0)\n FN = np.sum(not_y_pred) - TN\n TPR = np.float(TP) / (TP + FN)\n FPR = np.float(FP) / (FP + TN)\n return ((1 + TPR - FPR) / 2)\n\n\n#######################################################################\n# create startified folds for cross validation\ndef createStartifiedFolds(codebook, kFolds=10):\n folds = []\n success = []\n unsuccess = []\n max_len = 0\n len_tmp = 0\n code_to_int = dict((c, i + 1) for i, c in enumerate(codebook))\n\n with open(\"data/successful.txt\", \"r\") as filestream:\n for line in filestream:\n len_tmp = len(line.split(\",\"))\n if len_tmp > max_len:\n max_len = len_tmp\n currentline = line.replace(\"\\n\", \"\").split(\",\")\n seq = []\n for s in currentline:\n if s in code_to_int.keys():\n seq.append(int(code_to_int[s]))\n else:\n seq.append(500)\n success.append(seq)\n\n random.shuffle(success)\n with open(\"data/unsuccessful.txt\", \"r\") as fstream:\n for line in fstream:\n len_tmp = len(line.split(\",\"))\n if len_tmp > max_len:\n max_len = len_tmp\n currentline = line.replace(\"\\n\", \"\").split(\",\")\n seq = []\n for s in currentline:\n if s in code_to_int.keys():\n seq.append(int(code_to_int[s]))\n else:\n seq.append(400)\n unsuccess.append(seq)\n\n random.shuffle(unsuccess)\n for i in range(0, kFolds):\n foldSize_succ = int(float(len(success)) / kFolds)\n foldSize_unsucc = int(float(len(unsuccess)) / kFolds)\n idx_succ = range(i * foldSize_succ, i * foldSize_succ + foldSize_succ)\n random.shuffle(idx_succ)\n idx_unsucc = range(i * foldSize_unsucc, i * foldSize_unsucc + foldSize_unsucc)\n random.shuffle(idx_unsucc)\n test = [success[index] for index in idx_succ] + [unsuccess[index] for index in idx_unsucc]\n train = [success[index] for index in range(0, len(success)) if index not in idx_succ] + \\\n [unsuccess[index] for index in range(0, len(unsuccess)) if index not in idx_unsucc]\n random.shuffle(test)\n random.shuffle(train)\n folds.append([test, train])\n return folds, max_len\n\n\n###################################################################\ndef writeSampledSequences(X, y, codebook, outputdata_filename):\n int_to_code = dict((i + 1, c) for i, c in enumerate(codebook))\n f = open(outputdata_filename, \"w\")\n for i in range(0, len(X)):\n seq = []\n for s in X[i]:\n val = int(round(s))\n if val > 0:\n if val in int_to_code.keys():\n seq.append(str(int_to_code[val]))\n seq.append(str(y[i]))\n f.write(\",\".join(seq) + \"\\n\")\n f.close()\n\n\n#######################################################################\n# create startified folds for cross validation\ndef createUnderOrOverSample(method, given_data, outputdata_filename, max_len, codebook):\n dataX = []\n dataY = []\n for xx in given_data:\n dataX.append(xx[0:-1])\n dataY.append(xx[-1])\n\n X = pad_sequences(dataX, maxlen=max_len, dtype='float32')\n X_norm = X / (float(len(codebook)))\n y_norm = np.array(dataY)\n\n # perform over or under sampling\n X_d = []\n y_res = []\n if method == \"over\":\n sm = SMOTE(kind='borderline2')\n X_res, y_res = sm.fit_sample(X_norm, y_norm)\n else:\n sm = ClusterCentroids()\n X_res, y_res = sm.fit_sample(X_norm, y_norm)\n\n X_d = X_res * (float(len(codebook)))\n writeSampledSequences(X_d, y_res, codebook, outputdata_filename)\n\n\n#######################################################################\n# load transition dictionary\ndef loadDictionary(training_filename, n_order, label):\n transition_dict = {}\n with open(training_filename, \"r\") as file_stream:\n for line in file_stream:\n words = line.replace(\"\\n\", \"\").split(\",\")\n actual_label = words[len(words) - 1]\n if len(words) <= n_order:\n continue\n\n if label == actual_label:\n for i in xrange(0, len(words) - n_order - 1):\n current_tuple = tuple([words[j] for j in xrange(i, i + n_order + 1)])\n if current_tuple in transition_dict.keys():\n transition_dict[current_tuple] += 1\n else:\n transition_dict[current_tuple] = 1\n return transition_dict\n\n\n#######################################################################\n# load transition dictionary\ndef loadTransitionDictionary(training_filename, n_order, label):\n transition_dict = {}\n with open(training_filename, \"r\") as file_stream:\n for line in file_stream:\n words = line.replace(\"\\n\", \"\").split(\",\")\n actual_label = words[len(words) - 1]\n if len(words) <= n_order:\n continue\n\n if label == actual_label:\n for i in xrange(0, len(words) - n_order - 1):\n current_tuple = tuple([words[j] for j in xrange(i, i + n_order)])\n if current_tuple in transition_dict.keys():\n transition_dict[current_tuple].append(words[i + n_order])\n else:\n transition_dict[current_tuple] = [words[i + n_order]]\n return transition_dict\n","sub_path":"most-likely-patterns/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":13471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"134314477","text":"# coding: utf-8\nimport re\nfrom pprint import pprint\nfrom collections import Counter\n\nletters = 'abcdefghijklmnopqrstuvwxyz'\n\n\ndef words(text):\n return re.findall(r'\\w+', text.lower())\n\n\nWORDS = Counter(words(open('big.txt').read()))\n\n\ndef P(word, N=sum(WORDS.values())):\n \"Probability of `word`.\"\n return WORDS[word] / N\n\n\n# Using Pw(word) or P(word) may result in different answers\ndef next_states(state):\n L, R, edit, prob = state\n R0, R1 = R[0], R[1:]\n if edit == 2:\n return [(L + R0, R1, edit, prob)]\n noedit = [(L + R0, R1, edit, prob)]\n delete = [(L, R1, edit + 1, P(L + R1))]\n replaces = [(L + c, R1, edit + 1, P(L + c + R1)) for c in letters]\n inserts = [(L + R0 + c, R1, edit + 1, P(L + R0 + c + R1)) for c in letters]\n return noedit + delete + replaces + inserts\n\n\n# Using Pw(word) or P(word) may result in different answers\ndef correction(word):\n states = [('', word, 0, P(word))]\n MAXBEAM = 550\n\n for i in range(len(word)):\n states = [state for states in map(next_states, states) for state in states]\n\n word_dict = {}\n for state in states:\n L, R, edit, prob = state\n word = L + R\n if word not in word_dict or edit < word_dict[word][2]:\n word_dict[word] = state\n\n states = list(word_dict.values())\n states = sorted(states, key=lambda x: x[3], reverse=True)\n states = sorted(states, key=lambda x: x[2])[:MAXBEAM]\n\n states = [state for state in states if state[2] == 0 or state[3] > 0]\n\n return sorted(states, key=lambda x: x[3], reverse=True)[:3]\n\n\npprint(correction(\"appearant\"))\npprint(correction(\"beleive\"))\npprint(correction(\"writen\"))\npprint(correction(\"happy\"))\n","sub_path":"Natural-Language-Processing-Lab/Lab02_beam_search/lab2_beam_search.py","file_name":"lab2_beam_search.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"578818681","text":"from operator import add\nfrom functools import reduce\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport argparse\n\ndef energy(weights, input_pattern):\n #size = range(0, len(input_pattern))\n #return -reduce(add, [weights[i][j] * input_pattern[i] * input_pattern[j] for i in size for j in size])\n return -weights.dot(input_pattern).dot(input_pattern.T)\n\ndef plot_energy(energy_list):\n plt.plot(energy_list)\n plt.ylabel('Energy')\n plt.xlabel('Iterations')\n plt.show()\n\ndef plot_energies(energy_lists, legend):\n for energy_list in energy_lists:\n plt.plot(energy_list)\n plt.legend(legend);\n plt.ylabel('Energy')\n plt.xlabel('Iterations')\n plt.show()\n\ndef energy_at(weights, patterns, what = \"patterns\"):\n print(\"ENERGY AT \" + what + \":\")\n print(\"====================\")\n for pattern in patterns:\n print(str(pattern) + \": \" + str(energy(weights, pattern)))\n\n# Count how many bits differ between pattern x and y\ndef count_errors(x, y):\n count = 0\n for i in range(0, len(x)):\n if (x[i] != y[i]):\n count = count + 1\n return(count)\n\n# Set any value in x >= 0 to 1 and any value < 0 to -1\ndef sgn(x):\n for i in range(0, len(x)):\n if (x[i] >= 0):\n x[i] = 1\n else:\n x[i] = -1\n return(x)\n\n# Generate all possible input patterns of the chosen size\ndef get_all_possible_inputs(input, sub_part, size, depth):\n if(size == depth + 1):\n input.append(sub_part + [1])\n input.append(sub_part + [-1])\n return\n get_all_possible_inputs(input, sub_part + [1], size, depth + 1)\n get_all_possible_inputs(input, sub_part + [-1], size, depth + 1)\n\n# Remove duplicate patterns\ndef remove_duplicates(input):\n for i in range(0, len(input)):\n for j in range (i + 1, len(input)):\n if(count_errors(input[i], input[j]) == 0):\n input = np.delete(input, j, 0)\n input = remove_duplicates(input)\n return input\n return input\n\ndef find_attractors(weights):\n all_possible_input_patterns = []\n get_all_possible_inputs(all_possible_input_patterns, [], 8, 0)\n attractors = []\n\n for input in all_possible_input_patterns:\n old_input_pattern = input\n input_pattern = sgn(np.dot(weights, old_input_pattern))\n count = 1\n while (count < 100): #(count_errors(input_pattern, old_input_pattern) != 0)\n old_input_pattern = input_pattern\n input_pattern = sgn(np.dot(weights, old_input_pattern))\n count = count + 1\n if(count_errors(input_pattern, old_input_pattern) == 0):\n attractors.append(input_pattern)\n break\n \n return remove_duplicates(attractors)\n\ndef sequential_update(weights, pattern):\n pattern = np.array(pattern)\n out_patterns = [pattern.copy()]\n size = range(0, len(pattern))\n converged = False\n for iters in range(0, 20):\n old_pattern = pattern.copy()\n for j in size:\n sum = 0\n for i in size:\n sum += weights[j][i] * pattern[i]\n pattern[j] = np.sign(sum)\n out_patterns.append(pattern.copy())\n if (pattern == old_pattern).all():\n converged = True\n break\n return pattern, out_patterns, converged\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Do some Energy.')\n parser.add_argument('-p', '--part', type=int, required=True,\n help='which part of the assignment to run')\n args = parser.parse_args()\n\n # Memory pattern initiation\n memory_patterns = []\n memory_patterns.append([-1, -1, 1, -1, 1, -1, -1, 1]) #x1\n memory_patterns.append([-1, -1, -1, -1, -1, 1, -1, -1]) #x2\n memory_patterns.append([-1, 1, 1, -1, -1, 1, -1, 1]) #x3\n memory_patterns = np.array(memory_patterns)\n print(\"TRAINING PATTERNS\")\n print(memory_patterns)\n print(\"\")\n\n # Weight initiation\n weights = np.matmul(memory_patterns.T, memory_patterns)\n # Remove self connections\n #for i in range (0, len(weights)):\n #weights[i][i] = 0\n print(\"WEIGHTS\")\n print(weights)\n print(\"\")\n\n # Distorted pattern initiation\n x1d = [1, -1, 1, -1, 1, -1, -1, 1]\n x2d = [1, 1, -1, -1, -1, 1, -1, -1]\n x3d = [1, 1, 1, -1, 1, 1, -1, 1]\n\n # What is the energy at the di erent attractors?\n if args.part == 1:\n attractors = find_attractors(weights)\n print(\"ATTRACTORS: \", len(attractors))\n print(attractors)\n energy_at(weights, attractors, \"attractors\")\n\n # What is the energy at the points of the distorted patterns?\n elif args.part == 2:\n energy_at(weights, [x1d, x2d, x3d], \"distorted input patterns\")\n\n # Follow how the energy changes from iteration to iteration when you use the sequential update rule to approach an attractor.\n elif args.part == 3:\n (_, x1d_seq, _) = sequential_update(weights, x1d)\n (_, x2d_seq, _) = sequential_update(weights, x2d)\n (_, x3d_seq, _) = sequential_update(weights, x3d)\n plot_energies(list(map(lambda x: list(map(lambda y: energy(weights, y), x)), [x1d_seq, x2d_seq, x3d_seq])),\n ['x1d', 'x2d', 'x3d'])\n\n # Generate a weight matrix by setting the weights to normally distributed random numbers, and try iterating an arbitrary starting state. What happens?\n elif args.part == 4:\n converged_count = 0\n for i in range(0, 100):\n arbitrary_weights = np.random.normal(0, 1, (8, 8))\n arbitrary_state = np.ones(8)\n (_, arbitrary_seq, converged) = sequential_update(arbitrary_weights, arbitrary_state)\n if converged:\n converged_count += 1\n plot_energy(list(map(lambda x: energy(arbitrary_weights, x), arbitrary_seq)))\n print(\"converged: \" + str(converged_count) + \" out of 100 times\")\n\n # Make the weight matrix symmetric (e.g. by setting w=0.5*(w+w')). What happens now? Why?\n elif args.part == 5:\n converged_count = 0\n for i in range(0, 100):\n arbitrary_weights = np.random.normal(0, 1, (8, 8))\n arbitrary_weights = np.dot(0.5, arbitrary_weights + arbitrary_weights.T)\n arbitrary_state = np.ones(8)\n (_, arbitrarier_seq, converged) = sequential_update(arbitrary_weights, arbitrary_state)\n if converged:\n converged_count += 1\n plot_energy(list(map(lambda x: energy(arbitrary_weights, x), arbitrarier_seq)))\n print(\"converged: \" + str(converged_count) + \" out of 100 times\")\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"ANN-Lab3/Energy.py","file_name":"Energy.py","file_ext":"py","file_size_in_byte":6161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"265144000","text":"'''\nA paper-reviewer assignment solver that ensures a minimum paper load per reviewer, if possible.\n\nFirst calls an iteration of SimpleSolver with minimum reviewer loads,\nthen calls a second iteration, accounting for the results from the first iteration.\n\nArguments are the same as SimpleSolver,\nexcept that the \"num_reviews\" argument is replaced by \"minimums\" and \"maximums\".\n\n \"minimums\" & \"maximums\":\n lists of length #reviewers. Each item in the lists is an\n integer representing the minimum/maximum number of reviews a reviewer\n should be assigned.\n\n'''\nimport numpy as np\nimport logging\nfrom .simple_solver import SimpleSolver\n\nclass MinMaxSolver:\n '''Implements a min/max assignment graph solver.'''\n def __init__(\n self,\n minimums,\n maximums,\n demands,\n encoder,\n logger=logging.getLogger(__name__)\n ):\n\n self.minimums = minimums\n self.maximums = maximums\n self.demands = demands\n self.cost_matrix = encoder.cost_matrix\n\n if not self.cost_matrix.any():\n self.cost_matrix = np.random.rand(*encoder.cost_matrix.shape)\n\n self.constraint_matrix = encoder.constraint_matrix\n\n self.solved = False\n self.flow_matrix = None\n self.optimal_cost = None\n self.cost = None\n\n self.logger = logger\n\n def solve(self):\n '''Computes combined solution of two SimpleSolvers'''\n\n minimum_solver = SimpleSolver(\n self.minimums,\n self.demands,\n self.cost_matrix,\n self.constraint_matrix,\n logger=self.logger,\n strict=False\n ) # strict=False prevents errors from being thrown for supply/demand mismatch\n\n\n minimum_result = minimum_solver.solve()\n\n adjusted_constraints = self.constraint_matrix - minimum_solver.flow_matrix\n adjusted_maximums = self.maximums - np.sum(minimum_solver.flow_matrix, axis=0)\n adjusted_demands = self.demands - np.sum(minimum_solver.flow_matrix, axis=1)\n\n maximum_solver = SimpleSolver(\n adjusted_maximums,\n adjusted_demands,\n self.cost_matrix,\n adjusted_constraints,\n logger=self.logger)\n\n maximum_result = maximum_solver.solve()\n\n self.solved = True\n self.optimal_cost = minimum_solver.min_cost_flow.OptimalCost() + \\\n maximum_solver.min_cost_flow.OptimalCost()\n\n self.flow_matrix = minimum_result + maximum_result\n self.cost = np.sum(self.flow_matrix * self.cost_matrix)\n\n return self.flow_matrix\n","sub_path":"matcher/solvers/minmax_solver.py","file_name":"minmax_solver.py","file_ext":"py","file_size_in_byte":2631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"63052273","text":"# generating reward schedule for conflict/volatility tasks\r\n# important output variables\r\n# - t1_epochs\r\n# - t2_epochs\r\n# - noisy_pattern\r\n# - volatile_pattern\r\n\r\n\r\nimport numpy as np\r\nimport random\r\nfrom frontendhelpers import *\r\n\r\n\r\ndef define_reward(opt_p, n_trials=400, reward_mu=3, reward_std=1):\r\n\r\n trial_index = np.arange(n_trials)\r\n\r\n # define suboptimal choice reward probability\r\n subopt_p = 1 - opt_p\r\n\r\n # sample rewards\r\n reward_values = np.random.normal(\r\n loc=reward_mu, scale=reward_std, size=n_trials)\r\n\r\n # calcualte n_trials based on probabilities\r\n n_opt_reward_trials = int(opt_p * n_trials)\r\n n_subopt_reward_trials = int(subopt_p * n_trials)\r\n\r\n # find indices for optimal and suboptimal choices\r\n opt_reward_idx = np.random.choice(\r\n trial_index, size=n_opt_reward_trials, replace=False)\r\n subopt_reward_idx = np.setxor1d(trial_index, opt_reward_idx)\r\n\r\n # intialize reward vectors\r\n reward_t1, reward_t2 = np.zeros((n_trials)), np.zeros((n_trials))\r\n\r\n # assign rewards\r\n reward_t1[opt_reward_idx] = reward_values[opt_reward_idx]\r\n reward_t2[subopt_reward_idx] = reward_values[subopt_reward_idx]\r\n\r\n return reward_t1, reward_t2\r\n\r\n\r\ndef define_changepoints(n_trials, reward_t1, reward_t2, cp_lambda):\r\n\r\n # find approximate number of change points\r\n n_cps = int(n_trials / cp_lambda)\r\n cp_base = np.cumsum(\r\n np.random.poisson(\r\n lam=cp_lambda,\r\n size=n_cps)) # calculate cp indices\r\n\r\n cp_idx = np.insert(cp_base, 0, 0) # add 0\r\n cp_idx = np.append(cp_idx, n_trials - 1) # add 0\r\n\r\n cp_idx = cp_idx[cp_idx < n_trials]\r\n\r\n cp_indicator = np.zeros(n_trials)\r\n cp_indicator[cp_idx] = 1\r\n\r\n return cp_idx, cp_indicator\r\n\r\n\r\ndef define_epochs(n_trials, reward_t1, reward_t2, cp_idx, opt_p):\r\n\r\n t1_epochs = []\r\n t2_epochs = []\r\n\r\n subopt_p = 1 - opt_p\r\n\r\n epoch_number = []\r\n epoch_trial = []\r\n epoch_length = []\r\n\r\n reward_p = []\r\n\r\n p_id_solution = [] # female greeble is always first\r\n\r\n f_greeble = ord('f')\r\n m_greeble = ord('m')\r\n\r\n current_target = True\r\n for i in range(len(cp_idx) - 1):\r\n if current_target:\r\n t1_epochs.append(reward_t1[cp_idx[i]:cp_idx[i + 1]])\r\n t2_epochs.append(reward_t2[cp_idx[i]:cp_idx[i + 1]])\r\n reward_p.append(np.repeat(opt_p, cp_idx[i + 1] - cp_idx[i]))\r\n p_id_solution.append(\r\n np.repeat(f_greeble, cp_idx[i + 1] - cp_idx[i]))\r\n else:\r\n t1_epochs.append(reward_t2[cp_idx[i]:cp_idx[i + 1]])\r\n t2_epochs.append(reward_t1[cp_idx[i]:cp_idx[i + 1]])\r\n reward_p.append(np.repeat(subopt_p, cp_idx[i + 1] - cp_idx[i]))\r\n p_id_solution.append(\r\n np.repeat(m_greeble, cp_idx[i + 1] - cp_idx[i]))\r\n\r\n epoch_number.append(np.repeat(i, cp_idx[i + 1] - cp_idx[i]))\r\n epoch_trial.append(np.arange(cp_idx[i + 1] - cp_idx[i]))\r\n epoch_length.append(np.repeat(len(np.arange(\r\n cp_idx[i + 1] - cp_idx[i])), repeats=len(np.arange(cp_idx[i + 1] - cp_idx[i]))))\r\n\r\n if i == len(cp_idx) - 2:\r\n if current_target:\r\n t1_epochs.append(reward_t1[-1])\r\n t2_epochs.append(reward_t2[-1])\r\n reward_p.append(opt_p)\r\n p_id_solution.append(f_greeble)\r\n else:\r\n t1_epochs.append(reward_t2[-1])\r\n t2_epochs.append(reward_t1[-1])\r\n reward_p.append(opt_p)\r\n p_id_solution.append(m_greeble)\r\n\r\n epoch_number.append(i)\r\n\r\n current_target = not(current_target)\r\n\r\n epoch_length[-1] = epoch_length[-1] + 1\r\n # flatten\r\n epoch_number = np.hstack(epoch_number).astype('float')\r\n epoch_trial = np.hstack(epoch_trial).astype('float')\r\n epoch_length = np.hstack(epoch_length).astype('float')\r\n\r\n epoch_trial = np.append(epoch_trial, (epoch_trial[-1] + 1))\r\n epoch_length = np.append(epoch_length, epoch_length[-1])\r\n\r\n t1_epochs = np.hstack(t1_epochs)\r\n t2_epochs = np.hstack(t2_epochs)\r\n reward_p = np.hstack(reward_p).astype('float')\r\n reward_p[-1] = reward_p[-2]\r\n p_id_solution = np.hstack(p_id_solution)\r\n\r\n # Matthew: new code\r\n t1_epochs = np.divide(t1_epochs, 3)\r\n t2_epochs = np.divide(t2_epochs, 3)\r\n for i in range(0, len(t1_epochs)):\r\n if random.uniform(0, 1) > opt_p:\r\n temp = t1_epochs[i]\r\n t1_epochs[i] = t2_epochs[i]\r\n t2_epochs[i] = temp\r\n\r\n return t1_epochs, t2_epochs, epoch_number, reward_p, p_id_solution, epoch_trial, epoch_length\r\n\r\n\r\nn_trials = 600\r\nvolatility = 30\r\nconflict = 0.75\r\n\r\n\r\n(rt1, rt2) = define_reward(1, n_trials)\r\n(cp_idx, cp_indicator) = define_changepoints(n_trials, rt1, rt2, volatility)\r\n(t1_epochs, t2_epochs, epoch_number, reward_p, p_id_solution, epoch_trial,\r\n epoch_length) = define_epochs(10, rt1, rt2, cp_idx, conflict)\r\nnoisy_pattern = [min([.00001, abs(x)]) * 100000 for x in t1_epochs]\r\nvolatile_pattern = [x % 2 for x in epoch_number]\r\n","sub_path":"phaseAsegment2.py","file_name":"phaseAsegment2.py","file_ext":"py","file_size_in_byte":5086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"573665575","text":"\n# Class and section: CS 222 01\n# Program Assignment 1\n# Program Name: CS222Rock-Sebastian-Assign01\n# Due Date: 9/16/2013\n# Program description: Finds duplicate birthdays in a list to prove the birthday paradox.\n\nimport random\n\nprint(\"If more than 23 people are in a room, there is a decent chance the people have a birthday in common!\")\npopulation = int(input(\"Enter the number of people in the room: \"))\npeople = [] # Make an empty list for the people entering the room\n\nfor x in range(population): \n month = random.randint(1, 12) # A random month is chosen.\n # We need the if statements to make sure we have the right number of days.\n \n if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:\n day = random.randint(1, 31)\n\n elif month == 2:\n day = random.randint(1, 28) # If we cared about leap years, we could make this 29\n\n elif month == 4 or month == 6 or month == 9 or month == 11:\n day = random.randint(1, 30)\n\n person = month, day # Creates a tuple, since a person's birthday is static\n people.append(person) # Adds each person in the room to the list of people\n\ntwins = set() # Since sets do not allow duplicates, this prevents a birthday from showing up more than once.\nfor birthdays in people:\n if people.count(birthdays) > 1: # people.count counts the number of instances an element pops up in a list.\n twins.add(birthdays) # Adds duplicate birthday to a list.\n \ntwins = list(twins) # Sets don't support indexing, which we need.\nfor x in twins:\n if x[0] == 1: # Prints out the actual name of the month, just to make it look nicer.\n print(\"January \" + str(x[1]) + \" is a duplicate.\")\n elif x[0] == 2:\n print(\"February \" + str(x[1]) + \" is a duplicate.\")\n elif x[0] == 3:\n print(\"March \" + str(x[1]) + \" is a duplicate.\")\n elif x[0] == 4:\n print(\"April \" + str(x[1]) + \" is a duplicate.\")\n elif x[0] == 5:\n print(\"May \" + str(x[1]) + \" is a duplicate.\")\n elif x[0] == 6:\n print(\"June \" + str(x[1]) + \" is a duplicate.\")\n elif x[0] == 7:\n print(\"July \" + str(x[1]) + \" is a duplicate.\")\n elif x[0] == 8:\n print(\"August \" + str(x[1]) + \" is a duplicate.\")\n elif x[0] == 9:\n print(\"September \" + str(x[1]) + \" is a duplicate.\")\n elif x[0] == 10:\n print(\"October \" + str(x[1]) + \" is a duplicate.\")\n elif x[0] == 11:\n print(\"November \" + str(x[1]) + \" is a duplicate.\")\n elif x[0] == 12:\n print(\"December \" + str(x[1]) + \" is a duplicate.\")\n\nif not twins: # If the list is empty, we print out a different message.\n print(\"There are no birthdays in common!\")\n\ninput(\"\\nPress the enter key to exit.\")\n \n","sub_path":"Python/CS222-Assign01/CS222-Assign01.py","file_name":"CS222-Assign01.py","file_ext":"py","file_size_in_byte":2916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"568923927","text":"# encoding=utf8\r\n\r\n\"\"\"\r\nMethods for factoring integers into products of smaller primes.\r\n\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom mathpy.numtheory.integers import issquare\r\nfrom mathpy.numtheory.divisibility import gcd\r\n\r\n\r\ndef factor_trial(n):\r\n r\"\"\"\r\n Front-end function for performing integer factorization.\r\n\r\n Parameters\r\n ----------\r\n n : int or float\r\n Integer to be factored into product of smaller integers.\r\n\r\n Returns\r\n -------\r\n tuple\r\n A list containing the factors of :math:`n` should they exist. If :math:`n`\r\n is prime, the returned list will only contain :math:`n`.\r\n\r\n Examples\r\n --------\r\n >>> factor_trial(4)\r\n [2.0, 2.0]\r\n >>> factor_trial(13)\r\n 13\r\n >>> n = 9.24\r\n >>> factor_trial(n)\r\n [3.0, 3.0]\r\n\r\n Notes\r\n -----\r\n Integer factorization by trial division is the most inefficient algorithm for decomposing\r\n a composite number. Trial division is the method of testing if :math:`n` is divisible by\r\n a smaller number, beginning with 2 and proceeding upwards. This order is used to eliminate\r\n the need to test for multiples of 2 and 3. Also, the trial factors never need to go further\r\n than the square root of :math:`n`, :math:`\\sqrt{n}`, due to the fact that if :math:`n` has\r\n a factor, there exists a factor :math:`f \\leq \\sqrt{n}`.\r\n\r\n References\r\n ----------\r\n Trial division. (2017, April 30). In Wikipedia, The Free Encyclopedia.\r\n From https://en.wikipedia.org/w/index.php?title=Trial_division&oldid=778023614\r\n\r\n \"\"\"\r\n if n != np.floor(n):\r\n n = np.floor(n)\r\n if np.absolute(n) < 2:\r\n return [1, n]\r\n\r\n div = 2.0\r\n factors = []\r\n\r\n while n % div == 0:\r\n factors.append(div)\r\n n /= div\r\n\r\n div += 1\r\n\r\n while n > 1 and div <= np.sqrt(n):\r\n if n % div == 0:\r\n factors.append(div)\r\n n /= div\r\n else:\r\n div += 2\r\n\r\n if n > 1:\r\n factors.append(n)\r\n\r\n if len(factors) == 1:\r\n factors = [1, factors[0]]\r\n\r\n return factors\r\n\r\n\r\ndef fermat_factor(n):\r\n r\"\"\"\r\n Computes the factorization of an integer :math:`n` by Fermat's factorization method.\r\n\r\n Parameters\r\n ----------\r\n n : int or float\r\n Integer to compute the factorization using Fermat's approach. If the supplied value\r\n is not an integer, the function coerces the value into an integer.\r\n\r\n Returns\r\n -------\r\n tuple\r\n Contains the factors of :math:`n`, :math:`a` and :math:`b` defined by\r\n Fermat's factorization theorem.\r\n\r\n Notes\r\n -----\r\n Fermat's factorization theorem redefines a composite number :math:`n` as the\r\n difference of squares:\r\n\r\n .. math::\r\n\r\n n = a^2 - b^2\r\n\r\n Which can also be written as:\r\n\r\n .. math::\r\n\r\n n = (a + b)(a - b)\r\n\r\n Examples\r\n --------\r\n >>> fermat_factor(5959)\r\n (59.0, 101.0)\r\n\r\n References\r\n ----------\r\n Barnes, C. (2004). Integer Factorization Algorithms (1st ed.).\r\n Corvallis, OR: Department of Physics, Oregon State University.\r\n\r\n Fermat's factorization method. (2017, January 31). In Wikipedia, The Free Encyclopedia.\r\n From https://en.wikipedia.org/w/index.php?title=Fermat%27s_factorization_method&oldid=763010603\r\n\r\n \"\"\"\r\n if n != np.floor(n):\r\n n = np.floor(n)\r\n\r\n if np.absolute(n) <= 2:\r\n return 1, n\r\n\r\n a = np.ceil(np.sqrt(n))\r\n b = np.power(a, 2) - n\r\n while issquare(b) is False:\r\n a += 1\r\n b = np.power(a, 2) - n\r\n\r\n return a - np.sqrt(b), a + np.sqrt(b)\r\n\r\n\r\ndef pollardrho(n):\r\n r\"\"\"\r\n Implementation of Pollard's rho algorithm for factorizing an integer :math:`n`\r\n into two non-trivial prime numbers.\r\n\r\n Returns\r\n -------\r\n tuple\r\n List containing the two prime factors of :math:`n`, should they exist.\r\n\r\n Notes\r\n -----\r\n Pollard rho Factorization is another algorithm for factoring an integer :math:`n` where\r\n :math:`n = pq`. :math:`n` . Pollard's rho factorization iterates the formula:\r\n\r\n .. math::\r\n\r\n x_{n+1} = x_n^2 + a(mod n)\r\n\r\n The algorithm is much more efficient than the trial division factorization method but can\r\n be very slow under poor conditions.\r\n\r\n Examples\r\n --------\r\n >>> pollardrho(8051)\r\n (97, 83)\r\n >>> pollardrho(10403)\r\n (101, 103)\r\n\r\n References\r\n ----------\r\n Barnes, C. (2004). Integer Factorization Algorithms (1st ed.).\r\n Corvallis, OR: Department of Physics, Oregon State University.\r\n\r\n Pollard's rho algorithm. (2017, May 6). In Wikipedia, The Free Encyclopedia.\r\n From https://en.wikipedia.org/w/index.php?title=Pollard%27s_rho_algorithm&oldid=779076841\r\n\r\n Weisstein, Eric W. \"Pollard rho Factorization Method.\" From MathWorld--A Wolfram Web Resource.\r\n http://mathworld.wolfram.com/PollardRhoFactorizationMethod.html\r\n\r\n \"\"\"\r\n if n != np.floor(n):\r\n n = np.floor(n)\r\n if np.absolute(n) < 2:\r\n return 1, n\r\n\r\n x = 2\r\n y = 2\r\n d = 1\r\n\r\n while d == 1:\r\n x = (np.power(x, 2) + 1) % n\r\n y = (np.power(np.power(y, 2) + 1, 2) + 1) % n\r\n d = gcd(np.absolute(x - y), n)\r\n\r\n if d == n:\r\n return 1, n\r\n else:\r\n return d, n // d\r\n","sub_path":"mathpy/numtheory/factor.py","file_name":"factor.py","file_ext":"py","file_size_in_byte":5294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"549306361","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 23 02:56:37 2018\n\n@author: Harnick Khera github/hephyrius\n\n\nclass is responsible for utility functions such as hashing\n\n\"\"\"\nimport cryptography\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives import hashes\nfrom cryptography.hazmat.primitives.serialization import load_pem_public_key\nfrom cryptography.hazmat.primitives.asymmetric import ec\n\nimport hashlib\n\n\nclass UtilFunctions:\n \n \n def applySha256(self, _inputData):\n calculatedhash = hashlib.sha256(_inputData.encode())\n hex_dig = calculatedhash.hexdigest()\n \n # return calculatedhash, hex_dig\n return hex_dig\n \n #apply Private key to the transactiondata\n def ApplyECDSignature(PrivateKey, Data):\n Signature = PrivateKey.sign( Data, ec.ECDSA(hashes.SHA256()))\n return Signature\n \n \n #verify a signature using a public key, if no error is thrown we get a bool of true, else we get a false\n def verifyECDSignature(Publickey, Data, Signature):\n #print(Publickey)\n Pub = load_pem_public_key(Publickey.encode(), default_backend())\n try:\n Pub.verify(Signature, Data, ec.ECDSA(hashes.SHA256()))\n return True\n except Exception as e:\n #print(e)\n return False\n \n \n #calculate merkel root - not advanced but simple\n def GetMerkelRoot(transactions):\n \n count = len(transactions)\n \n previousLayer = []\n \n for i in transactions:\n previousLayer.append(i.TransactionHash)\n \n \n while count > 1:\n treeLayer = []\n \n for i in range(1,len(previousLayer)):\n treeLayer.append(applySha256(previousLayer[i-1]+previousLayer[i]))\n \n count = len(treeLayer)\n previousLayer = treeLayer\n \n root = \"\"\n if len(root) == 1:\n root = treeLayer[0]\n \n return root\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Truncated_Experiment/UtilFunctions.py","file_name":"UtilFunctions.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"493737300","text":"import math\nfrom adversarialsearchproblem import AdversarialSearchProblem\n\ndef alpha_beta_cutoff(asp, cutoff_ply, eval_func):\n \"\"\"\n This function should:\n - search through the asp using alpha-beta pruning\n - cut off the search after cutoff_ply moves have been made.\n\n Inputs:\n asp - an AdversarialSearchProblem\n cutoff_ply- an Integer that determines when to cutoff the search\n and use eval_func.\n For example, when cutoff_ply = 1, use eval_func to evaluate\n states that result from your first move. When cutoff_ply = 2, use\n eval_func to evaluate states that result from your opponent's\n first move. When cutoff_ply = 3 use eval_func to evaluate the\n states that result from your second move.\n You may assume that cutoff_ply > 0.\n eval_func - a function that takes in a GameState and outputs\n a real number indicating how good that state is for the\n player who is using alpha_beta_cutoff to choose their action.\n You do not need to implement this function, as it should be provided by\n whomever is calling alpha_beta_cutoff, however you are welcome to write\n evaluation functions to test your implementation. The eval_func we provide\n does not handle terminal states, so evaluate terminal states the\n same way you evaluated them in the previous algorithms.\n\n Output: an action(an element of asp.get_available_actions(asp.get_start_state()))\n \"\"\"\n\n # initializing variables\n start_state = asp.get_start_state()\n player = start_state.player_to_move()\n optimal_move = None\n alpha = -math.inf # note - alpha at the initial state is the same as the max score\n beta = math.inf\n\n # finding the best move\n for action in asp.get_available_actions(start_state):\n next_state = asp.transition(start_state, action)\n next_score = cutoff_ab_min_value(asp, next_state, player, alpha, beta, cutoff_ply - 1, eval_func)\n\n if next_score > alpha: # if a value is found above the lower bound we increase alpha\n alpha = next_score\n optimal_move = action\n\n return optimal_move\n\n\ndef cutoff_ab_max_value(asp, state, player, alpha, beta, depth, eval_func):\n \"\"\"helper function for minimax\n\n Inputs: asp - an adversarial search problem\n state - the current game state\n player - the player whose turn it is\n\n Outputs: a value reflecting the minimum possible score that the player can\n attain from a state assuming optimal game play by both players\n \"\"\"\n if asp.is_terminal_state(state):\n if asp.evaluate_state(state)[player]:\n return math.inf\n else:\n return -math.inf\n elif depth == 0:\n return eval_func(state,player)\n else:\n max_score = float(\"-inf\")\n for action in asp.get_available_actions(state):\n next_state = asp.transition(state, action)\n next_score = cutoff_ab_min_value(asp, next_state, player, alpha, beta, depth - 1, eval_func)\n if next_score >= beta: # if a value is found above the upper bound we prune\n return next_score\n if next_score > alpha: # if a value is found above the lower bound we increase alpha\n alpha = next_score\n if next_score > max_score:\n max_score = next_score\n\n return max_score\n\n\ndef cutoff_ab_min_value(asp, state, player, alpha, beta, depth, eval_func):\n \"\"\"Inputs: asp - an adversarial search problem\n state - the current game state\n player - the player whose turn it is\n\n Outputs: a value reflecting the maximum possible score that the player can\n attain from a state assuming optimal game play by both players\n \"\"\"\n if asp.is_terminal_state(state):\n if asp.evaluate_state(state)[player]:\n return math.inf\n else:\n return -math.inf\n elif depth <= 0:\n return eval_func(state, player)\n else:\n min_score = math.inf\n for action in asp.get_available_actions(state):\n next_state = asp.transition(state, action)\n next_score = cutoff_ab_max_value(asp, next_state, player, alpha, beta, depth - 1, eval_func)\n if next_score <= alpha: # if a value is found below the lower bound we prune\n return next_score\n if next_score < beta: # if a value is found below the upper bound we decrease beta\n beta = next_score\n if next_score < min_score:\n min_score = next_score\n\n return min_score\n","sub_path":"bot_algorithms/alpha_beta_cutoff.py","file_name":"alpha_beta_cutoff.py","file_ext":"py","file_size_in_byte":4786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"450338963","text":"import mysql.connector\n\ndef main():\n File_to_DB()\n\n\ndef File_to_DB():\n \"\"\"\n This script will take the file, transferFile.txt, which contains a text version of the database,\n and input all the book metadata into the database.\n\n When you run it make sure you switch the variables in the creation of conn and the path to the file transferFile\n :return:\n \"\"\"\n conn = mysql.connector.connect(\n user='root',\n password='MaximumHaze16',\n host='localhost',\n database='seniordesign'\n )\n cur = conn.cursor()\n fr = open(\"C:\\\\users\\\\sarah\\\\desktop\\\\dbtransfer2\\\\transferFile.txt\", 'r')\n count =0\n for line in fr:\n id = int(line[0:line.find(\"%\")])\n title= line[line.find(\"%\")+1:line.find(\"%%\")]\n author = line[line.find(\"%%\")+2:line.find(\"%%%\")]\n genre = line[line.find(\"%%%\")+3:line.find(\"%%%%\")]\n length = int(line[line.find(\"%%%%\")+4:line.find(\"%%%%%\")])\n cur.execute(\"insert into example values(%s,%s,%s,%s,%s)\",(id,title,author,genre,length))\n\n conn.commit()\n conn.close()\n fr.close()\n\nif __name__ == '__main__':\n main()","sub_path":"Python/SeniorDesign/transferscript.py","file_name":"transferscript.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"594046629","text":"from util.network_util import *\nimport tensorflow as tf\nfrom model.networks.base_network import *\n\nclass RNNModel(BaseModel):\n def __init__(self, params, input_size, num_classes, seed, init):\n super(RNNModel, self).__init__(params)\n\n self.Network['Recurrent'] = []\n\n for ii in range(len(self.params.rnn_r_hidden_seq)):\n init_data = \\\n {'w_init_method': 'normc', 'w_init_para': {'stddev':1.0}}\n\n if self.params.rnn_bidirectional:\n pass\n elif self.params.rnn_dilated:\n pass\n else:\n self.Network['Recurrent'].append(Recurrent_Network_with_mask(\n scope='rnn'+str(ii), activation_type=self.params.rnn_r_act_seq[ii],\n normalizer_type=self.params.rnn_r_norm_seq[ii],\n recurrent_cell_type=self.params.rnn_cell_type,\n train=True, hidden_size=self.params.rnn_r_hidden_seq[ii],\n input_depth=input_size, init_data=init_data\n ))\n input_size = self.params.rnn_r_hidden_seq[ii]\n\n network_shape = [self.params.rnn_r_hidden_seq[-1]] + \\\n self.params.rnn_l_hidden_seq + [num_classes]\n\n num_layer = len(network_shape) - 1\n act_type = \\\n self.params.rnn_l_act_seq + [None]\n norm_type = \\\n self.params.rnn_l_norm_seq + [None]\n init_data = []\n for _ in range(num_layer):\n init_data.append(\n {'w_init_method': 'xavier', 'w_init_para': {'uniform': False},\n 'b_init_method': 'constant', 'b_init_para': {'val': 0.0}}\n )\n self.Network['Linear'] = MLPWithMask(\n dims=network_shape, scope='mlp',\n activation_type=act_type, normalizer_type=norm_type,\n train=True, init_data=init_data, seed=seed\n )\n\n def __call__(self, input):\n self.Tensor['Intermediate'] = [None for _ in self.Network['Recurrent']]\n for i, network in enumerate(self.Network['Recurrent']):\n self.Tensor['Intermediate'][i] = network(input)[0]\n input = self.Tensor['Intermediate'][i]\n self.Tensor['Predictions'] = self.Network['Linear'](self.Tensor['Intermediate'][-1])\n return self.Tensor['Predictions']\n\n def weight_variables(self):\n weights = []\n for net in self.Network['Recurrent']:\n weights += net.weights()\n return weights + self.Network['Linear'].weights()\n\n def get_mask(self):\n mask = []\n for net in self.Network['Recurrent']:\n mask += net.get_mask()\n return mask + self.Network['Linear'].get_mask()\n\n def get_weighted_mask(self):\n weighted_mask = []\n for net in self.Network['Recurrent']:\n weighted_mask += net.get_weighted_mask()\n\n return weighted_mask + self.Network['Linear'].get_weighted_mask()\n\n\n\n\n","sub_path":"model/networks/rnn.py","file_name":"rnn.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"491238821","text":"# --*--coding: utf-8--*--\n# @Time: 2021/2/15\n# @Author: Leander\n# @File: 01 开启线程的两种方式\n# 第一种方式\n# from threading import Thread\n# import time\n#\n# def task(name):\n# print(f'name is running')\n# time.sleep(1)\n# print(f'name is over')\n#\n# # 开启线程不需要在main下面执行代码 直接书写就可以\n# # 但是我们还是习惯性的将启动命令写在main 下面\n#\n# t = Thread(target=task, args=('egon',))\n# t.start() # 创建线程的开销非常小,几乎是代码一执行线程就已经创建了\n# print('主')\n\n# 第二种方式\n\nfrom threading import Thread\nimport time\nclass MyThread(Thread):\n def __init__(self, name):\n \"\"\"针对双下划线开头双下划綫结尾(__init__)的方法,统一读成双下init\"\"\"\n # 重写了别人的方法,又不知道别人的方法里有啥,你就调用父类的方法\n super(MyThread, self).__init__()\n self.name = name\n def run(self):\n print(f'{self.name} is running')\n\nif __name__ == '__main__':\n t = MyThread('egon')\n t.start()","sub_path":"2021-02-16/01 开启线程的两种方式.py","file_name":"01 开启线程的两种方式.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"588160911","text":"'''-------------------------------------------------------------------------------\n Tool Name: CreateMuskingumXFile\n Source Name: CreateMuskingumXFile.py\n Version: ArcGIS 10.3\n License: Apache 2.0\n Author: Andrew Dohmann and Alan Snow\n Updated by: Andrew Dohmann\n Description: Produces \n History: Initial coding - 06/27/2016, version 1.0\n Updated: Version 1.1, 06/27/2016, initial coding\n-------------------------------------------------------------------------------'''\nimport arcpy\nimport csv\nimport os\nimport time\n\nclass CreateMuskingumXFile(object):\n def __init__(self):\n \"\"\"Define the tool (tool name is the name of the class).\"\"\"\n self.label = \"Create Muskingum X File\"\n self.description = (\"Creates the Muskingum X file for RAPID\")\n self.canRunInBackground = False\n self.category = \"Calibration\"\n\n def getParameterInfo(self):\n \"\"\"Define parameter definitions\"\"\"\n input_Drainage_Lines = arcpy.Parameter(name=\"input_Drainage_Lines\",\n displayName=\"Input Drainage Lines\",\n direction=\"Input\",\n parameterType=\"Required\",\n datatype=\"GPFeatureLayer\")\n input_Drainage_Lines.filter.list = ['Polyline']\n\n stream_id = arcpy.Parameter(name = \"stream_ID\",\n displayName = \"Stream ID\",\n direction = \"Input\",\n parameterType = \"Required\",\n datatype = \"Field\"\n )\n stream_id.parameterDependencies = [\"input_Drainage_Lines\"]\n stream_id.filter.list = ['Short', 'Long', 'Double']\n stream_id.value = \"HydroID\"\n\n out_muskingum_x_file = arcpy.Parameter(name = 'out_muskingum_x_file',\n displayName = 'Muksingum X File',\n datatype = 'DEFile',\n parameterType = 'Required',\n direction = 'Output')\n \n params = [input_Drainage_Lines,\n stream_id,\n out_muskingum_x_file]\n\n return params\n\n def isLicensed(self):\n \"\"\"Set whether tool is licensed to execute.\"\"\"\n return True\n\n def updateParameters(self, parameters):\n \"\"\"Modify the values and properties of parameters before internal\n validation is performed. This method is called whenever a parameter\n has been changed.\"\"\"\n if parameters[2].altered:\n (dirnm, basenm) = os.path.split(parameters[2].valueAsText)\n if not basenm.endswith(\".csv\"):\n parameters[2].value = os.path.join(\n dirnm, \"{}.csv\".format(basenm))\n else:\n parameters[2].value = os.path.join(\n arcpy.env.scratchFolder, \"x.csv\")\n\n def updateMessages(self, parameters):\n \"\"\"Modify the messages created by internal validation for each tool\n parameter. This method is called after internal validation.\"\"\"\n return\n\n def execute(self, parameters, messages):\n \"\"\"The source code of the tool.\"\"\"\n \n Drainage_Lines = parameters[0].valueAsText\n stream_id = parameters[1].valueAsText\n out_muskingum_x_file = parameters[2].valueAsText\n\n Musk_x_field = \"Musk_x\"\n # Process: Muskingum x \n #check to see if a Muskingum x already exists, if not, add the field\n fieldList = arcpy.ListFields(Drainage_Lines, Musk_x_field)\n fieldCount = len(fieldList)\n if (fieldCount < 1):\n arcpy.AddError(\"The Musk_x field is missing. To fix this, run the \\\"Create Muskingum X Field\\\" tool.\")\n \n #generate file \n ##make a list of all of the fields in the table\n field_names = [stream_id, Musk_x_field]\n with open(out_muskingum_x_file,'wb') as csvfile:\n connectwriter = csv.writer(csvfile, dialect='excel')\n for row in sorted(arcpy.da.SearchCursor(Drainage_Lines, field_names)):\n connectwriter.writerow([row[1]])\n\n \n return\n","sub_path":"toolbox/scripts/CreateMuskingumXFile.py","file_name":"CreateMuskingumXFile.py","file_ext":"py","file_size_in_byte":4330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"342232578","text":"#######################################################################\n# Drum Machine #\n# #\n# CREATORS: #\n### Ashley Babjac #\n### Zoe Babyar #\n# #\n# PROGRAM DESCRIPTION: #\n### Simple Drum-Machine game that allows user to choose sounds and #\n### place them in measure to create a beat #\n# #\n# VERSION: 0.0 #\n### Simple Set up of graphics with no logic components #\n#######################################################################\n\n\nimport pygame, time, pygameMenu\npygame.mixer.pre_init(44100, 16, 2, 4096)\npygame.init()\n\n#screen size constants\ndisplay_width = 800\ndisplay_height = 600\n\n#color constants\nblack = (0,0,0)\nwhite = (255, 255, 255)\nred = (255, 0, 0)\nred2 = (199,26,7)\nblue = (0,0,255)\nblue2 = (52,7,199)\ngreen = (0,255,0)\ngreen2 = (19,199,7)\nyellow = (255,230,0)\nyellow2 = (179,191,22)\npurple = (178,49,188)\npurple2 = (81,0,115)\npink = (255,0,205)\npink2 = (196,26,134)\norange = (255, 137,0)\norange2 = (166,67,0)\nteal = (0,255,255)\nteal2 = (0,142,100)\ngray = (190,205,210)\n\n#sound constants\n#hi_hat = pygame.mixer.Sound(\"../sounds/hihat.wav\")\n#kick = pygame.mixer.Sound(\"../sounds/kick.wav\")\n#rimshot = pygame.mixer.Sound(\"../sounds/rimshot.wav\")\n#shaker = pygame.mixer.Sound(\"../sounds/shaker.wav\")\n#snare = pygame.mixer.Sound(\"../sounds/snare.wav\")\n\n#set up window\ngameDisplay = pygame.display.set_mode((display_width, display_height))\npygame.display.set_caption('UTK Drum Machine')\ngameDisplay.fill(gray)\n\n#initialize FPS(frames per second) clock\nclock = pygame.time.Clock()\n\n#helper function for display_message\ndef text_objects(text, font, color):\n\ttextSurface = font.render(text, True, color)\n\treturn textSurface, textSurface.get_rect()\n\n#prints a message to the game screen\ndef message_display(text, font, size, location_w, location_h, color, action=None):\n\tText = pygame.font.SysFont(font, size)\n\tTextSurf, TextRect = text_objects(text, Text, color)\n\tTextRect.center = ((location_w, location_h))\n\tgameDisplay.blit(TextSurf, TextRect)\n\n\tpygame.display.update()\n\n#general button pressing function\ndef button(msg,x,y,w,h,ic,ac,font_size):\n mouse = pygame.mouse.get_pos()\n click = pygame.mouse.get_pressed()\n\n if x+w > mouse[0] > x and y+h > mouse[1] > y:\n pygame.draw.rect(gameDisplay, ac,(x,y,w,h))\n\n #if click[0] == 1:\n #depends on the click\n\n else:\n pygame.draw.rect(gameDisplay, ic,(x,y,w,h))\n\n smallText = pygame.font.SysFont(\"comicsansms\",font_size)\n textSurf, textRect = text_objects(msg, smallText, black)\n textRect.center = ( (x+(w/2)), (y+(h/2)) )\n gameDisplay.blit(textSurf, textRect)\n\n\n\n\n#sets up the game display for the user\ndef set_up_display():\n\t#start and stop buttons\n button(\"start\", display_width/2+50, display_height/15, 50, 50, green, green2, 20)\n button(\"stop\", display_width/2+120, display_height/15, 50, 50, red, red2, 20)\n\n\t#set up sound buttons\n\t#thinking about changing sound buttons to drop down menu as well\n button(\"hi-hat\", display_width/50, display_height/6, 50, 50, blue, blue2, 20)\n button(\"kick\", display_width/50+70, display_height/6, 50, 50, blue, blue2, 20)\n button(\"rimshot\", display_width/50+140, display_height/6, 50, 50, blue, blue2, 20)\n button(\"shaker\", display_width/50+210, display_height/6, 50, 50, blue, blue2, 20)\n button(\"snare\", display_width/50+280, display_height/6, 50, 50, blue, blue2, 20)\n\n\t#indentation error here?\n\t#generall area where we will \"drag\" sounds\n\t#pygame.draw.rect(gameDisplay, black, (0,250,800,350))\n\t#where I am thinking of putting the timing drop down menu\n\t#pygame.draw.rect(gameDisplay, teal, ())\n\n\t#set timing menu\n\t#having trouble getting pop-up menu for timing working\n\t#refer to https://github.com/ppizarror/pygame-menu for menu commands and examples\n\t#timer_menu = pygameMenu.Menu(gameDisplay,\n\t#\tdopause=False,\n\t#\tfont=pygameMenu.fonts.FONT_NEVIS,\n\t#\tmenu_alpha=85,\n\t#\tmenu_color=(0, 0, 0), # Background color\n\t#\tmenu_color_title=(0, 0, 0),\n\t#\tmenu_height=int(H_SIZE / 2),\n\t#\tmenu_width=600,\n\t#\tonclose=PYGAME_MENU_RESET, # If this menu closes (press ESC) back to main\n\t#\ttitle='Timer Menu',\n\t#\ttitle_offsety=5, # Adds 5px to title vertical position\n\t#\twindow_height=H_SIZE,\n\t#\twindow_width=W_SIZE\n\t#\t)\n\n\n#runs the game\ndef game_loop():\n\tcrashed = False\n\n\twhile not crashed:\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tcrashed = True\n\t\t\t#otherwise do something\n\n\t\tset_up_display()\n\t\tpygame.display.update()\n\n\t\tclock.tick(60)\n\n#title\nmessage_display(\"Drum Machine\", \"Helvetica\", 60, display_width/4, display_height/10, black)\n\ngame_loop()\npygame.quit()\nquit()\n","sub_path":"developement_app/drum_machine_v_0.0.0.py","file_name":"drum_machine_v_0.0.0.py","file_ext":"py","file_size_in_byte":5143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"417134509","text":"from django.contrib.auth.models import Permission\nfrom django.test import TestCase\nfrom django.urls import reverse\n\nfrom wagtail.test.snippets.models import StandardSnippet\nfrom wagtail.test.utils import WagtailTestUtils\n\n\nclass TestSnippetDeleteView(WagtailTestUtils, TestCase):\n def setUp(self):\n self.snippet_model = StandardSnippet\n\n # create a set of test snippets\n self.test_snippets = [\n self.snippet_model.objects.create(\n text=f\"Title-{i}\",\n )\n for i in range(1, 6)\n ]\n\n self.user = self.login()\n self.url = (\n reverse(\n \"wagtail_bulk_action\",\n args=(\n self.snippet_model._meta.app_label,\n self.snippet_model._meta.model_name,\n \"delete\",\n ),\n )\n + \"?\"\n )\n for snippet in self.test_snippets:\n self.url += f\"id={snippet.pk}&\"\n\n def test_simple(self):\n response = self.client.get(self.url)\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(\n response, \"wagtailsnippets/bulk_actions/confirm_bulk_delete.html\"\n )\n\n def test_bulk_delete(self):\n response = self.client.post(self.url)\n\n # Should redirect back to index\n self.assertEqual(response.status_code, 302)\n\n # Check that the users were deleted\n for snippet in self.test_snippets:\n self.assertFalse(self.snippet_model.objects.filter(pk=snippet.pk).exists())\n\n def test_delete_with_limited_permissions(self):\n self.user.is_superuser = False\n self.user.user_permissions.add(\n Permission.objects.get(\n content_type__app_label=\"wagtailadmin\", codename=\"access_admin\"\n )\n )\n self.user.save()\n\n response = self.client.get(self.url)\n self.assertEqual(response.status_code, 200)\n\n html = response.content.decode()\n self.assertInHTML(\n \"

You don't have permission to delete these standard snippets

\",\n html,\n )\n\n for snippet in self.test_snippets:\n self.assertInHTML(f\"
  • {snippet.text}
  • \", html)\n\n response = self.client.post(self.url)\n # User should be redirected back to the index\n self.assertEqual(response.status_code, 302)\n\n # Documents should not be deleted\n for snippet in self.test_snippets:\n self.assertTrue(self.snippet_model.objects.filter(pk=snippet.pk).exists())\n","sub_path":"wagtail/snippets/tests/test_bulk_actions/test_bulk_delete.py","file_name":"test_bulk_delete.py","file_ext":"py","file_size_in_byte":2588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"160962436","text":"from __future__ import print_function\nimport os\nimport sys\nimport json\nimport numpy as np\nimport cPickle\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\ndef create_glove_embedding_init(idx2word, glove_file):\n word2emb = {}\n with open(glove_file, 'r') as f:\n entries = f.readlines()\n emb_dim = len(entries[0].split(' ')) - 1\n print('embedding dim is %d' % emb_dim)\n weights = np.zeros((len(idx2word), emb_dim), dtype=np.float32)\n\n for entry in entries:\n vals = entry.split(' ')\n word = vals[0]\n vals = map(float, vals[1:])\n word2emb[word] = np.array(vals)\n for idx, word in enumerate(idx2word):\n if word not in word2emb:\n continue\n weights[idx] = word2emb[word]\n return weights, word2emb\n\n\nif __name__ == '__main__':\n # seg_cats = json.load(open('instances_val2014.json'))['categories']\n # {u'id': 87, u'name': u'scissors', u'supercategory': u'indoor'}\n\n idx2word = []\n obj_voc = cPickle.load(open('objects_vocab.pkl'))['idx2word']\n for c in xrange(1600):\n tmp = obj_voc[c][:-1].split(',')[0]\n idx2word.append(tmp)\n attr_voc = cPickle.load(open('attributes_vocab.pkl'))['idx2word']\n for c in xrange(400):\n tmp = attr_voc[c][:-1].split(',')[0]\n idx2word.append(tmp)\n emb_dim = 300\n cPickle.dump(idx2word, open('obj_attr_idx2word.pkl', 'wb'))\n glove_file = 'glove.6B.%dd.txt' % emb_dim\n weights, word2emb = create_glove_embedding_init(idx2word, glove_file)\n np.save('../glove6b_obj_attr_init_%dd.npy' % emb_dim, weights)\n","sub_path":"scripts/create_obj_att_embed.py","file_name":"create_obj_att_embed.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"318227724","text":"import sys\nimport xmltodict\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\ndef getcontributors(result):\n thelist = result['root']['metadata']['oai_dc:dc']['dc:contributor']['item']\n thelistcomprehended = [ item['#text'] for item in thelist ]\n return thelistcomprehended\n\ndef getabstract(result):\n abstract = result['root']['metadata']['oai_dc:dc']['key'][7]['#text']\n return abstract\n\ndef getid(result):\n theid = result['root']['header']['identifier']['#text']\n return theid\n\ndef normalize(result, timestamp):\n result2 = xmltodict.parse(result)\n #import pdb; pdb.set_trace()\n payload = {\n \"doc\": {\n 'title': result2['root']['metadata']['oai_dc:dc']['key'][5]['#text'],\n 'contributors': [result2['root']['metadata']['oai_dc:dc']['key'][6]['#text']] + getcontributors(result2),\n 'properties': {\n 'abstract': getabstract(result2)\n },\n 'meta': {},\n 'id': getid(result2),\n 'source': \"VTechWorks\",\n 'timestamp': str(timestamp)\n }\n }\n return payload\n\n# these tests assume that a file named 'output.xml' was created, using the first item of the tuple generated at\n# the end of consume.py; that file generation line is still in there, but you'll have to uncomment it to test\n\n# def test_normalize_makes_dictionary():\n# with open('output.xml','r') as f:\n# theresult = f.read()\n# assert isinstance(normalize(theresult, datetime.now()), dict)\n\n# def test_get_contributors():\n# with open('output.xml','r') as f:\n# theresult = f.read()\n# result2 = xmltodict.parse(theresult)\n# assert isinstance(getcontributors(result2), list)\n# assert getcontributors(result2)[0] == 'Mechanical Engineering'\n\n# def test_get_abstract():\n# with open('output.xml','r') as f:\n# theresult = f.read()\n# result2 = xmltodict.parse(theresult)\n# #print(type(getabstract(result2)))\n# assert isinstance(getabstract(result2), (str,unicode))\n\n# def test_get_id():\n# with open('output.xml','r') as f:\n# theresult = f.read()\n# result2 = xmltodict.parse(theresult)\n# assert isinstance(getid(result2), (str,unicode))\n# assert getid(result2) == 'oai:vtechworks.lib.vt.edu:10919/49545' \n","sub_path":"normalize.py","file_name":"normalize.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"454603240","text":"\r\n\"\"\" \r\n.. module:: OEP_OPCUAServer\r\n :platform: Unix, Windows\r\n :synopsis: Easy to use OPC UA Server\r\n\r\n.. moduleauthor:: Mikel Ayani \r\n\"\"\"\r\n\r\nfrom threading import Thread # OEP is a thread\r\nfrom multiprocessing import Process, Pipe # To execute engines in subprocesses\r\nfrom opcua import ua, Node, Server, uamethod # OPCUA Server\r\nfrom opcua.common import ua_utils # OPCUA Utils\r\nfrom xml.etree import ElementTree # Handling of xml files\r\nfrom xml.etree.ElementTree import XML # Handling of xml files\r\nimport shutil # Copy files\r\nimport os # cache handling\r\nimport ast # literal_eval\r\nimport datetime, hashlib # Generate hash keys for client connections\r\nimport time # Sleep and clock\r\nimport pathlib # Create and manage folders\r\nimport logging # Internal logger\r\nimport json # dict to string\r\nfrom RestClient import RestClient # Cloud API\r\nfrom oep_physics_engine import oep_physics_engine\r\nfrom oep_behavior_engine import oep_behavior_engine\r\n\r\n\r\nDEBUG_MODE = True # Activate Debug mode\r\n\r\n\r\n'''\r\nBaseType = {'Class': 'ObjectType' or 'VariableType,\r\n 'Variables': (Name, data_type, array_dimension, value),\r\n 'property': (Name, data_type, array_dimension, value),\r\n'''\r\n\r\nBaseTypes = {}\r\n\r\nBaseTypes['workspace'] = {'Class': 'ObjectType', \r\n 'Variables': [],\r\n 'Properties': [],\r\n 'Methods': [('LoadSystem', 'LoadSystem', [ua.VariantType.String], [ua.VariantType.Boolean])],\r\n 'Folders': []}\r\n\r\n'''\r\nBaseTypes['products'] = {'Class': 'ObjectType',\r\n 'Variables': [],\r\n 'Properties': [],\r\n 'Methods': [('CreateProduct', 'CreateProduct', [ua.VariantType.String, ua.VariantType.String], [ua.VariantType.NodeId])],\r\n 'Folders': []}\r\n\r\nBaseTypes['product'] = {'Class': 'ObjectType',\r\n 'Variables': [('Frame', ua.uatypes.VariantType.Float, 7, [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0])],\r\n 'Properties': [('Base Body', ua.uatypes.VariantType.String, 0, '')],\r\n 'Methods': [('Remove', 'RemoveProduct', [], [ua.VariantType.Boolean])],\r\n 'Folders': []}\r\n\r\n'''\r\nBaseTypes['resource'] = {'Class': 'ObjectType',\r\n 'Variables': [],\r\n 'Properties': [('filename', ua.uatypes.VariantType.String, 0, ''),\r\n ('mime', ua.uatypes.VariantType.String, 0, '')],\r\n 'Methods': [('Read', 'GetResource', [ua.VariantType.String], [ua.VariantType.ByteString]),\r\n ('Write', 'WriteResource', [ua.VariantType.String, ua.VariantType.ByteString], [ua.VariantType.Boolean])],\r\n 'Folders': []}\r\n\r\nBaseTypes['system'] = {'Class': 'ObjectType',\r\n 'Variables': [('frame', ua.uatypes.VariantType.Float, 7, [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0])],\r\n 'Properties': [],\r\n 'Methods': [('Remove', 'RemoveSystem', [ua.VariantType.String], [ua.VariantType.Boolean]),\r\n ('AddNewAssembly', 'AddNewAssembly', [ua.VariantType.String, ua.VariantType.String], [ua.VariantType.Boolean])],\r\n 'Folders': ['resources']}\r\n\r\nBaseTypes['assembly'] = {'Class': 'ObjectType',\r\n 'Variables': [('frame', ua.uatypes.VariantType.Float, 7, [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0])],\r\n 'Properties': [],\r\n 'Methods': [('Remove', 'RemoveAssembly', [ua.VariantType.String], [ua.VariantType.Boolean]),\r\n ('AddNewComponent', 'AddNewComponent', [ua.VariantType.String, ua.VariantType.String, ua.VariantType.String], [ua.VariantType.Boolean]),\r\n ('AddNewSignalConnection', 'AddNewSignalConnection', [ua.VariantType.String, ua.VariantType.String, ua.VariantType.String, ua.VariantType.String], [ua.VariantType.Boolean])],\r\n 'Folders': []}\r\n\r\nBaseTypes['component'] = {'Class': 'ObjectType',\r\n 'Variables': [('frame', ua.uatypes.VariantType.Float, 7, [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0])],\r\n 'Properties': [('base_body', ua.uatypes.VariantType.String, 0, ''),\r\n ('static', ua.uatypes.VariantType.Boolean, 0, True)],\r\n 'Methods': [('Remove', 'RemoveComponent', [ua.VariantType.String], [ua.VariantType.Boolean])],\r\n 'Folders': ['resources']}\r\n\r\nBaseTypes['metadata'] = {'Class': 'ObjectType',\r\n 'Variables': [],\r\n 'Properties': [('name', ua.uatypes.VariantType.String, 0, ''),\r\n ('version', ua.uatypes.VariantType.String, 0, ''),\r\n ('owner', ua.uatypes.VariantType.String, 0, ''),\r\n ('manufacturer', ua.uatypes.VariantType.String, 0, ''),\r\n ('model', ua.uatypes.VariantType.String, 0, ''),\r\n ('eCl@ss', ua.uatypes.VariantType.String, 0, ''),\r\n ('description', ua.uatypes.VariantType.String, 0, ''),\r\n ('key_words', ua.uatypes.VariantType.String, 0, ''),\r\n ('thumbnail', ua.uatypes.VariantType.String, 0, '')],\r\n 'Methods': [],\r\n 'Folders': []}\r\n\r\n\r\nBaseTypes['signal_connection']= {'Class': 'VariableType',\r\n 'Variables': [],\r\n 'Properties': [('from', ua.uatypes.VariantType.String, 0, ''),\r\n ('to', ua.uatypes.VariantType.String, 10, ['','','','','','','','','',''])],\r\n 'Methods': [('Remove', 'RemoveSignalConnection', [ua.VariantType.String], [ua.VariantType.Boolean])],\r\n 'Folders': []}\r\n\r\n# General: State Machines\r\nBaseTypes['state_machine'] = {'Class': 'VariableType',\r\n 'Variables': [('current_state', ua.uatypes.VariantType.String, 0, '')],\r\n 'Properties': [],\r\n 'Methods': [],\r\n 'Folders': []}\r\n\r\nBaseTypes['state'] = {'Class': 'VariableType',\r\n 'Variables': [('initial', ua.uatypes.VariantType.Boolean, 0, False)],\r\n 'Properties': [],\r\n 'Methods': [],\r\n 'Folders': []}\r\n\r\nBaseTypes['action'] = {'Class': 'VariableType',\r\n 'Variables': [],\r\n 'Properties': [('qualifier', ua.uatypes.VariantType.String, 0, ''),\r\n ('variable', ua.uatypes.VariantType.String, 0, ''),\r\n ('value', ua.uatypes.VariantType.String, 0, '')],\r\n 'Methods': [],\r\n 'Folders': []}\r\n\r\nBaseTypes['transition'] = {'Class': 'VariableType',\r\n 'Variables': [],\r\n 'Properties': [('to', ua.uatypes.VariantType.String, 0, ''),\r\n ('statement', ua.uatypes.VariantType.String, 0, '')],\r\n 'Methods': [],\r\n 'Folders': []}\r\n\r\n# Visualization: Symbol\r\nBaseTypes['symbol'] = {'Class': 'VariableType',\r\n 'Variables': [],\r\n 'Properties': [('resource', ua.uatypes.VariantType.String, 0, '')],\r\n 'Methods': [],\r\n 'Folders': []}\r\n\r\n# Visualization: Geometry\r\nBaseTypes['geometry'] = {'Class': 'VariableType',\r\n 'Variables': [],\r\n 'Properties': [('frame', ua.uatypes.VariantType.Float, 7, [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]),\r\n ('resource', ua.uatypes.VariantType.String, 0, ''),\r\n ('scale', ua.uatypes.VariantType.Float, 3, [1.0, 1.0, 1.0]),\r\n ('color', ua.uatypes.VariantType.Float, 4, [1.0, 1.0, 1.0, 1.0]),\r\n ('left_mouse', ua.uatypes.VariantType.Boolean, 0, False),\r\n ('right_mouse', ua.uatypes.VariantType.Boolean, 0, False)],\r\n 'Methods': [],\r\n 'Folders': []}\r\n\r\n# Visualization: Lights\r\nBaseTypes['light'] = {'Class': 'VariableType',\r\n 'Variables': [('color', ua.uatypes.VariantType.Float, 4, [1.0, 1.0, 1.0, 1.0]),\r\n ('active', ua.uatypes.VariantType.Boolean, 0, False)],\r\n 'Properties': [('frame', ua.uatypes.VariantType.Float, 7, [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]),\r\n ('attenuation', ua.uatypes.VariantType.Float, 0, 0.0),\r\n ('light_type', ua.uatypes.VariantType.String, 0, 'Point')],\r\n 'Methods': [],\r\n 'Folders': []}\r\n\r\n\r\n# Physics: Body\r\nBaseTypes['rigid_body'] = {'Class': 'VariableType',\r\n 'Variables': [('frame', ua.uatypes.VariantType.Float, 7, [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0])],\r\n 'Properties': [('mass', ua.uatypes.VariantType.Float, 7, [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0])],\r\n 'Methods': [],\r\n 'Folders': []}\r\n\r\n# Physics: Collision Shapes\r\nBaseTypes['box_shape'] = {'Class': 'VariableType',\r\n 'Variables': [('visible', ua.uatypes.VariantType.Boolean, 0, False)],\r\n 'Properties': [('frame', ua.uatypes.VariantType.Float, 7, [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]),\r\n ('size', ua.uatypes.VariantType.Float, 3, [1.0, 1.0, 1.0])],\r\n 'Methods': [],\r\n 'Folders': []}\r\n\r\nBaseTypes['custom_shape'] = {'Class': 'VariableType',\r\n 'Variables': [('visible', ua.uatypes.VariantType.Boolean, 0, False)],\r\n 'Properties': [('frame', ua.uatypes.VariantType.Float, 7, [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]),\r\n ('resource', ua.uatypes.VariantType.String, 0, ''),\r\n ('scale', ua.uatypes.VariantType.Float, 3, [1.0, 1.0, 1.0])],\r\n 'Methods': [],\r\n 'Folders': []}\r\n\r\n# Physics: Materials\r\n\r\n# Physics: Materials\r\n\r\n# Physics: Sensors\r\n\r\n# Physics: Joints\r\n\r\n# Behavior: FMI\r\nBaseTypes['fmi_behavior'] = {'Class': 'VariableType',\r\n 'Variables': [],\r\n 'Properties': [('resource', ua.uatypes.VariantType.String, 0, ''),\r\n ('step_time', ua.uatypes.VariantType.Float, 0, 0.001)],\r\n 'Methods': [],\r\n 'Folders': []}\r\n\r\nBaseTypes['fmi_port'] = {'Class': 'VariableType',\r\n 'Variables': [],\r\n 'Properties': [('connected_to', ua.uatypes.VariantType.String, 0, ''),\r\n ('port_type', ua.uatypes.VariantType.String, 0, 'input')],\r\n 'Methods': [],\r\n 'Folders': []}\r\n\r\n\r\n# Behavior: Signal ports\r\nBaseTypes['electric_port'] = {'Class': 'VariableType',\r\n 'Variables': [('voltage', ua.uatypes.VariantType.Float, 0, 0.0),\r\n ('current', ua.uatypes.VariantType.Float, 0, 0.0)],\r\n 'Properties': [('frame', ua.uatypes.VariantType.Float, 7, [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]),\r\n ('signal_type', ua.uatypes.VariantType.String, 0, '')],\r\n 'Methods': [],\r\n 'Folders': []}\r\n\r\nBaseTypes['pneumatic_port'] = {'Class': 'VariableType',\r\n 'Variables': [('pressure', ua.uatypes.VariantType.Float, 0, 0.0),\r\n ('flow', ua.uatypes.VariantType.Float, 0, 0.0)],\r\n 'Properties': [('frame', ua.uatypes.VariantType.Float, 7, [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]),\r\n ('signal_type', ua.uatypes.VariantType.String, 0, '')],\r\n 'Methods': [],\r\n 'Folders': []}\r\n\r\nBaseTypes['hydraulic_port'] = {'Class': 'VariableType',\r\n 'Variables': [('pressure', ua.uatypes.VariantType.Float, 0, 0.0),\r\n ('flow', ua.uatypes.VariantType.Float, 0, 0.0)],\r\n 'Properties': [('frame', ua.uatypes.VariantType.Float, 7, [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]),\r\n ('signal_type', ua.uatypes.VariantType.String, 0, '')],\r\n 'Methods': [],\r\n 'Folders': []}\r\n\r\n# Behavior: Internal connection\r\nBaseTypes['int_port_connection']= {'Class': 'VariableType',\r\n 'Variables': [('active', ua.uatypes.VariantType.Boolean, 0, False)],\r\n 'Properties': [('from', ua.uatypes.VariantType.String, 0, ''),\r\n ('to', ua.uatypes.VariantType.String, 0, '')],\r\n 'Methods': [],\r\n 'Folders': []}\r\n\r\n# Communication: Ports\r\n\r\n\r\n'''\r\n# Server connections\r\nBaseTypes['server_status'] = {'Class': 'ObjectType',\r\n 'Variables': [],\r\n 'Properties': [],\r\n 'Methods': [],\r\n 'Folders': []}\r\n\r\nBaseTypes['conn_list'] = {'Class': 'ObjectType',\r\n 'Variables': [],\r\n 'Properties': [],\r\n 'Methods': [('AddNewServerConnection', 'AddNewServerConnection', [ua.VariantType.String], [ua.VariantType.NodeId]),\r\n ('RemoveServerConnection', 'RemoveServerConnection', [ua.VariantType.String], [ua.VariantType.Boolean])],\r\n 'Folders': []}\r\n\r\nBaseTypes['server_con'] = {'Class': 'VariableType',\r\n 'Variables': [('Update Rate', ua.uatypes.VariantType.Float, 0, 0.0),\r\n ('Status', ua.uatypes.VariantType.String, 0, '')],\r\n 'Properties': [('IP', ua.uatypes.VariantType.String, 0, '')],\r\n 'Methods': [],\r\n 'Folders': []}\r\n'''\r\n\r\n# -----------------------------------------------------------------------------\r\nclass client_session(object):\r\n ''' Class to handle client sessions.'''\r\n \r\n def __init__(self, username, password):\r\n ''' Constructor.'''\r\n self.username = username\r\n self.password = password\r\n self.birthdate = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\r\n self.expires = 0 # TODO\r\n self.domain = 'https://cloud.simumatik.com'\r\n # Create client and try to login\r\n self.client = RestClient(self.domain, self.username, self.password)\r\n # Try to login\r\n self.client.get_hello_for_authorized_user()\r\n # Generate session id\r\n c = hashlib.sha256()\r\n c.update(self.username.encode('utf-8'))\r\n c.update(self.password.encode('utf-8'))\r\n c.update(self.birthdate.encode('utf-8'))\r\n self.sessionid = c.hexdigest()\r\n \r\n def close(self):\r\n ''' Close and cleanup.'''\r\n self.client = None\r\n\r\n\r\n# -----------------------------------------------------------------------------\r\nclass open_emulation_platform(Thread):\r\n \r\n engine_list = {'Behavior':oep_behavior_engine,\r\n 'Physics':oep_physics_engine}\r\n \r\n def __init__(self, ip, port):\r\n '''Constructor.'''\r\n # Inherit\r\n Thread.__init__(self, name='open_emulation_platform')\r\n # Get logger\r\n self._logger = logging.getLogger(__name__)\r\n # Initialize\r\n self._ip = ip\r\n self._port = port\r\n self._running = True\r\n self._server = None\r\n self._engines = {}\r\n self._client_sessions = {}\r\n self._cache = {}\r\n \r\n def stop_server(self):\r\n ''' Stop thread.'''\r\n self._running = False\r\n \r\n def initialize(self):\r\n ''' Initialize.'''\r\n try:\r\n # Create Server\r\n self._server = Server()\r\n self._server.set_endpoint(\"opc.tcp://{0}:{1}/server/\".format(self._ip, self._port))\r\n self._server.set_server_name('Open Emulation Platform')\r\n # Register namespace\r\n self._namespace_index = self._server.register_namespace('OpenEmulationPlatform')\r\n #uri = \"http://openemulationplatform.opcua.io\"\r\n self._server.allow_remote_admin(True)\r\n self._server.start()\r\n \r\n except Exception as e:\r\n if DEBUG_MODE: self._logger.error(msg='OPCUA Server launch error: {0}'.format(str(e)))\r\n self._server = None\r\n \r\n def setup(self):\r\n ''' Setup.'''\r\n # Setup File system\r\n pathlib.Path('cache/systems').mkdir(parents=True, exist_ok=True)\r\n pathlib.Path('cache/components').mkdir(parents=True, exist_ok=True)\r\n pathlib.Path('cache/resources').mkdir(parents=True, exist_ok=True)\r\n # Setup server if OK\r\n if self._server is not None:\r\n # Format server\r\n self.format_server()\r\n # Start engines\r\n for name, cls in self.engine_list.items():\r\n p_pipe, c_pipe = Pipe()\r\n engine = Process(target=cls, name='OEP_{0}_engine'.format(name), args=(c_pipe,))\r\n engine.start()\r\n self._engines[name] = (engine, p_pipe)\r\n if DEBUG_MODE: self._logger.error(msg='{0} engine launched.'.format(name))\r\n \r\n def run_loop(self):\r\n ''' Thread running loop.'''\r\n # Check engine pipes\r\n for name, (engine, pipe) in self._engines.items():\r\n # Check pipe\r\n while(pipe.poll()): \r\n # Process message\r\n (msg, data) = pipe.recv()\r\n # Status change\r\n if msg == 'status':\r\n pass\r\n #if DEBUG_MODE: self._logger.error(msg='{0} engine status changed: {1}'.format(name, data))\r\n elif msg == 'config':\r\n pass\r\n elif msg =='value_changes':\r\n pass\r\n\r\n def cleanup(self):\r\n ''' Thread cleanup.'''\r\n # Clean client sessions\r\n while self._client_sessions:\r\n (session_id, client) = self._client_sessions.popitem()\r\n client.close()\r\n \r\n # Close engines\r\n while self._engines:\r\n name, (engine, pipe) = self._engines.popitem()\r\n # Send close msg\r\n pipe.send(('close',None))\r\n # Join\r\n engine.join()\r\n # log\r\n if DEBUG_MODE: self._logger.error(msg='{0} engine destroyed.'.format(name))\r\n \r\n # Close Server\r\n if self._server:\r\n self._server.stop()\r\n self._server = None\r\n\r\n def run(self):\r\n ''' Thread loop.'''\r\n # Initialize\r\n self.initialize()\r\n \r\n # Setup\r\n self.setup()\r\n \r\n # Load cache\r\n self.LoadCache()\r\n \r\n # Running loop\r\n while self._running:\r\n # Main loop\r\n self.run_loop()\r\n # Sleep\r\n time.sleep(1e-3)\r\n \r\n # Clean up\r\n self.cleanup()\r\n\r\n def format_server(self):\r\n \"\"\" Format Server according OEP structure.\"\"\"\r\n # Add Main Object\r\n root = self._server.get_root_node()#get_server_node()\r\n self._root = root.add_object(self._namespace_index, 'OpenEmulationPlatform')\r\n self._root.add_method(self._namespace_index, 'Login', self.Login, [ua.VariantType.String, ua.VariantType.String], [ua.VariantType.String])\r\n self._root.add_method(self._namespace_index, 'Logout', self.Logout, [ua.VariantType.String], [ua.VariantType.Boolean])\r\n\r\n # Library folder\r\n self._library = self._root.add_object(self._namespace_index, 'Library')\r\n # Create base library\r\n self._baselib = self._library.add_object(self._namespace_index, 'Base')\r\n \r\n # Add base types\r\n for type_name, info in BaseTypes.items():\r\n # Create Base type\r\n self.CreateNewTypeClass(self._baselib, type_name, info)\r\n \r\n # Create library folders\r\n self._syslib = self._library.add_object(self._namespace_index, 'Systems')\r\n self._complib = self._library.add_object(self._namespace_index, 'Components')\r\n self._complib.add_method(self._namespace_index, 'CreateNewComponent', self.CreateNewComponent, [ua.VariantType.String], [ua.VariantType.String])\r\n self._complib.add_method(self._namespace_index, 'SearchComponent', self.SearchComponent, [ua.VariantType.String, ua.VariantType.String], [ua.VariantType.String])\r\n self._reslib = self._library.add_object(self._namespace_index, 'Resources')\r\n \r\n '''\r\n # Status Object\r\n self._status = self.CreateObjectInstance(self._root, 'Status', 'server_status')\r\n self._connections = self.CreateObjectInstance(self._status, 'Connections', 'conn_list')\r\n '''\r\n \r\n # Create Workspace\r\n self._workspace = self.CreateObjectInstance(self._root, 'Workspace', 'workspace')\r\n '''\r\n self._products = self.CreateObjectInstance(self._workspace, 'Products', 'products')\r\n '''\r\n # Events\r\n custom_etype = self._server.nodes.base_event_type.add_object_type(self._namespace_index, 'OEPCustomEvent')\r\n custom_etype.add_property(self._namespace_index, 'EventNodeId', ua.Variant(0, ua.VariantType.NodeId))\r\n self._myevgen = self._server.get_event_generator(custom_etype, self._root)\r\n \r\n #---------------------------------------------------------------------------\r\n # General Platform methods\r\n @uamethod\r\n def Login(self, parent:ua.VariantType.NodeId, username:str, password:str) -> str:\r\n \"\"\" Logs in in the cloud with the given username and password and returns a session id if success.\r\n :param parent: Parent nodeid\r\n :param username: User name\r\n :param password: User password\r\n :returns: Session Id\r\n \"\"\"\r\n # Try to login\r\n if DEBUG_MODE: self._logger.error(msg=\"Trying to login: {0} - {1}\".format(username, password))\r\n try:\r\n session = client_session(username, password)\r\n if DEBUG_MODE: self._logger.error(msg=\"Login successful.\")\r\n except Exception as e:\r\n if DEBUG_MODE: self._logger.error(msg=\"Login failed:{0}\".format(str(e)))\r\n return ''\r\n # Save session\r\n self._client_sessions[session.sessionid] = session\r\n # Return\r\n return session.sessionid\r\n\r\n @uamethod\r\n def Logout(self, parent:ua.VariantType.NodeId, session_id:str) -> bool:\r\n \"\"\" Logout the user giving the session id.\r\n :param parent: Parent nodeid\r\n :param session_id: User session Id\r\n :returns: Logout successful\r\n \"\"\"\r\n # Check session id\r\n if session_id is not None:\r\n if session_id in self._client_sessions:\r\n # Remove session\r\n c = self._client_sessions.pop(session_id)\r\n c.close()\r\n # Log\r\n if DEBUG_MODE: self._logger.error(msg='User logout: {0}'.format(c.username))\r\n # Return Success\r\n return True\r\n # Return failed\r\n return False\r\n \r\n def checkSessionId(self, session_id):\r\n \"\"\" Checks if given cookie is valid (return True) or not (return False)\"\"\"\r\n if session_id is not None:\r\n if session_id in self._client_sessions:\r\n return True\r\n return False\r\n\r\n #---------------------------------------------------------------------------\r\n # Cache\r\n def LoadCache(self):\r\n \"\"\" Load local cache.\"\"\"\r\n try:\r\n # Load Components\r\n for guid in next(os.walk('cache/components/'))[1]:\r\n obj = self.LoadComponentFromCache(guid)\r\n if obj: self._cache[guid] = obj\r\n # Load systems\r\n for guid in next(os.walk('cache/systems/'))[1]:\r\n obj = self.LoadSystemFromCache(guid)\r\n if obj: self._cache[guid] = obj\r\n except Exception as e:\r\n if DEBUG_MODE: self._logger.error(msg=\"Error while loading cache:{0}\".format(str(e)))\r\n\r\n def LoadResourceFromCache(self, resource_path, resource_guid):\r\n \"\"\" Load Resource into server.\"\"\"\r\n res_file = None\r\n try:\r\n # Get File in path\r\n path = '{0}/{1}'.format(resource_path, resource_guid)\r\n onlyfiles = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]\r\n if onlyfiles:\r\n res_file = onlyfiles[0]\r\n\r\n except Exception as e:\r\n if DEBUG_MODE: self._logger.error(msg=\"Error while loading resource {0} from cache:{1}\".format(resource_guid, str(e)))\r\n return None\r\n \r\n # Check file\r\n if res_file is not None:\r\n # Create new ObjectType class based on 'component' \r\n res_node = self.CreateObjectInstance(self._reslib, resource_guid, 'resource')\r\n # Set filename property\r\n pnode = res_node.get_child('{}:{}'.format(self._namespace_index, 'filename'))\r\n pnode.set_value(ua_utils.string_to_val(res_file, ua.VariantType.String))\r\n # Set mime property\r\n pnode = res_node.get_child('{}:{}'.format(self._namespace_index, 'mime'))\r\n pnode.set_value(ua_utils.string_to_val(res_file, ua.VariantType.String))\r\n # Log\r\n if DEBUG_MODE: self._logger.error(msg=\"Resource loaded from cache: {0}\".format(resource_guid))\r\n # Return\r\n return res_node\r\n\r\n def LoadComponentFromCache(self, component_guid:str):\r\n \"\"\" Load Component from cahce into server.\"\"\"\r\n comp_xml = None\r\n try:\r\n # Parse the given XML file:\r\n tree = ElementTree.parse('cache/components/{0}/component.xml'.format(component_guid))\r\n comp_xml = tree.getroot().find('component')\r\n except Exception as e:\r\n if DEBUG_MODE: self._logger.error(msg=\"Error while loading component {0} from cache:{1}\".format(component_guid, str(e)))\r\n return None\r\n \r\n # Check Xml\r\n if comp_xml is not None:\r\n # Create new ObjectType class based on 'component' \r\n comp_node = self.CreateNewTypeClass(self._complib, component_guid, BaseTypes['component'])\r\n # Load children nodes\r\n for xml_child in comp_xml:\r\n # first Properties and Variables\r\n if xml_child.tag in ['property','variable']:\r\n # Check if node exists\r\n try:\r\n child_node = comp_node.get_child('{}:{}'.format(self._namespace_index, xml_child.get('name')))\r\n value = ua_utils.string_to_val(xml_child.text, child_node.get_data_type_as_variant_type())\r\n child_node.set_value(value)\r\n except:\r\n # New property\r\n if xml_child.tag == 'property':\r\n child_node = comp_node.add_property(self._namespace_index, xml_child.get('name'), ast.literal_eval(xml_child.text))\r\n child_node.set_writable() \r\n # new variable\r\n else:\r\n child_node = comp_node.add_variable(self._namespace_index, xml_child.get('name'), ast.literal_eval(xml_child.text))\r\n child_node.set_writable() \r\n \r\n # Import Children\r\n else:\r\n self.AddObjectInstanceFromXml(comp_node, xml_child)\r\n # Log\r\n if DEBUG_MODE: self._logger.error(msg=\"Component loaded from cache: {0}\".format(component_guid))\r\n # Return\r\n return comp_node\r\n\r\n def SaveComponentToCache(self, component_guid:str) -> bool:\r\n \"\"\" Save Component to cache xml file.\r\n :param component_guid: Component guid\r\n :returns: Save successful\r\n \"\"\"\r\n #xml_type = XML(xml_string)\r\n pass\r\n \r\n def LoadSystemFromCache(self, system_guid:str):\r\n \"\"\" Load System into server.\"\"\"\r\n sys_xml = None\r\n try:\r\n # Parse the given XML file:\r\n tree = ElementTree.parse('cache/systems/{0}/system.xml'.format(sys_xml))\r\n sys_xml = tree.getroot().find('systems')\r\n except Exception as e:\r\n if DEBUG_MODE: self._logger.error(msg=\"Error while loading system {0} from cache:{1}\".format(system_guid, str(e)))\r\n return None\r\n \r\n # Check Xml\r\n if sys_xml is not None:\r\n # Create new ObjectType class based on 'component' \r\n sys_node = self.CreateObjectInstance(self._syslib, system_guid, 'system')\r\n # Import metadata node\r\n if sys_node:\r\n self.AddObjectInstanceFromXml(sys_node, sys_xml.find('metadata'), recursive=False)\r\n # Log\r\n if DEBUG_MODE: self._logger.error(msg=\"System loaded from cache: {0}\".format(system_guid))\r\n # Return\r\n return sys_node\r\n\r\n def SaveSystemToCache(self, system_guid:str):\r\n \"\"\" Save System to cache xml file.\"\"\"\r\n # TODO:\r\n pass\r\n \r\n\r\n #---------------------------------------------------------------------------\r\n # Library\r\n @uamethod\r\n def CreateNewComponent(self, library:ua.VariantType.NodeId, session_id:str) -> str:\r\n \"\"\" Creates a new component .\r\n :param library: Library nodeid\r\n :param session_id: User session Id\r\n :returns: component_guid: Component Guid\r\n \"\"\"\r\n # Check session id\r\n if session_id is not None:\r\n if session_id in self._client_sessions:\r\n # Get client\r\n c = self._client_sessions[session_id]\r\n # Create new component\r\n new_comp = c.client.create_component(name='', description='')\r\n # Check component info\r\n if 'id' in new_comp:\r\n # Get guid\r\n component_guid = new_comp['id']\r\n # Create new folder\r\n directory = 'cache/components/{0}'.format(component_guid)\r\n if not os.path.exists(directory):\r\n os.makedirs(directory) \r\n # Copy component template\r\n shutil.copy2('templates/component.xml', directory) \r\n try:\r\n # Parse the given XML file:\r\n tree = ElementTree.parse('{0}/component.xml'.format(directory))\r\n tree.getroot().find('component').set('guid', component_guid)\r\n tree.write('{0}/component.xml'.format(directory))\r\n except Exception as e:\r\n if DEBUG_MODE: self._logger.error(msg=\"Error while modifying component template: {0}\".format(e))\r\n return None\r\n # Create resource folder\r\n directory = '{0}/resources'.format(directory)\r\n if not os.path.exists(directory):\r\n os.makedirs(directory) \r\n # Load component\r\n comp_node = self.LoadComponentFromCache(component_guid) \r\n # Update dictionary\r\n self._cache[component_guid] = comp_node \r\n # return\r\n return new_comp['id']\r\n # If failed\r\n return None\r\n\r\n @uamethod\r\n def SyncComponent(self, library:ua.VariantType.NodeId, session_id:str, component_guid:str) -> bool:\r\n \"\"\" Syncs the given component to the cloud.\r\n :param library: Library nodeid\r\n :param session_id: User session Id\r\n :param component_guid: Component Guid\r\n :returns: Result\r\n \"\"\"\r\n # Check session id\r\n if session_id is not None:\r\n if session_id in self._client_sessions:\r\n # Get client\r\n c = self._client_sessions[session_id]\r\n # Save component to xml\r\n # TODO: \r\n # Create new component\r\n res = c.client.upload_component_file(id=component_guid, file='cache/components/{0}/component.xml'.format(component_guid))\r\n print(res)\r\n return True\r\n # If failed\r\n return False\r\n\r\n @uamethod\r\n def RemoveComponent(self, library:ua.VariantType.NodeId, session_id:str, component_guid:str) -> bool:\r\n \"\"\" Removes the given component from the cloud, the cache and the server.\r\n :param library: Library nodeid\r\n :param session_id: User session Id\r\n :param component_guid: Component Guid\r\n :returns: Result\r\n \"\"\"\r\n # TODO: \r\n # Check session id\r\n if session_id is not None:\r\n if session_id in self._client_sessions:\r\n # Get client\r\n c = self._client_sessions[session_id]\r\n # TODO\r\n @uamethod\r\n def SearchComponent(self, library, session_id, filter='{}') -> str:\r\n \"\"\" Search for a given component from the cloud using the filter.\r\n :param library: Library nodeid\r\n :param session_id: User session Id\r\n :param filter: Component filter, a dictionary including the filter attributes converted to a string\r\n :returns: Result, is a dictionary with information of all search results converted to a string\r\n \"\"\"\r\n # Check session id\r\n if session_id is not None:\r\n if session_id in self._client_sessions:\r\n # Get client\r\n c = self._client_sessions[session_id]\r\n res = c.client.get_components()\r\n return json.dumps(res)\r\n return ''\r\n \r\n @uamethod\r\n def DownloadComponent(self, library, session_id, component_guid) -> bool:\r\n \"\"\" Downloads the given component from the cloud to the cache.\r\n :param library: Library nodeid\r\n :param session_id: User session Id\r\n :param component_guid: Component Guid\r\n :returns: Result, True if success\r\n \"\"\"\r\n # TODO: \r\n pass\r\n\r\n @uamethod\r\n def SearchSystem(self, library, session_id, filter='{}'):\r\n \"\"\" Search for a given system from the cloud using the filter.\r\n :param library: Library nodeid\r\n :type library: ua.VariantType.NodeId\r\n \r\n :param session_id: User session Id\r\n :type session_id: ua.VariantType.String\r\n \r\n :param filter: System filter\r\n :type filter: ua.VariantType.String\r\n \r\n :returns: ua.VariantType.Boolean -- Result\r\n \"\"\"\r\n res = {}\r\n # Check session id\r\n if session_id is not None:\r\n if session_id in self._client_sessions:\r\n # Get client\r\n c = self._client_sessions[session_id]\r\n \r\n # \r\n return json.dumps(c.get_projects())\r\n # TODO: \r\n return json.dumps(res)\r\n \r\n @uamethod\r\n def DownloadSystem(self, library, session_id, system_guid):\r\n \"\"\" Downloads the given system from the cloud to the cache.\r\n :param library: Library nodeid\r\n :type library: ua.VariantType.NodeId\r\n \r\n :param session_id: User session Id\r\n :type session_id: ua.VariantType.String\r\n \r\n :param system_guid: System Guid\r\n :type system_guid: ua.VariantType.String\r\n \r\n :returns: ua.VariantType.Boolean -- Result\r\n \"\"\"\r\n # TODO: \r\n pass\r\n \r\n #---------------------------------------------------------------------------\r\n # Resource\r\n @uamethod\r\n def GetResource(self, resource, session_id):\r\n \"\"\" Opens the given system object.\r\n :param resource: Resource nodeid\r\n :type resource: ua.VariantType.NodeId\r\n \r\n :param session_id: User session Id\r\n :type session_id: ua.VariantType.String\r\n \r\n :returns: ua.VariantType.ByteString -- Resource\r\n \"\"\"\r\n if self.checkSessionId(session_id):\r\n pass\r\n \r\n def WriteResource(self, resource, session_id, data):\r\n \"\"\" Opens the given system object.\r\n :param resource: Resource nodeid\r\n :type resource: ua.VariantType.NodeId\r\n \r\n :param session_id: User session Id\r\n :type session_id: ua.VariantType.String\r\n \r\n :returns: ua.VariantType.ByteString -- Resource\r\n \"\"\"\r\n if self.checkSessionId(session_id):\r\n pass\r\n \r\n\r\n #---------------------------------------------------------------------------\r\n # Workspace\r\n @uamethod\r\n def LoadSystem(self, workspace, session_id, system_guid):\r\n \"\"\" Opens the given system object.\r\n :param workspace: Workspace nodeid\r\n :type workspace: ua.VariantType.NodeId\r\n \r\n :param session_id: User session Id\r\n :type session_id: ua.VariantType.String\r\n \r\n :param system_guid: System Guid\r\n :type system_guid: ua.VariantType.String\r\n \r\n :returns: ua.VariantType.NodeId -- System nodeid\r\n \"\"\"\r\n if self.checkSessionId(session_id):\r\n # Get parent\r\n parent_node = self._server.get_node(workspace)\r\n # TODO:\r\n '''\r\n assert type(xml_string) is str, 'xml_stringt argument must be a valid string object.'\r\n xml_element = XML(xml_string)\r\n system = self.AddObjectInstanceFromXml(parent_node, xml_element)\r\n self.TriggerCustomEvent('NewSystem', system.nodeid)\r\n return system.nodeid\r\n return self.AddNewObject(parent, system_id, 'system', 'NewSystem')\r\n '''\r\n return None\r\n # Open failed \r\n return None\r\n \r\n '''\r\n @uamethod\r\n def CreateProduct(self, parent, name, type_name):\r\n \"\"\" Creates an instance object of the given product type on the given parent and with the given name.\r\n :param parent: Parent nodeid\r\n :type parent: ua.VariantType.NodeId\r\n \r\n :param name: Product name\r\n :type name: ua.VariantType.String\r\n \r\n :param inherits: Inherits from User product type name\r\n :type inherits: ua.VariantType.String\r\n \r\n :returns: ua.VariantType.NodeId -- New Component nodeid\r\n \"\"\"\r\n assert type(parent) is ua.NodeId, 'parent argument must be a valid NodeId object.'\r\n assert type(name) is str, 'name argument must be a valid string object.'\r\n # Create new type instance\r\n parent_node = self._server.get_node(parent)\r\n new_product = self.CreateObjectInstance(parent_node, name, type_name)\r\n # Trigger event\r\n self.TriggerCustomEvent('NewProductAdded', new_product.nodeid)\r\n # Return \r\n return new_product.nodeid\r\n '''\r\n #---------------------------------------------------------------------------\r\n # System\r\n @uamethod\r\n def RemoveSystem(self, system, session_id):\r\n \"\"\" Removes the selected system.\r\n :param system: System nodeid\r\n :type system: ua.VariantType.NodeId\r\n \r\n :param session_id: User session Id\r\n :type session_id: ua.VariantType.String\r\n \r\n :returns: ua.VariantType.Boolean -- System removed\r\n \"\"\"\r\n # TODO:\r\n #return self.RemoveObject(parent, name, 'SystemRemoved')\r\n return True\r\n\r\n @uamethod\r\n def SyncSystem(self, system, session_id):\r\n \"\"\" Sync system to the cloud.\r\n :param system: System nodeid\r\n :type system: ua.VariantType.NodeId\r\n \r\n :param session_id: User session Id\r\n :type session_id: ua.VariantType.String\r\n \r\n :returns: ua.VariantType.Boolean -- System synchronized\r\n \"\"\"\r\n # Parse file\r\n # TODO: \r\n pass\r\n \r\n @uamethod\r\n def AddNewAssembly(self, system, session_id, name):\r\n \"\"\" Adds new assembly object.\r\n :param system: System nodeid\r\n :type system: ua.VariantType.NodeId\r\n \r\n :param session_id: User session Id\r\n :type session_id: ua.VariantType.String\r\n \r\n :param name: Assembly name\r\n :type name: ua.VariantType.String\r\n \r\n :returns: ua.VariantType.NodeId -- Assembly nodeid\r\n \"\"\"\r\n return self.AddNewObject(system, name, 'assembly', 'NewAssembly')\r\n \r\n #---------------------------------------------------------------------------\r\n # Assembly\r\n @uamethod\r\n def RemoveAssembly(self, assembly, session_id):\r\n \"\"\" Removes assembly object with given name.\r\n :param assembly: Assembly nodeid\r\n :type assembly: ua.VariantType.NodeId\r\n \r\n :param session_id: User session Id\r\n :type session_id: ua.VariantType.String\r\n \r\n :returns: ua.VariantType.Boolean -- System removed\r\n \"\"\"\r\n return #self.RemoveObject(assembly, name, 'AssemblyRemoved')\r\n\r\n @uamethod\r\n def AddNewComponent(self, assembly, session_id, name, component_guid):\r\n \"\"\" Adds new component object.\r\n :param assembly: Assembly nodeid\r\n :type assembly: ua.VariantType.NodeId\r\n \r\n :param session_id: User session Id\r\n :type session_id: ua.VariantType.String\r\n \r\n :param name: Component name\r\n :type name: ua.VariantType.String\r\n \r\n :param component_guid: Component Guid\r\n :type component_guid: ua.VariantType.String\r\n \r\n :returns: ua.VariantType.NodeId -- Component nodeid\r\n \"\"\"\r\n return self.AddNewObject(assembly, name, component_guid, 'NewComponent')\r\n \r\n @uamethod\r\n def AddNewSignalConnection(self, assembly, session_id, name, from_port, to_port):\r\n \"\"\" Adds new signal connection object.\r\n :param assembly: Assembly nodeid\r\n :type assembly: ua.VariantType.NodeId\r\n \r\n :param session_id: User session Id\r\n :type session_id: ua.VariantType.String\r\n \r\n :param name: Signal Connection name\r\n :type name: ua.VariantType.String\r\n \r\n :param from_port: Signal From port\r\n :type from_port: ua.VariantType.String\r\n \r\n :param to_port: Signal To port\r\n :type to_port: ua.VariantType.String\r\n \r\n :returns: ua.VariantType.NodeId -- Component nodeid\r\n \"\"\"\r\n connection_id = self.AddNewObject(assembly, name, 'signal_connection', 'NewSignalConnection')\r\n connection_node = self._server.get_node(connection_id)\r\n from_node = connection_node.get_child('{}:{}'.format(self._namespace_index, 'From'))\r\n from_node.set_value(from_port)\r\n to_node = connection_node.get_child('{}:{}'.format(self._namespace_index, 'To'))\r\n to_node.set_value(to_port)\r\n return connection_id\r\n \r\n #---------------------------------------------------------------------------\r\n # Component\r\n @uamethod\r\n def RemoveComponent(self, component, session_id):\r\n \"\"\" Removes component object with given name.\r\n :param component: Component nodeid\r\n :type component: ua.VariantType.NodeId\r\n \r\n :param session_id: User session Id\r\n :type session_id: ua.VariantType.String\r\n \r\n :returns: ua.VariantType.Boolean -- Component removed\r\n \"\"\"\r\n return #self.RemoveObject(parent, name, 'ComponentRemoved')\r\n\r\n\r\n #---------------------------------------------------------------------------\r\n # Signal Connection\r\n @uamethod\r\n def RemoveSignalConnection(self, connection, session_id):\r\n \"\"\" Removes signal connection object with given name.\r\n :param connection: Connection nodeid\r\n :type connection: ua.VariantType.NodeId\r\n \r\n :param session_id: User session Id\r\n :type session_id: ua.VariantType.String\r\n \r\n :returns: ua.VariantType.Boolean -- Component removed\r\n \"\"\"\r\n return #self.RemoveObject(parent, name, 'SignalConnectionRemoved')\r\n\r\n #---------------------------------------------------------------------------\r\n # Events\r\n def TriggerCustomEvent(self, message, nodeid):\r\n \"\"\" Triggers a new custom event.\r\n :param message: Event message\r\n :type message: String\r\n \r\n :param nodeid: Attached NodeId to event\r\n :type nodeid: ua.VariantType.NodeId\r\n \"\"\"\r\n self._myevgen.event.Message = ua.LocalizedText(message)\r\n self._myevgen.event.EventNodeId = nodeid\r\n self._myevgen.trigger()\r\n\r\n #---------------------------------------------------------------------------\r\n # Generic\r\n def CreateNewTypeClass(self, parent_node, name, info=None):\r\n \"\"\" Creates a object type class with the given name in the parent node. If provided info, inherits from the given base class.\r\n :param parent_node: Parent node\r\n :type parent_node: ua.Node\r\n \r\n :param name: User type name\r\n :type name: String\r\n \r\n :param inherits: Inherits from base type name\r\n :type inherits: Dict\r\n \r\n :returns: ua.Node -- New object type node\r\n \"\"\"\r\n assert type(name) is str and name is not '', 'type_name argument must be a valid and non empty string object.'\r\n # Create new object type class\r\n new_type = parent_node.add_object_type(self._namespace_index, name)\r\n # Inherit Children\r\n if info is not None:\r\n # Add Variables\r\n for (name, data_type, array_dimension, value) in info['Variables']:\r\n # TODO: Add data_type and dimension, ...\r\n var = new_type.add_variable(self._namespace_index, name, value, data_type)\r\n var.set_writable() \r\n # Add Properties\r\n for (name, data_type, array_dimension, value) in info['Properties']:\r\n # TODO: Add data_type and dimension, ...\r\n prop = new_type.add_property(self._namespace_index, name, value, data_type)\r\n prop.set_writable()\r\n # Add Methods\r\n for (name, method_name, input_args, output_args) in info['Methods']:\r\n method = new_type.add_method(self._namespace_index, name, getattr(self, method_name), input_args, output_args)\r\n # Add Folders\r\n for name in info['Folders']:\r\n folder = new_type.add_folder(self._namespace_index, name)\r\n\r\n # Return new type\r\n return new_type\r\n\r\n def GetObjectTypeFromName(self, type_name):\r\n \"\"\" Returns the node of the given object type class.\r\n :param type_name: Base type name\r\n :type type_name: String\r\n \r\n :returns: Node -- Base type node\r\n \"\"\"\r\n for child in self._baselib.get_children():\r\n if child.get_display_name().Text == type_name:\r\n return child\r\n for child in self._complib.get_children():\r\n if child.get_display_name().Text == type_name:\r\n return child\r\n return None\r\n\r\n def CreateObjectInstance(self, parent, name, type_name):\r\n \"\"\" Returns node of the created object.\r\n :param parent: Parent node\r\n :type parent: Node\r\n \r\n :param name: Object name\r\n :type name: String\r\n \r\n :param type_name: Base type name\r\n :type type_name: String\r\n\r\n :returns: Node -- Object node\r\n \"\"\"\r\n assert type(parent) is Node, 'parent argument must be a valid Node object.'\r\n assert type(name) is str and name is not '', 'name argument must be a valid and non empty string object.'\r\n objecttype = self.GetObjectTypeFromName(type_name)\r\n assert objecttype is not None, 'inherits argument must be a valid object type.'\r\n new_object = parent.add_object(self._namespace_index, name, objecttype=objecttype.nodeid)\r\n # Instantiate methods\r\n if type_name in BaseTypes:\r\n info = BaseTypes[type_name]\r\n for (mname, method_name, input_args, output_args) in info['Methods']:\r\n self._server.link_method(new_object.get_child('{}:{}'.format(self._namespace_index, mname)), getattr(self, method_name))\r\n # Return\r\n return new_object\r\n \r\n def AddObjectInstanceFromXml(self, parent, xml_element, recursive=True):\r\n \"\"\" Adds an object/variable instance to a node from a XML element.\r\n :param parent: Parent node\r\n :type parent: ua.Node\r\n \r\n :param xml_element: XML Element node\r\n :type xml_element: xml.etree.ElementTree.Element\r\n \"\"\"\r\n assert type(parent) is Node, 'parent argument must be a valid Node object.'\r\n try:\r\n # check if node is a reference\r\n type_name = xml_element.get('reference', xml_element.tag)\r\n # Create Instance\r\n new_instance = self.CreateObjectInstance(parent, xml_element.get('name'), type_name) \r\n # Get children\r\n for xml_child in xml_element:\r\n if xml_child.tag in ['property','variable']:\r\n child_node = new_instance.get_child('{}:{}'.format(self._namespace_index, xml_child.get('name')))\r\n value = ua_utils.string_to_val(xml_child.text, child_node.get_data_type_as_variant_type())\r\n child_node.set_value(value)\r\n # Import Children\r\n elif recursive:\r\n # Import Children\r\n self.AddObjectInstanceFromXml(new_instance, xml_child)\r\n # Return\r\n return new_instance\r\n \r\n except Exception as e:\r\n # Log\r\n if DEBUG_MODE: self._logger.error(msg=\"System while loading object instance from xml: {0}\".format(e))\r\n return None\r\n\r\n '''\r\n def AddNewObject(self, parent, name, objecttype, eventname):\r\n \"\"\" Adds new object.\r\n :param parent: Parent nodeid\r\n :type parent: ua.VariantType.NodeId\r\n \r\n :param name: Object name\r\n :type name: ua.VariantType.String\r\n \r\n :param name: ObjectType name\r\n :type name: ua.VariantType.String\r\n \r\n :param name: Triggered event name\r\n :type name: ua.VariantType.String\r\n \r\n :returns: ua.VariantType.NodeId -- Created objects nodeid\r\n \"\"\"\r\n assert type(parent) is ua.NodeId, 'parent argument must be a valid NodeId object.'\r\n assert type(name) is str and name is not '', 'name argument must be a valid and non empty string object.'\r\n assert type(objecttype) is str, 'objecttype argument must be a valid ObjectType string name.'\r\n assert type(eventname) is str, 'eventname argument must be a valid string value.'\r\n try:\r\n # Get parent node from nodeid\r\n parent_node = self._server.get_node(parent)\r\n # Create new object from given type\r\n new_object = self.CreateObjectInstance(parent_node, name, objecttype)\r\n # Trigger given event with the new object nodeid\r\n self.TriggerCustomEvent(eventname, new_object.nodeid)\r\n # Return new object nodeid\r\n return new_object.nodeid\r\n except:\r\n # Return None if failed\r\n return None\r\n\r\n def RemoveObject(self, parent, name, eventname):\r\n \"\"\" Removes the object with given name.\r\n :param parent: Parent nodeid\r\n :type parent: ua.VariantType.NodeId\r\n \r\n :param name: Object name\r\n :type name: ua.VariantType.String\r\n \r\n :param name: Triggered event name\r\n :type name: ua.VariantType.String\r\n \r\n :returns: ua.VariantType.Boolean -- Connection removed\r\n \"\"\"\r\n assert type(parent) is ua.NodeId, 'parent argument must be a valid NodeId object.'\r\n assert type(name) is str and name is not '', 'name argument must be a valid and non empty string object.'\r\n assert type(eventname) is str, 'eventname argument must be a valid string value.'\r\n try:\r\n # Get parent node from nodeid\r\n parent_node = self._server.get_node(parent)\r\n # Get node to remove form name\r\n object_node = parent_node.get_child('{}:{}'.format(self._namespace_index, name))\r\n # Trigger given event with the object nodeid\r\n self.TriggerCustomEvent(eventname, object_node.nodeid)\r\n # Remove node\r\n object_node.delete()\r\n # Return True if success\r\n return True\r\n except:\r\n # Return False if failed\r\n return False\r\n\r\n \r\n \r\n @uamethod\r\n def ExportUserType(self, parent, name):\r\n \"\"\" Export user type from library to a XML File.\r\n :param parent: Parent nodeid\r\n :type parent: ua.VariantType.NodeId\r\n \r\n :param name: User type name\r\n :type name: ua.VariantType.String\r\n \r\n :returns: ua.VariantType.String -- XML String containing User type\r\n \"\"\"\r\n # TODO: \r\n return 'empty'\r\n \r\n\r\n #---------------------------------------------------------------------------\r\n # Connections\r\n \r\n @uamethod\r\n def AddNewServerConnection(self, parent, name):\r\n \"\"\" Adds new server connection object.\r\n :param parent: Parent nodeid\r\n :type parent: ua.VariantType.NodeId\r\n \r\n :param name: Connection name\r\n :type name: ua.VariantType.String\r\n \r\n :returns: ua.VariantType.NodeId -- Connection nodeid\r\n \"\"\"\r\n return self.AddNewObject(parent, name, 'server_con', 'NewServerConnection')\r\n \r\n @uamethod\r\n def RemoveServerConnection(self, parent, name):\r\n \"\"\" Removes server connection object with given name.\r\n :param parent: Parent nodeid\r\n :type parent: ua.VariantType.NodeId\r\n \r\n :param name: Connection name\r\n :type name: ua.VariantType.String\r\n \r\n :returns: ua.VariantType.Boolean -- Connection removed\r\n \"\"\"\r\n return self.RemoveObject(parent, name, 'ServerConnectionRemoved')\r\n \r\n def CreateInstanceFromXml(self, parent, xml_element):\r\n \"\"\" Constructor from xml node.\r\n :param parent: Parent nodeid\r\n :type parent: ua.VariantType.NodeId\r\n \r\n :param xml_element: XML String containing User type\r\n :type xml_element: ua.VariantType.String\r\n \r\n :returns: ua.VariantType.NodeId -- New user type nodeid\r\n \"\"\"\r\n assert isinstance(xml_element, Element), 'xml_element argument must be a valid node xml.etree.ElementTree.Element object.'\r\n assert type(parent) is Node, 'node argument must be a valid ua.Node object.'\r\n # check if node is a reference\r\n type_name = xml_element.get('reference', xml_element.tag)\r\n # Create Instance\r\n new_instance = self.CreateObjectInstance(parent, xml_element.get('name'), type_name) \r\n # Load Chlidren\r\n self.LoadChildrenFromXml(new_instance, xml_element)\r\n # Return\r\n return new_instance.nodeid\r\n\r\n @uamethod\r\n def ImportUserType(self, parent, xml_string):\r\n \"\"\" Import user type to library from a XML Element.\r\n :param parent: Parent nodeid\r\n :type parent: ua.VariantType.NodeId\r\n \r\n :param xml_string: XML String containing User type\r\n :type xml_string: ua.VariantType.String\r\n \r\n :returns: ua.VariantType.NodeId -- New user type nodeid\r\n \"\"\"\r\n assert type(xml_string) is str, 'xml_string argument must be a valid string object.'\r\n xml_type = XML(xml_string)\r\n \r\n '''\r\n ","sub_path":"src/open_emulation_platform.py","file_name":"open_emulation_platform.py","file_ext":"py","file_size_in_byte":58963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"549547478","text":"#coding: utf-8\nimport csv\nimport os\n\nclass CSVHelper(object):\n def __init__(self, filename, header=None):\n self._filename = filename\n\n #the Row array should like: [ [cellA1, cellA2, ...], [cellA2, cellB2, ...]]\n def write_rows(self, row_array):\n with open(self._filename, 'ab') as csvfile:\n spamwriter = csv.writer(csvfile, quotechar='|', quoting=csv.QUOTE_MINIMAL, )\n spamwriter.writerows(row_array)\n\n def read_rows(self):\n p = os.getcwd()\n rows = {}\n with open(self._filename) as csvfile:\n reader = csv.reader(csvfile)\n rows = list(reader)\n return rows\n","sub_path":"ExamClientPy/Helper/CSVHelper.py","file_name":"CSVHelper.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"467835256","text":"import random\nimport time\nimport sys\n\nWIDTH_PATTERN = [0, 1, 3, 5, 6]\nMOLECULES = [['G', 'C'], ['A', 'T']]\nBORDER = '#'\nOFFSET = (9, 8, 7, 6, 5, 4, 4, 5, 5, 6, 5, 5, 4, 4, 5, 6, 7, 8)\nPAUSE_TIME = 0.2\n\nprint('DNA Animation')\nprint('Press Ctrl-C to quit...')\ntime.sleep(2)\nidxOffset = -1\n\ntry:\n while True:\n for width in WIDTH_PATTERN + WIDTH_PATTERN[:0:-1]:\n idxOffset = (idxOffset + 1) % len(OFFSET)\n\n if width == 0:\n print(' ' * OFFSET[idxOffset] + BORDER * 2)\n else:\n moleculesPair = random.choice(MOLECULES)\n if random.randint(0, 1) == 1:\n moleculesPair[0], moleculesPair[1] = moleculesPair[1], moleculesPair[0]\n\n print(' ' * (OFFSET[idxOffset]) + BORDER +\n moleculesPair[0] + '-' * width + moleculesPair[1] + BORDER)\n\n time.sleep(PAUSE_TIME)\nexcept KeyboardInterrupt:\n sys.exit()\n","sub_path":"Chapter_21_DnaVisualization/DNA.py","file_name":"DNA.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"406273394","text":"#\r\n# @lc app=leetcode id=67 lang=python3\r\n#\r\n# [67] Add Binary\r\n#\r\n# https://leetcode.com/problems/add-binary/description/\r\n#\r\n# algorithms\r\n# Easy (39.39%)\r\n# Likes: 987\r\n# Dislikes: 198\r\n# Total Accepted: 309.7K\r\n# Total Submissions: 785.9K\r\n# Testcase Example: '\"11\"\\n\"1\"'\r\n#\r\n# Given two binary strings, return their sum (also a binary string).\r\n#\r\n# The input strings are both non-empty and contains only characters 1 or 0.\r\n#\r\n# Example 1:\r\n#\r\n#\r\n# Input: a = \"11\", b = \"1\"\r\n# Output: \"100\"\r\n#\r\n# Example 2:\r\n#\r\n#\r\n# Input: a = \"1010\", b = \"1011\"\r\n# Output: \"10101\"\r\n#\r\n#\r\n\r\n\r\nclass Solution:\r\n def addBinary(self, a: str, b: str) -> str:\r\n res = ''\r\n plus, i, j = 0, len(a) - 1, len(b) - 1\r\n while i >= 0 or j >= 0 or plus > 0:\r\n if i >= 0:\r\n plus += int(a[i])\r\n i -= 1\r\n if j >= 0:\r\n plus += int(b[j])\r\n j -= 1\r\n res += str(plus % 2)\r\n plus //= 2\r\n return res[::-1]\r\n","sub_path":"leetcode-algorithms/067. Add Binary/67.add-binary.py","file_name":"67.add-binary.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"69008925","text":"\"\"\" https://leetcode.com/problems/maximum-score-from-removing-substrings/\nInspiration: If we split the string by characters other than \"a\" and \"b\". After serveral deletion, at the end there should be only \"a\"s or \"b\"s in the string. \n\n1. swap (x, y) and reverse s if y>x\n2. use two pass stack linear scans to first remove \"ab\" in s then remove \"ba\" in stk\n\"\"\" \nclass Solution:\n def maximumGain(self, s: str, x: int, y: int) -> int:\n if y>x: x, y, s = y, x, s[::-1]\n ans = 0\n stk = []\n for c in s:\n stk.append(c)\n while len(stk)>=2 and stk[-2:]==['a', 'b']:\n stk.pop()\n stk.pop()\n ans += x\n \n stk2 = []\n for c in stk:\n stk2.append(c)\n while len(stk)>=2 and stk2[-2:]==['b', 'a']:\n stk2.pop()\n stk2.pop()\n ans += y\n return ans\n","sub_path":"Q_Greedy/TwoPass/L2_1717_Maximum_Score_From_Removing_Substrings.py","file_name":"L2_1717_Maximum_Score_From_Removing_Substrings.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"616603386","text":"from subprocess import call\nimport sys\nimport random\nimport hashlib\n\n\ndef parse_info(info):\n\n # this function must return an array of dictionary.\n # each element should have username which is added as a user\n # you may use same function used in 'cms_user_adder'\n\n '''\n\n # PARSING SAMPLE\n # YOU SHOULD IMPLEMNET THIS BY USERSELF\n\n data = []\n cnt = 1\n for row in info:\n r = row.strip().split()\n pw = hashlib.md5(str(random.random()).encode()).hexdigest()\n\n d = {\n 'username': r[0],\n 'password': pw,\n 'first_name': r[1],\n 'last_name': r[2],\n }\n\n data.append(d)\n cnt += 1\n\n return data\n\n '''\n\n return [\n {\n 'username': 'iam',\n 'password': 'mr',\n 'first_name': 'Donald',\n 'last_name': 'Trump',\n }\n ]\n\n\ndef main():\n\n if len(sys.argv) < 3:\n print(\"[*] Usage : python %s \" % sys.argv[0])\n exit()\n\n user_info_file = sys.argv[1]\n contest_id = sys.argv[2]\n\n users = open(user_info_file, 'r').readlines()\n user_info = parse_info(users)\n\n for info in user_info:\n\n # $ cmsAddParticipation -c \n call(['cmsAddParticipation', info['username'],\n '-c', contest_id])\n\n print('[+] Done adding participation')\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/cms_user_participater.py","file_name":"cms_user_participater.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"284210196","text":"WINDOWWIDTH = 600\nWINDOWHEIGHT = 600\nTEXTCOLOR = (255, 255, 255)\nBLACK = (0, 0, 0)\nFPS = 40\nBADDIEMINSIZE = 40\nBADDIEMAXSIZE = 80\nCHERRYMINSIZE = 20\nCHERRYMAXSIZE = 40\nBADDIEMINSPEED = 2\nBADDIEMAXSPEED = 4\nCHERRYMINSPEED = 1\nCHERRYMAXSPEED = 2\nADDNEWBADDIERATE = 6\nADDNEWBULLETRATE = 100\nADDNEWCHERRYRATE = 10\nPLAYERMOVERATE = 5\nBULLETMINMOVERATE = 4\nBULLETMAXMOVERATE = 8\nBULLETWIDTH = 1\nBULLETHEIGHT = 4\nCHERRYMOVERATE = 30\nADDBADDIEBULLETRATE = 200\nUPLEFT = 3\nUPRIGHT = 4\nUP = 5\n\n","sub_path":"dodgerconstants-DESKTOP-HFFA1QI.py","file_name":"dodgerconstants-DESKTOP-HFFA1QI.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"630435266","text":"# -*- encoding: utf-8 -*-\n\"\"\"\n boilerplate\n -----------\n\n The heart of the application.\n\n :copyright: (c) 2013 by Morgan Delahaye-Prat.\n :license: BSD, see LICENSE for more details.\n\"\"\"\n\n\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport sys, importlib\nfrom flask import Flask, request, session\n\nfrom .helpers.routing import RegexConverter\nfrom .helpers.patch import monkey_patch_blueprint\n\n\n# Preliminary tasks\nmonkey_patch_blueprint()\n\n\ndef load_config(app, config=None):\n \"\"\"\n Load the configuration of the application.\n The default settings are set in the python file `default_config.py`.\n \"\"\"\n\n target = '{}.default_config'.format(__name__.split('.', 1)[0])\n app.config.from_object(target)\n if config is not None:\n app.config.from_object(config)\n\n\ndef register_ui(app, name, prefix):\n \"\"\"Register the UI part of a module.\"\"\"\n\n target = '{}.{}.{}.{}'.format(\n __name__.split('.', 1)[0],\n app.config.get('BOILERPLATE_MODULES', 'modules'), # default to modules\n name,\n app.config.get('BOILERPLATE_UI', 'ui')\n )\n\n try:\n ui = importlib.import_module(target)\n except ImportError as err:\n if ((sys.version_info < (3, 3) and 'No module named ui' in err.message) or\n ( sys.version_info >= (3, 3) and err.name == target)):\n app.logger.warning('[SKIP] `{}` ui : {}'.format(name, err))\n else:\n app.logger.error('[FAIL] `{}` ui : {}'.format(name, err))\n raise err\n else:\n if prefix == '/': prefix = None\n app.register_blueprint(ui.ui, url_prefix=prefix)\n app.logger.info('[LOAD] `{}` ui. (uri: {})'.format(name, prefix))\n\n\ndef register_api(app, name, prefix):\n \"\"\"Register the API part of a module.\"\"\"\n\n target = '{}.{}.{}.{}'.format(\n __name__.split('.', 1)[0],\n app.config.get('BOILERPLATE_MODULES', 'modules'), # default to modules\n name,\n app.config.get('BOILERPLATE_API', 'api')\n )\n\n try:\n api = importlib.import_module(target)\n except ImportError as err:\n if ((sys.version_info < (3, 3) and 'No module named api' in err.message) or\n ( sys.version_info >= (3, 3) and err.name == target)):\n app.logger.warning('[SKIP] `{}` api : {}'.format(name, err))\n else:\n app.logger.error('[FAIL] `{}` api : {}'.format(name, err))\n raise err\n else:\n prefix = '/{}/{}'.format(app.config.get('BOILERPLATE_API_PREFIX', ''),\n prefix)\n prefix = '/{}'.format('/'.join(s for s in prefix.split('/') if s))\n if prefix == '/': prefix = None\n app.register_blueprint(api.api, url_prefix=prefix)\n app.logger.info('[LOAD] `{}` api. (uri: {})'.format(name, prefix))\n\n\ndef register_models(app, name):\n \"\"\"Register models of a module.\"\"\"\n\n target = '{}.{}.{}.{}'.format(\n __name__.split('.', 1)[0],\n app.config.get('BOILERPLATE_MODULES', 'modules'), # default to modules\n name,\n app.config.get('BOILERPLATE_MODELS', 'models')\n )\n\n try:\n models = importlib.import_module(target)\n except ImportError as err:\n if ((sys.version_info < (3, 3) and 'No module named models' in err.message) or\n ( sys.version_info >= (3, 3) and err.name == target)):\n app.logger.warning('[SKIP] `{}` model(s) : {}'.format(name, err))\n else:\n app.logger.error('[FAIL] `{}` model(s) : {}'.format(name, err))\n raise err\n else:\n app.logger.info('[LOAD] `{}` model(s).'.format(name))\n\n\ndef register_modules(app, modules):\n \"\"\"\n Call the three methods to fully load a module.\n \"\"\"\n for name, uri in modules.items():\n register_models(app, name)\n register_api(app, name, uri)\n register_ui(app, name, uri)\n\n # application wide models loading\n target = '{}.{}'.format(\n __name__.split('.', 1)[0],\n app.config.get('BOILERPLATE_MODELS', 'models')\n )\n models = importlib.import_module(target)\n\ndef app_factory(name=__name__, modules=None, config=None):\n\n app = Flask(__name__, static_path='/static')\n load_config(app, config)\n\n # register all the modules\n register_modules(app, modules)\n\n # register the routing converters\n app.url_map.converters['regex'] = RegexConverter\n\n # return the application when the initialization process is finished\n return app\n","sub_path":"boilerplate/boilerplate.py","file_name":"boilerplate.py","file_ext":"py","file_size_in_byte":4476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"209516911","text":"# File: C (Python 2.2)\n\nimport DirectNotifyGlobal\nimport StateData\nimport FSM\nimport State\nimport CogHQExterior\nimport CogHQLobby\nimport CogHQBossBattle\nimport FactoryExterior\nimport FactoryInterior\nimport QuietZoneState\nimport TownBattle\nimport Toon\nimport Suit\nfrom PandaModules import *\n\nclass CogHQLoader(StateData.StateData):\n notify = DirectNotifyGlobal.directNotify.newCategory('CogHQLoader')\n \n def __init__(self, hood, parentFSMState, doneEvent):\n StateData.StateData.__init__(self, doneEvent)\n self.hood = hood\n self.parentFSMState = parentFSMState\n self.placeDoneEvent = 'cogHQLoaderPlaceDone'\n self.townBattleDoneEvent = 'town-battle-done'\n self.fsm = FSM.FSM('CogHQLoader', [\n State.State('start', None, None, [\n 'quietZone',\n 'factoryExterior',\n 'cogHQExterior',\n 'cogHQBossBattle']),\n State.State('cogHQExterior', self.enterCogHQExterior, self.exitCogHQExterior, [\n 'quietZone',\n 'factoryExterior',\n 'cogHQLobby']),\n State.State('cogHQLobby', self.enterCogHQLobby, self.exitCogHQLobby, [\n 'quietZone',\n 'cogHQExterior',\n 'cogHQBossBattle']),\n State.State('cogHQBossBattle', self.enterCogHQBossBattle, self.exitCogHQBossBattle, [\n 'quietZone']),\n State.State('factoryExterior', self.enterFactoryExterior, self.exitFactoryExterior, [\n 'quietZone',\n 'factoryInterior',\n 'cogHQExterior']),\n State.State('factoryInterior', self.enterFactoryInterior, self.exitFactoryInterior, [\n 'quietZone',\n 'factoryExterior']),\n State.State('quietZone', self.enterQuietZone, self.exitQuietZone, [\n 'cogHQExterior',\n 'cogHQLobby',\n 'cogHQBossBattle',\n 'factoryExterior',\n 'factoryInterior']),\n State.State('final', None, None, [\n 'start'])], 'start', 'final')\n\n \n def load(self, zoneId):\n self.parentFSMState.addChild(self.fsm)\n self.music = base.loadMusic(self.musicFile)\n self.battleMusic = base.loadMusic('phase_9/audio/bgm/encntr_suit_winning.mid')\n self.townBattle = TownBattle.TownBattle(self.townBattleDoneEvent)\n self.townBattle.load()\n Suit.loadSuits(3)\n Toon.loadCogHQAnims()\n self.loadPlaceGeom(zoneId)\n\n \n def loadPlaceGeom(self, zoneId):\n return None\n\n \n def unloadPlaceGeom(self):\n return None\n\n \n def unload(self):\n self.unloadPlaceGeom()\n self.parentFSMState.removeChild(self.fsm)\n del self.parentFSMState\n del self.fsm\n self.townBattle.unload()\n self.townBattle.cleanup()\n del self.townBattle\n del self.battleMusic\n Suit.unloadSuits(3)\n Suit.unloadSkelDialog()\n Toon.unloadCogHQAnims()\n ModelPool.garbageCollect()\n TexturePool.garbageCollect()\n\n \n def enter(self, requestStatus):\n self.fsm.enterInitialState()\n self.fsm.request(requestStatus['where'], [\n requestStatus])\n\n \n def exit(self):\n self.ignoreAll()\n\n \n def enterQuietZone(self, requestStatus):\n self.quietZoneDoneEvent = 'quietZoneDone'\n self.acceptOnce(self.quietZoneDoneEvent, self.handleQuietZoneDone)\n self.quietZoneStateData = QuietZoneState.QuietZoneState(self.quietZoneDoneEvent)\n self.quietZoneStateData.load()\n self.quietZoneStateData.enter(requestStatus)\n\n \n def exitQuietZone(self):\n self.ignore(self.quietZoneDoneEvent)\n del self.quietZoneDoneEvent\n self.quietZoneStateData.exit()\n self.quietZoneStateData.unload()\n self.quietZoneStateData = None\n\n \n def handleQuietZoneDone(self):\n status = toonbase.tcr.handlerArgs\n self.fsm.request(status['where'], [\n status])\n\n \n def enterPlace(self, requestStatus):\n self.acceptOnce(self.placeDoneEvent, self.placeDone)\n self.place = self.placeClass(self, self.fsm, self.placeDoneEvent)\n toonbase.tcr.playGame.setPlace(self.place)\n self.place.load()\n self.place.enter(requestStatus)\n\n \n def exitPlace(self):\n self.ignore(self.placeDoneEvent)\n self.place.exit()\n self.place.unload()\n self.place = None\n toonbase.tcr.playGame.setPlace(self.place)\n\n \n def placeDone(self):\n self.requestStatus = self.place.doneStatus\n status = self.place.doneStatus\n if status['loader'] == 'cogHQLoader' and status.get('shardId') == None:\n self.unloadPlaceGeom()\n zoneId = status['zoneId']\n self.loadPlaceGeom(zoneId)\n self.fsm.request('quietZone', [\n status])\n else:\n self.doneStatus = status\n messenger.send(self.doneEvent)\n\n \n def enterCogHQExterior(self, requestStatus):\n self.placeClass = CogHQExterior.CogHQExterior\n self.enterPlace(requestStatus)\n self.hood.spawnTitleText(requestStatus['zoneId'])\n\n \n def exitCogHQExterior(self):\n taskMgr.remove('titleText')\n self.hood.hideTitleText()\n self.exitPlace()\n self.placeClass = None\n\n \n def enterCogHQLobby(self, requestStatus):\n self.placeClass = CogHQLobby.CogHQLobby\n self.enterPlace(requestStatus)\n self.hood.spawnTitleText(requestStatus['zoneId'])\n\n \n def exitCogHQLobby(self):\n taskMgr.remove('titleText')\n self.hood.hideTitleText()\n self.exitPlace()\n self.placeClass = None\n\n \n def enterCogHQBossBattle(self, requestStatus):\n self.placeClass = CogHQBossBattle.CogHQBossBattle\n self.enterPlace(requestStatus)\n\n \n def exitCogHQBossBattle(self):\n self.exitPlace()\n self.placeClass = None\n\n \n def enterFactoryExterior(self, requestStatus):\n self.placeClass = FactoryExterior.FactoryExterior\n self.enterPlace(requestStatus)\n self.hood.spawnTitleText(requestStatus['zoneId'])\n\n \n def exitFactoryExterior(self):\n taskMgr.remove('titleText')\n self.hood.hideTitleText()\n self.exitPlace()\n self.placeClass = None\n\n \n def enterFactoryInterior(self, requestStatus):\n self.placeClass = FactoryInterior.FactoryInterior\n self.enterPlace(requestStatus)\n\n \n def exitFactoryInterior(self):\n self.exitPlace()\n self.placeClass = None\n\n\n","sub_path":"2004-02-24-ga-sv1.0.10.10/modules_decompiled/CogHQLoader.py","file_name":"CogHQLoader.py","file_ext":"py","file_size_in_byte":6650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"586335764","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jul 4 15:23:50 2019\r\n\r\n@author: amanoels\r\n\"\"\"\r\nimport numpy as np\r\nimport pandas as pd\r\n#import matplotlib.pyplot as plt # Import Biblioteca de Visualização\r\nimport seaborn as sns\r\nfrom sklearn.linear_model import LinearRegression\r\n#from plotnine import * \r\n\r\n\r\n#Importando dados com Pandas\r\ndf = pd.read_excel(\"D:\\DataSets_Exemplos\\RLSBEZERRO.xlsx\")\r\n\r\n# Convertendo para arrays do Numpy\r\n#df = np.array(df)\r\n# Fazendo o Reshape em x pois é necessario um array bi-dimensional\r\nx = np.array(df['Medida(CM)']).reshape(-1,1)\r\ny = np.array(df['Peso (KG)'])\r\n\r\nsns.set()\r\n# Gerando um grafico de dispersão\r\n#plt.scatter(x,y)\r\nsns.scatterplot(x,y)\r\n#plt.scatter(df['Medida(CM)'],df['Peso (KG)'])\r\n\r\n# Gerando analise de Boxplot\r\n#plt.boxplot(x)\r\n#plt.label(\"Diagrama de Caixa Medida CM\")\r\nsns.boxplot(x, orient = \"v\", notch = \"TRUE\")\r\nsns.boxplot(y, orient = \"v\", notch = \"TRUE\")\r\n\r\n# Gerando o modelo\r\nmodel = LinearRegression()\r\n\r\n# Carregando o modelo\r\nmodel.fit(x,y)\r\n\r\n# Obtendo os resultados\r\nr_sq = model.score(x, y)\r\nprint('O r² de Determinação é :', r_sq) # Precisão do modelo\r\nprint('O Intercepto do modelo é :', model.intercept_) # Intercepto do modelo\r\nprint('O Coeficiente do modelo é : ', model.coef_) # Medida CM do modelo\r\n# Prevendo um resultado\r\n# Gerando uma analise de teste\r\na = {'Peso_Previsto':[20,28]}\r\na\r\n# Transformando em DataFrame\r\nb = pd.DataFrame(a)\r\nb\r\n# Agrupando resultados em uma estrutura para predição\r\najuste = model.intercept_ + model.coef_ * b\r\n# Exibindo\r\najuste\r\n\r\n# Gerando resultado em tempo real\r\ndados = int(input('Digite a medida do torax em CM do Bezerro: ' ))\r\n# Calculando resultado do modelo.\r\najuste2 = model.intercept_ + model.coef_ * dados\r\n# Exibindo resultado. \r\nprint('A medida CM informada foi:',dados,'CM',\r\n 'e a previsão de peso do Bezerro é de :', ajuste2,'KG')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#geom_boxplot(aes(x, stat='boxplot', show_legend = \"True\")\r\n# Convertendo para DataFrame com nome de \r\n#df_x = pd.DataFrame(x, columns = ['Medida CM'])\r\n#ggplot(df, aes(x = 'Medida(CM)', y = 'Peso (KG)')) + geom_boxplot()\r\n#ggplot(df, aes(x = 'Medida(CM)', y = 'Peso (KG)')) + geom_point()\r\n\r\n#teste = df.iloc[:, 1:3]\r\n\r\n#plt.scatter(teste['Preco_Anunciado'],teste['Area_Util'])\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"RegressãoLinear/Regressão_Linear_python.py","file_name":"Regressão_Linear_python.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"370855388","text":"\n# coding: utf-8\n\n# ### 导入包\n\n# In[375]:\n\n\nimport numpy as np\nimport h5py\nimport matplotlib.pyplot as plt\n\n\n# ### 工具函数\n\n# #### sigmoid\n\n# In[376]:\n\n\ndef sigmoid(Z):\n '''\n cache - as activation_cache\n '''\n \n A=1/(1+np.exp(-Z))\n cache=Z\n \n return A,cache\n\n\n# #### sigmoid backward\n\n# In[377]:\n\n\ndef sigmoid_backward(dA,cache):\n '''\n dA - at present dA\n Z - at present Z\n cache - include dZ\n '''\n Z=cache\n s=1/(1+np.exp(-Z))\n dZ=dA*s*(1-s)\n \n assert(dZ.shape==Z.shape)\n \n return dZ\n\n\n# #### relu\n\n# In[378]:\n\n\ndef relu(Z):\n '''\n cache - as activation_cache\n '''\n A=np.maximum(0,Z)\n \n assert(A.shape == Z.shape)\n \n cache=Z\n \n return A,cache\n\n\n# #### relu backward\n\n# In[379]:\n\n\ndef relu_backward(dA,cache):\n \n Z=cache\n dZ=np.array(dA,copy=True)\n \n dZ[Z<=0]=0\n \n assert(dZ.shape==Z.shape)\n \n return dZ\n\n\n# ### 初始化参数\n\n# In[380]:\n\n\ndef init_params(layer_dims):\n '''\n layer_dims - a tuple:[n0,...,nL] include number of node of layer for 0 to L\n params - include params of layer for 1 to L\n '''\n np.random.seed(3)\n L=len(layer_dims) \n params={}\n \n for l in range(1,L):\n params['W'+str(l)]=np.random.randn(layer_dims[l],layer_dims[l-1])/np.sqrt(layer_dims[l-1])\n params['b'+str(l)]=np.zeros((layer_dims[l],1))\n \n assert(params['W'+str(l)].shape==(layer_dims[l],layer_dims[l-1]))\n assert(params['b'+str(l)].shape==(layer_dims[l],1))\n \n return params\n\n\n# ### 前向传播\n\n# In[381]:\n\n\ndef forward_weight(A_prev,W,b):\n '''\n A_prev - A of prev layer \n W - W of this layer \n b - b of this layer \n \n Z - weight of this layer\n cache - include A_prev,W,b\n '''\n Z=np.dot(W,A_prev)+b\n \n assert(Z.shape==(W.shape[0],A_prev.shape[1]))\n cache=(A_prev,W,b)\n \n return Z,cache\n\n\n# In[382]:\n\n\ndef forward_activation(A_prev,W,b,activation):\n '''\n A_prev - A of prev layer \n W - W of this layer \n b - b of this layer \n activation - choice func of activation\n \n A - A of this layer at \n \n cache -\n weight_cache include A_prev,W,b\n activation_cache include Z\n '''\n Z,weight_cache=forward_weight(A_prev,W,b)\n \n if activation=='sigmoid':\n A,activation_cache=sigmoid(Z)\n elif activation=='relu':\n A,activation_cache=relu(Z)\n cache=(weight_cache,activation_cache)\n \n return A,cache \n\n\n# In[383]:\n\n\ndef forward_propagation(X,params):\n '''\n X - train data\n params - params of layer for 1 to L\n \n AL - A of last layer (output)\n caches - include cache of layer for 1 to L\n '''\n \n caches=[]\n A=X\n L=len(params)//2\n \n for l in range(1,L):\n A_prev=A\n A,cache=forward_activation(A_prev,params['W'+str(l)],params['b'+str(l)],'relu')\n caches.append(cache)\n \n AL,cache=forward_activation(A,params['W'+str(L)],params['b'+str(L)],'sigmoid')\n caches.append(cache)\n\n assert(AL.shape==(1,X.shape[1]))\n \n return AL,caches\n\n\n# ### 计算损失\n\n# In[384]:\n\n\ndef compute_cost(AL,Y):\n '''\n AL - A of last layer\n Y - label of train data\n cost - a value\n '''\n \n m=Y.shape[1]\n cost = -np.sum(np.multiply(np.log(AL),Y) + np.multiply(np.log(1 - AL), 1 - Y)) / m\n cost=np.squeeze(cost)\n \n assert(cost.shape==())\n \n return cost\n\n\n# ### 反向传播\n\n# In[385]:\n\n\ndef back_propagation(dZ,cache):\n '''\n dZ - at present dZ\n cache - include A_prev,W,b\n '''\n \n A_prev,W,b=cache\n m=A_prev.shape[1]\n \n dW=np.dot(dZ,A_prev.T)/m\n db=dZ.sum(axis=1,keepdims=True)/m\n dA_prev=np.dot(W.T,dZ)\n \n assert(dW.shape==W.shape)\n assert(db.shape==b.shape)\n assert(dA_prev.shape==A_prev.shape)\n \n return dA_prev,dW,db\n\n\n# In[386]:\n\n\ndef back_activation(dA,cache,activation):\n '''\n dA - dA of this layer\n cache - include weight_cache and acvation_cache\n activation - choice the func of activation\n '''\n weight_cache,activation_cache=cache\n \n if activation=='sigmoid':\n dZ=sigmoid_backward(dA,activation_cache)\n elif activation=='relu':\n dZ=relu_backward(dA,activation_cache)\n \n dA_prev,dW,db=back_propagation(dZ,weight_cache)\n \n return dA_prev,dW,db\n\n\n# ### 计算梯度\n\n# In[387]:\n\n\ndef compute_grads(AL,Y,caches):\n \n grads={}\n L=len(caches)\n m=AL.shape[1]\n Y=Y.reshape(AL.shape)\n\n dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL))\n \n current_cache=caches[L-1]\n grads[\"dA\"+str(L)],grads[\"dW\"+str(L)],grads[\"db\"+str(L)]=back_activation(dAL,current_cache,\"sigmoid\")\n\n for l in reversed(range(L-1)):\n current_cache=caches[l]\n dA_prev_temp,dW_temp,db_temp=back_activation(grads[\"dA\"+str(l+2)],current_cache,\"relu\")\n grads[\"dA\"+str(l+1)]=dA_prev_temp\n grads[\"dW\"+str(l+1)]=dW_temp\n grads[\"db\"+str(l+1)]=db_temp\n \n return grads\n\n\n# ### 更新参数\n\n# In[388]:\n\n\ndef update_params(params,grads,learning_rate):\n \n L=len(params)//2\n \n for l in range(L):\n \n params[\"W\"+str(l+1)]=params[\"W\"+str(l+1)] - learning_rate * grads['dW'+str(l+1)]\n params[\"b\"+str(l+1)]=params[\"b\"+str(l+1)] - learning_rate * grads['db'+str(l+1)]\n \n return params\n\n\n# ### 搭建L层神经网络\n\n# In[401]:\n\n\ndef L_layer_model(X,Y,layers_dims,n_iterations,learning_rate,print_cost=False,plot_image=False):\n \n np.random.seed(1)\n \n costs=[]\n params=init_params(layers_dims)\n \n for iters in range(n_iterations):\n \n AL,caches=forward_propagation(X,params)\n cost=compute_cost(AL,Y)\n costs.append(cost)\n\n grads=compute_grads(AL,Y,caches)\n params=update_params(params,grads,learning_rate)\n\n if print_cost:\n if iters%100==0:\n print(\"第{}次迭代,损失为{}\".format(iters,cost))\n \n if plot_image:\n plt.figure(figsize=(12,6))\n plt.plot(range(n_iterations),costs)\n plt.title(\"Learning rate=\"+str(learning_rate))\n plt.xlabel(\"cost\")\n plt.ylabel(\"iterations\")\n plt.show()\n \n return params\n\n\n# ### 预测\n\n# In[402]:\n\n\ndef predict(X,params,threshold):\n \n AL,caches=forward_propagation(X,params)\n y_pred=np.where(AL>threshold,1,0)\n \n return y_pred\n\n\n# ### 计算准确率\n\n# In[403]:\n\n\ndef score(y_pred,Y,threshold):\n \n scores=len(Y[y_pred-Y==0])/Y.shape[1]\n \n return scores\n\n\n# ### 加载数据\n\n# In[404]:\n\n\ndef load_dataset():\n train_dataset = h5py.File('datasets/train_catvnoncat.h5', \"r\")\n train_set_x_orig = np.array(train_dataset[\"train_set_x\"][:]) # your train set features\n train_set_y_orig = np.array(train_dataset[\"train_set_y\"][:]) # your train set labels\n\n test_dataset = h5py.File('datasets/test_catvnoncat.h5', \"r\")\n test_set_x_orig = np.array(test_dataset[\"test_set_x\"][:]) # your test set features\n test_set_y_orig = np.array(test_dataset[\"test_set_y\"][:]) # your test set labels\n\n classes = np.array(test_dataset[\"list_classes\"][:]) # the list of classes\n\n train_set_y_orig = train_set_y_orig.reshape((1, train_set_y_orig.shape[0]))\n test_set_y_orig = test_set_y_orig.reshape((1, test_set_y_orig.shape[0]))\n\n return train_set_x_orig, train_set_y_orig, test_set_x_orig, test_set_y_orig, classes\n\n\n# ### 处理数据\n\n# In[405]:\n\n\ntrain_set_x_orig , train_set_y , test_set_x_orig , test_set_y , classes = load_dataset()\n\ntrain_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T \ntest_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T\n\ntrain_x = train_x_flatten / 255\ntrain_y = train_set_y\ntest_x = test_x_flatten\ntest_y = test_set_y\n\n\n# ### 训练\n\n# In[406]:\n\n\n# 设置超参数\nlayers_dims=[12288,20,7,5,1]\nn_iterations=2500\nlearning_rate=0.0075\nthreshold=0.5\n\n\n# In[407]:\n\n\nparams=L_layer_model(train_x,train_y,layers_dims,n_iterations,learning_rate,print_cost=True,plot_image=True)\n\n\n# In[408]:\n\n\ntrain_y_pred=predict(train_x,params,threshold)\ntest_y_pred=predict(test_x,params,threshold)\n\ntrain_score=score(train_y_pred,train_y,threshold)\ntest_score=score(test_y_pred,test_y,threshold)\n\nprint(\"训练集准确率为:\",train_score)\nprint(\"测试集准确率为:\",test_score)\n\n\n# ### 打印出分类错误的图片\n\n# In[413]:\n\n\ndef print_mistake_imag(img_data,y_true,y_pred):\n \n plt.figure(figsize=(12,6))\n y_m=y_pred-y_true\n mistake_index=np.where(y_m==1)\n width=len(mistake_index[1])\n classes=['non-cat','cat']\n \n for i,m_index in enumerate(mistake_index[1]):\n plt.subplot(1,width,i+1)\n plt.imshow(img_data[m_index])\n string='Prediction:'+classes[y_pred[0][m_index]]+'\\n'+'True:'+classes[y_true[0][m_index]]\n plt.title(string)\n\n\n# In[414]:\n\n\nprint_mistake_imag(test_set_x_orig,test_y_pred,test_y)\n\n\n# ### 用模型测试自己的图片\n\n# In[415]:\n\n\ndef discern_cat(impath,params):\n classes=['non-cat','cat']\n img=cv2.imread(impath)\n img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\n img=cv2.resize(img,(64,64))\n plt.figure(figsize=(5,5))\n plt.imshow(img)\n \n img_array=img.reshape(-1,1)\n reason=predict(img_array,params,0.5)[0]\n print('This is a '+classes[int(reason)])\n\n\n# In[428]:\n\n\nimport cv2\n\npath='my_image/1.jpg'\ndiscern_cat(path,params)\n\n","sub_path":"DNN/DNN.py","file_name":"DNN.py","file_ext":"py","file_size_in_byte":9362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"123269230","text":"from django.forms import ModelForm\nfrom Reservacion.models import Reservacion\nfrom django.utils.translation import gettext_lazy as _\nfrom bootstrap_datepicker_plus import DateTimePickerInput\n\n\nclass ReservarForm(ModelForm):\n class Meta:\n model = Reservacion\n fields = ['fecha', 'local', 'maquina']\n help_texts = {\n\n 'fecha': _('Formato de la fecha dd/mm/yyyy'),\n }\n error_messages = {\n 'fecha': {\n 'max_length': _(\"El formato de la fecha es incorrecto ejemplo : 01/12/2020 .\"),\n }\n }\n widgets = {\n 'fecha': DateTimePickerInput(), # default date-format %m/%d/%Y will be used\n # 'end_date': DatePickerInput(format='%Y-%m-%d'), # specify date-frmat\n }\n","sub_path":"Reservacion/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"520201561","text":"'''\nCreated on 2016年8月23日\n\n@author: Zhang Xiulong\n'''\nfrom tools.list_operation import *\nfrom tools.text_process import *\n\ndef move_repeat_corpus(input_corpus_path,output_corpus_path):\n input_corpus_list = read_list(input_corpus_path)\n _check_conflict_corpus(input_corpus_list)\n _move_repeat_corpus(input_corpus_list,output_corpus_path)\n \ndef _check_conflict_corpus(input_corpus_list):\n content_topic_map = {}\n for line in input_corpus_list:\n split_list = split_line_2_list(line,\"\\t\",2)\n topic_name = split_list[0]\n content = split_list[1]\n if content in content_topic_map : \n temp_topic = content_topic_map[content]\n if temp_topic != topic_name:\n print('conflict in two lines:')\n print(line)\n print(temp_topic + '\\t' + content)\n print('exit')\n exit()\n else:\n content_topic_map[content] = topic_name\n \ndef _move_repeat_corpus(input_corpus_list,output_corpus_path):\n content_topic_map = {}\n for line in input_corpus_list:\n split_list = split_line_2_list(line,\"\\t\",2)\n topic_name = split_list[0]\n content = split_list[1]\n if content in content_topic_map : \n print('repeat content:',content)\n continue\n else:\n content_topic_map[content] = topic_name\n \n with codecs.open(output_corpus_path, 'w', 'utf-8') as write_file:\n for content in content_topic_map:\n topic = content_topic_map[content]\n line = topic + '\\t' + content\n write_file.write(line + '\\r\\n')\n \n \n \n \n \nif __name__ == '__main__':\n input_corpus_path = '../../data/total/additive_server_corpus.txt'\n output_corpus_path = '../../data/total/additive_server_corpus_clean.txt'\n move_repeat_corpus(input_corpus_path,output_corpus_path)\n ","sub_path":"tools/move_repeat_additive_data.py","file_name":"move_repeat_additive_data.py","file_ext":"py","file_size_in_byte":1921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"241413455","text":"import numpy as np\nimport tensorflow as tf\nimport pandas as pd\nimport copy\nimport matplotlib.pyplot as plt\n\n# read in the data set\nf = open('./text8/text8')\ntext8 = []\nfor line in f.readlines():\n text8.append(line)\ntext8 = text8[0].split()\n\nvoc = {}\nfor word in text8:\n if word in voc:\n voc[word] += 1\n else:\n voc[word] = 1\n\nvoclist = []\nfor word, count in voc.items():\n temp = [word, count]\n voclist.append(temp)\n\nvocdf = pd.DataFrame(voclist)\nind = np.argsort(vocdf.iloc[:,1])[::-1]\nvocdf = vocdf.iloc[ind,:]\n\nfinalvoc = list(vocdf.iloc[:9999,0])\nfinalvoc.append('')\n\ntext8reduce = copy.copy(text8)\nfor i,word in enumerate(text8reduce):\n if word in finalvoc:\n text8reduce[i] = finalvoc.index(word)\n else:\n text8reduce[i] = 9999 # set to \n\ncoocmat = np.zeros(shape=(10000,10000))\n\nwindowsize = 3\nfor i,word in enumerate(text8reduce):\n wordwindow = text8reduce[max(0, i-windowsize):i] + text8reduce[(i+1):min(i+windowsize+1, len(text8reduce))]\n for coword in wordwindow:\n coocmat[word, coword]+=1\n\nembsize = 100\ncoocmattensor = tf.constant(coocmat)\ns, u, v = tf.svd(coocmattensor)\n\nwith tf.Session() as sess:\n s, u, v = sess.run([s,u,v])\n\n# visualize most common 100 words using the first two dimensions of the embeddings\nfor i in range(50):\n fig = plt.gcf()\n fig.set_size_inches(18.5, 10.5)\n plt.text(u[i,0], u[i,1], finalvoc[i])\n plt.xlim((-0.5,0.2))\n plt.ylim((-0.5,0.2)) \nplt.savefig('viz.jpg')\n\nemb = u[:, :embsize]\nnp.save('embedding', emb)\n","sub_path":"assignments/assignment 1/q3_count.py","file_name":"q3_count.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"275504051","text":"# Sum Pairs\n# Write a function called sum_pairs which accepts a list and a number and returns the first pair of numbers that sum to the number passed to the function.\ndef sum_pairs(li, num):\n\talready_visited = set()\n\tfor i in li:\n\t\tdifference = num - i\n\t\tif difference in already_visited:\n\t\t\treturn [difference, i]\n\t\talready_visited.add(i)\n\treturn []\n\nprint(sum_pairs([4,2,10,5,1], 6)) # [4, 2]\nprint(sum_pairs([11, 20, 4, 2, 1, 5], 100)) # []","sub_path":"Basics/157_Python_Ex_18.py","file_name":"157_Python_Ex_18.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"387347161","text":"import numpy as np\nimport tensorflow as tf\nimport pickle\nimport math\nfrom RawData_functions import select_genes\n\n'''\n1. Functions for building a network\n'''\ndef shift_scale(train_data):\n train_x, train_g, train_y, sample_info = train_data\n input_shift = np.mean(train_x, axis=0).reshape(1,-1)\n input_scale = np.std(train_x, axis=0).reshape(1,-1)\n return(input_shift, input_scale)\n\n\ndef weight_variables(shape, given_initial=None):\n if given_initial == None:\n initial = tf.truncated_normal(shape, stddev=0.1)\n else:\n initial = given_initial\n return tf.Variable(initial, name='W')\n\n\ndef bias_variables(shape, given_initial=None):\n if given_initial == None:\n initial = tf.constant(0.1, dtype=tf.float32, shape=shape)\n else:\n initial = given_initial\n return tf.Variable(initial, name='b')\n\n\n# this is a simpler version of Tensorflow's 'official' version. See:\n# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/layers/python/layers/layers.py#L102\ndef batch_norm_wrapper(inputs, is_training=True, decay=0.99):\n epsilon = 0.001\n scale = tf.Variable(tf.ones([inputs.get_shape()[-1]]))\n beta = tf.Variable(tf.zeros([inputs.get_shape()[-1]]))\n pop_mean = tf.Variable(tf.zeros([inputs.get_shape()[-1]]), trainable=False)\n pop_var = tf.Variable(tf.ones([inputs.get_shape()[-1]]), trainable=False)\n\n if is_training:\n batch_mean, batch_var = tf.nn.moments(inputs, [0])\n train_mean = tf.assign(pop_mean,\n pop_mean * decay + batch_mean * (1 - decay))\n train_var = tf.assign(pop_var,\n pop_var * decay + batch_var * (1 - decay))\n with tf.control_dependencies([train_mean, train_var]):\n return tf.nn.batch_normalization(inputs,\n batch_mean, batch_var, beta, scale, epsilon)\n else:\n return tf.nn.batch_normalization(inputs,\n pop_mean, pop_var, beta, scale, epsilon)\n\n\ndef build_graph(w_input, w_hidden=[200, 100], w_output=2, given_initial=None):\n '''\n :param n_feature: in the cell-typing case, this is the number of genes at input layer\n :param n_output:\n :return:\n '''\n # Placeholders\n x_shift = tf.placeholder(tf.float32, [None, w_input], name='x_shift')\n x_scale = tf.placeholder(tf.float32, [None, w_input], name='x_scale')\n xs = tf.placeholder(tf.float32, [None, w_input], name='xs')\n ys = tf.placeholder(tf.float32, [None, w_output], name='ys')\n class_factor = tf.placeholder(tf.float32, [None, w_output], name='class_factor') # A factor for balancing class training samples\n kp = tf.placeholder(tf.float32, len(w_hidden), name='kp')\n param = []\n\n\n # Input ---> hidden layers\n current_input_train = xs\n current_input_test = xs\n for layer_i, n_output in enumerate(w_hidden):\n # 1. Initialize parameters\n n_input = int(current_input_train.get_shape()[1])\n if given_initial == None:\n W_init, b_init = None, None\n else:\n W_init, b_init = given_initial[layer_i]\n W = weight_variables([n_input, n_output], W_init)\n b = bias_variables([n_output], b_init)\n param.append([W, b])\n\n # 2. Forward propagation\n # For training purpose, we perform batch normalization\n z_train = tf.matmul(current_input_train, W) + b\n bn = batch_norm_wrapper(z_train)\n h_fc = tf.nn.relu(bn)\n h_fc_drop = tf.nn.dropout(h_fc, kp[layer_i])\n current_input_train = h_fc_drop\n # For testing purpose, we do not perform batch normalization. Important!\n z_test = tf.matmul(current_input_test, W) + b\n current_input_test = tf.nn.relu(z_test)\n\n # Hidden layers ---> Output\n W = weight_variables([w_hidden[-1], w_output])\n b = bias_variables([w_output])\n h_fc_train = tf.nn.relu(tf.matmul(current_input_train, W) + b, name='Final_activation_train')\n h_fc_test = tf.nn.relu(tf.matmul(current_input_test, W) + b, name='Final_activation_test')\n prediction_train = tf.nn.softmax(h_fc_train, name='Prediction_train')\n prediction_test = tf.nn.softmax(h_fc_test, name='Prediction_test')\n\n ########################################################################\n # OP's for training\n ########################################################################\n with tf.name_scope('Loss'): # Cross-entropy loss\n loss = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction_train+1e-20) * class_factor,\n reduction_indices=[1]), name='loss')\n tf.summary.scalar('Loss/', loss)\n with tf.name_scope('Train'):\n train_step = tf.train.AdamOptimizer(5e-4, name='AdamOptimizer').minimize(loss, name='min_loss')\n\n ########################################################################\n # OP's for testing\n ########################################################################\n y_pred = tf.argmax(prediction_test, 1)\n y_true = tf.argmax(ys, 1)\n accuracy = tf.reduce_mean(tf.cast(tf.equal(y_pred, y_true), tf.float32), name='Accuracy')\n return (xs, ys), class_factor, x_shift, x_scale, kp, train_step, loss, prediction_test, accuracy, tf.train.Saver()\n\n\n'''\n3. Predict testing data\n'''\n\ndef nn_pred(model_tag, test_data):\n # Load model\n global train_gene, input_shift, input_scale, w_hidden, w_output\n train_gene, input_shift, input_scale, w_hidden, w_output = pickle.load(open('data/Input_parameter_'+model_tag+\".pickle\", \"rb\"))\n tf.reset_default_graph()\n global saver, graph, predition, xs, ys, x_shift, x_scale, kp\n saver = tf.train.import_meta_graph('./data/nn-save/' + model_tag + '/model.meta')\n graph = tf.get_default_graph()\n prediction = graph.get_tensor_by_name(\"Prediction_test:0\")\n xs = graph.get_tensor_by_name(\"xs:0\")\n ys = graph.get_tensor_by_name(\"ys:0\")\n x_shift = graph.get_tensor_by_name(\"x_shift:0\")\n x_scale = graph.get_tensor_by_name(\"x_scale:0\")\n kp = graph.get_tensor_by_name(\"kp:0\")\n # Restore values of graph\n global sess\n sess = tf.Session()\n sess.run(tf.global_variables_initializer())\n saver.restore(sess, './data/nn-save/' + model_tag + '/model')\n # Testing data\n test_x, _, test_y, _ = test_data\n # Make predictions\n keep_1 = [1]*len(w_hidden)\n feed = {xs: test_x,\n ys: test_y,\n x_shift: input_shift,\n x_scale: input_scale,\n kp:keep_1}\n preds = sess.run(prediction, feed_dict=feed)\n pred_label = np.argmax(preds, axis=1)\n return [preds, pred_label]\n\n'''\n4. Functions for training a network\n'''\ndef random_mini_batches(X, Y, mini_batch_size=64, seed=0):\n \"\"\"\n Creates a list of random minibatches from (X, Y)\n\n Arguments:\n X -- input data, of shape (number of examples, input size)\n Y -- true \"label\" of shape (number of examples, number of cell types)\n mini_batch_size - size of the mini-batches, integer\n seed -- so we can permutate mini-batch assignments.\n\n Returns:\n mini_batches -- list of synchronous (mini_batch_X, mini_batch_Y)\n \"\"\"\n\n m = X.shape[0] # number of training examples\n mini_batches = []\n np.random.seed(seed)\n\n # Step 1: Shuffle (X, Y)\n permutation = list(np.random.permutation(m))\n shuffled_X = X[permutation, :]\n shuffled_Y = Y[permutation, :]\n\n # Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case.\n num_complete_minibatches = math.floor(\n m / mini_batch_size) # number of mini batches of size mini_batch_size in your partitionning\n for k in range(0, num_complete_minibatches):\n mini_batch_X = shuffled_X[k * mini_batch_size: k * mini_batch_size + mini_batch_size, :]\n mini_batch_Y = shuffled_Y[k * mini_batch_size: k * mini_batch_size + mini_batch_size, :]\n mini_batch = (mini_batch_X, mini_batch_Y)\n mini_batches.append(mini_batch)\n\n # Handling the end case (last mini-batch < mini_batch_size)\n if m % mini_batch_size != 0:\n mini_batch_X = shuffled_X[num_complete_minibatches * mini_batch_size: m, :]\n mini_batch_Y = shuffled_Y[num_complete_minibatches * mini_batch_size: m, :]\n mini_batch = (mini_batch_X, mini_batch_Y)\n mini_batches.append(mini_batch)\n\n return mini_batches\n\n'''\n5. Functions for testing model performance\n'''\n\ndef tf_confusion_metrics(model, actual_classes, session, feed_dict, pos_cutoff=0.5):\n actuals = tf.argmax(actual_classes, 1)\n # predictions = tf.argmax(model, 1)\n predictions = tf.greater(model[:, 1], pos_cutoff)\n predictions = tf.cast(predictions, dtype=tf.int32)\n\n ones_like_actuals = tf.ones_like(actuals)\n zeros_like_actuals = tf.zeros_like(actuals)\n ones_like_predictions = tf.ones_like(predictions)\n zeros_like_predictions = tf.zeros_like(predictions)\n\n tp_op = tf.reduce_sum(\n tf.cast(\n tf.logical_and(\n tf.equal(actuals, ones_like_actuals),\n tf.equal(predictions, ones_like_predictions)\n ),\n \"float\"\n )\n )\n\n tn_op = tf.reduce_sum(\n tf.cast(\n tf.logical_and(\n tf.equal(actuals, zeros_like_actuals),\n tf.equal(predictions, zeros_like_predictions)\n ),\n \"float\"\n )\n )\n\n fp_op = tf.reduce_sum(\n tf.cast(\n tf.logical_and(\n tf.equal(actuals, zeros_like_actuals),\n tf.equal(predictions, ones_like_predictions)\n ),\n \"float\"\n )\n )\n\n fn_op = tf.reduce_sum(\n tf.cast(\n tf.logical_and(\n tf.equal(actuals, ones_like_actuals),\n tf.equal(predictions, zeros_like_predictions)\n ),\n \"float\"\n )\n )\n\n tp, tn, fp, fn = \\\n session.run(\n [tp_op, tn_op, fp_op, fn_op],\n feed_dict={}\n )\n\n tpr = float(tp) / (float(tp) + float(fn) + 10 ** (-10))\n fpr = float(fp) / (float(fp) + float(tn) + 10 ** (-10))\n\n accuracy = (float(tp) + float(tn)) / (float(tp) + float(fp) + float(fn) + float(tn) + 10 ** (-10))\n\n recall = tpr\n precision = float(tp) / (float(tp) + float(fp) + 10 ** (-10))\n\n f1_score = (2 * (precision * recall)) / (precision + recall + 10 ** (-10))\n\n print('Precision = ', precision)\n print('Recall = ', recall)\n print('F1 Score = ', f1_score)\n print('Accuracy = ', accuracy)\n\n return ([[tp, fp], [fn, tn]])\n\n","sub_path":"NN_utils.py","file_name":"NN_utils.py","file_ext":"py","file_size_in_byte":10517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"222946945","text":"from nlp_data_py import WikiDataset\nfrom nlp_data_py import Book, Splitter\n\nlanguages = ['ru', 'en', 'de', 'uk', 'be']\npages = {'ru': ['ABBYY', 'Яндекс', 'Google_(компания)', 'Microsoft', 'Apple', 'Mail.ru',\n 'Московский физико-технический институт', 'Эйлер,_Леонард', 'Россия', 'Германия', 'Великобритания',\n 'Украина', 'Европа', 'Соединённые_Штаты_Америки'],\n 'en': ['ABBYY', 'Yandex', 'Google', 'Microsoft', 'Apple', 'Mail.ru',\n 'Moscow_Institute_of_Physics_and_Technology', 'Leonhard_Euler', 'United_Kingdom',\n 'Germany', 'United_States'],\n 'de': ['ABBYY', 'Yandex', 'Google', 'Microsoft', 'Apple', 'Mail.ru',\n 'Moskauer_Institut_für_Physik_und_Technologie', 'Leonhard_Euler', 'Vereinigte_Staaten'],\n 'uk': ['ABBYY', 'Яндекс', 'Google', 'Microsoft', 'Московський_фізико-технічний_інститут', 'Леонард_Ейлер',\n 'Велика_Британія', 'Росія', 'Німеччина', 'Україна'],\n 'be': ['ABBYY', 'Яндэкс', 'Google', 'Microsoft', 'Маскоўскі_фізіка-тэхнічны_інстытут', 'Леанард_Эйлер',\n 'Расія', 'Германія', 'Украіна', 'Беларусь', 'Вялікабрытанія']}\n\nfor lang in languages:\n scanned_pickle = './data/wiki_' + str(lang) + '/scanned_' + str(lang) + '.pkl'\n save_dataset_path = './data/wiki_' + str(lang) + '/'\n\n book_def: Book = Book(chunk_splitter='(?<=[.!?]) +', chunks_per_page=2)\n splitter: Splitter = Splitter(split_ratios=[0.66, 0.33], dataset_names=[str(lang) + '_train', str(lang) + '_test'],\n shuffle=False)\n\n WikiDataset.create_dataset_from_wiki(lang=lang,\n seeds=pages.get(lang),\n match=\".*neuro\",\n recursive=True, limit=2,\n scanned_pickle=scanned_pickle,\n save_dataset_path=save_dataset_path,\n book_def=book_def,\n splitter=splitter)","sub_path":"data_collection.py","file_name":"data_collection.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"243235747","text":"import os\nimport sys\n\nclass Solution(object):\n def twoSum(self, nums, target):\n dNum = {}\n for i in range(len(nums)):\n num = nums[i]\n remain = target - num\n if remain in dNum:\n print [dNum[remain], i]\n else:\n dNum[num] = i\n #for i in range(len(nums)):\n # for j in range(i+1, len(nums)):\n # if nums[i] + nums[j] == target:\n # print [i, j]\n # sys.exit()\n\nnums = [2, 7, 11, 15]\ntarget = 9\n\nSolution().twoSum(nums, target)\n","sub_path":"twosum.py","file_name":"twosum.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"603639668","text":"from django.shortcuts import render, redirect, reverse, get_object_or_404\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\nfrom .models import Review\nfrom .forms import ReviewForm\nfrom toy.models import Toy\n\n\ndef index(request):\n reviews = Review.objects.all()\n\n return render(request, 'review/index.template.html', {\n 'reviews': reviews\n })\n\n\n@login_required\ndef create_review(request, toy_id):\n toy = get_object_or_404(Toy, pk=toy_id)\n\n if request.method == \"POST\":\n # fill in the form with what the user has typed in\n form = ReviewForm(request.POST)\n if form.is_valid():\n # save the form it will the create model instance\n # i.e it will insert the new row into the table in the database\n # when we specify Commit=False, means don't save to database\n review = form.save(commit=False)\n review.user = request.user # request.user contain logged in user\n review.toy = toy\n review.save()\n messages.success(request, \"New review added! \" + review.title)\n return redirect(index)\n else:\n form = ReviewForm()\n return render(request, 'review/create.template.html', {\n 'form': form,\n 'toy': toy\n })\n\n\n@login_required\ndef update_review(request, review_id):\n # 1. retrieve the review which we are editing\n review_being_updated = get_object_or_404(Review, pk=review_id)\n\n # 2 - create the form and fill it with data from review instance\n if request.method == \"POST\":\n review_form = ReviewForm(request.POST, instance=review_being_updated)\n\n # 3. create the form and fill in the user's data. Also specify that\n # this is to update an existing model (the instance argument)\n if review_form.is_valid():\n review_form.save()\n return redirect(reverse(index))\n\n else:\n return render(request, 'review/update.template.html', {\n \"form\": review_form,\n \"review\": review_being_updated\n })\n else:\n # 4. create a form with the review details filled in\n review_form = ReviewForm(instance=review_being_updated)\n\n return render(request, 'review/update.template.html', {\n \"form\": review_form,\n \"review\": review_being_updated\n })\n\n\n@login_required\ndef delete_review(request, review_id):\n\n if request.method == 'POST':\n review_to_delete = get_object_or_404(Review, pk=review_id)\n review_to_delete.delete()\n return redirect(index)\n else:\n review_to_delete = get_object_or_404(Review, pk=review_id)\n return render(request, 'review/delete.template.html', {\n \"review\": review_to_delete\n })\n","sub_path":"review/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"84751385","text":"''' \r\nImplementation of Evolutionary Algorithm with Numerical differentiation (EAND) in Python\r\n \r\nArticle: Soft Sensors Design in a Petrochemical Process using an Evolutionary Algorithm \r\nJournal: Measurement\r\nYear: 2019\r\n\r\nDeveloper: Gustavo A. P. de Morais\r\nContact Info: gustavo_gapm@usp.br, gustavo_gapm@hotmail.com\r\n\r\nReturns the values from the local selection procedure to the main population\r\n'''\r\n\r\nimport numpy as np\r\n\r\ndef eand_final_selection(X, Y, Xh, Yh, nPop, nPop2, ndv) :\r\n \r\n # Initialization \r\n P = np.zeros((nPop + nPop2,ndv),dtype=int)\r\n C = np.zeros((nPop + nPop2,1),dtype=float)\r\n indice = np.zeros((nPop,1),dtype=int)\r\n \r\n # All individuals are ranked together according to their fitness value\r\n for i in range(nPop) :\r\n P[i] = X[i]\r\n C[i] = Y[i]\r\n for i in range(nPop2) :\r\n P[nPop+i] = Xh[i]\r\n C[nPop+i] = Yh[i]\r\n \r\n indice = [i[0] for i in sorted(enumerate(C), key=lambda x:x[1])]\r\n \r\n # The fittest individuals are randomly returned\r\n m = np.random.permutation(range(nPop))\r\n m = m + nPop2\r\n \r\n # New ordenation\r\n for i in range(nPop) :\r\n X[i] = P[indice[m[i]]].copy() \r\n Y[i] = C[indice[m[i]]]\r\n \r\n return X, Y\r\n\r\n","sub_path":"EAND Python/Maximization problem/Integer variables/eand_final_selection.py","file_name":"eand_final_selection.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"144353636","text":"#! python3\nimport pyautogui\nfrom os import listdir\n\nfiles = listdir(r\"C:\\Users\\pandasr\\Dropbox\\programming\\pythonStuff\\decklists\") #get absolute directory of decklists\n\nfor file in files: #print deck list from directory\n if file.endswith(\".txt\"):\n print (file[:-4])\n\nchooseDeck = input(\"what deck do you want to build?\")\n\nwhile not \"{}.txt\".format(chooseDeck) in files: #check if user input is correct\n chooseDeck = input(\"Deck does not exist. Choose again.\")\n\ndeck = open(r\"C:\\Users\\pandasr\\Dropbox\\programming\\pythonStuff\\decklists\\{}.txt\".format(chooseDeck))\n\ndeckList = deck.read().split(\"\\n\")\n\nfor card in deckList:\n if card == \"stalagg\":\n #Exceptions for cards that appears on second position\n pyautogui.moveTo(932, 946, duration=0.15)\n pyautogui.click()\n pyautogui.typewrite(str(card))\n pyautogui.press(\"enter\")\n pyautogui.moveTo(600, 355, duration=0.15)\n pyautogui.click()\n elif card.isspace():\n pass\n else:\n pyautogui.moveTo(932, 946, duration=0.15)\n pyautogui.click()\n pyautogui.typewrite(str(card))\n pyautogui.press(\"enter\")\n pyautogui.moveTo(399, 355, duration=0.15)\n pyautogui.click()\n\nclose(\"{}.txt\".format(chooseDeck))\n","sub_path":"deckBuilder.py","file_name":"deckBuilder.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"79377259","text":"from rest_framework import views\n\nfrom rest_framework.exceptions import ValidationError\nfrom core.models import Employee\nfrom django.http.response import JsonResponse\n\n\nclass EmployeeView(views.APIView):\n\n def patch(self, request, *args, **kwargs):\n employee_rid = request.data.get('employee_rid', None)\n kyc = request.data.get('kyc', None)\n if not employee_rid:\n raise ValidationError({\"status\": \"False\", \"message\": \"RID required\"})\n emp_obj = Employee.objects.filter(rid=employee_rid, deleted_at=None).first()\n if not emp_obj:\n raise ValidationError({\n \"status\": \"False\", \"message\": \"Employee Does not Exists\"})\n\n emp_obj.kyc = kyc\n emp_obj.save()\n return JsonResponse({\"status\": \"True\", \"message\": \"Kyc updated successfully\"})\n","sub_path":"api/v1/services/kyc/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"370381804","text":"import sys\nsys.path.append('../queue_and_stack')\nfrom dll_queue import Queue\nfrom dll_stack import Stack\n\n\nclass BinarySearchTree:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n # Insert the given value into the tree\n def insert(self, value):\n if value > self.value: # then it belongs on the right\n if self.right is None: # so if there is room on the right\n self.right = BinarySearchTree(value) # extend a branch there\n else: # but if there isn't room\n self.right.insert(value) # move right and try again\n elif value < self.value: # then it belongs on the left\n if self.left is None: # so if there is room on the left\n self.left = BinarySearchTree(value) # extend a branch there\n else: # but if there isn't room\n self.left.insert(value) # move left and try again\n \n # Return True if the tree contains the value\n # False if it does not\n def contains(self, target):\n if target == self.value: # if this is the target we're looking for\n return True # success!\n elif target > self.value: # then it belongs on the right\n if self.right is None: # so if there isn't anything on the right\n return False # it isn't there\n else: # but if there is stuff on the right\n return self.right.contains(target) # check the right\n elif target < self.value: # then it belongs on the left\n if self.left is None: # so if there isn't anything on the left\n return False # it isn't there\n else: # but if there is stuff on the left\n return self.left.contains(target) # check the left\n\n # Return the maximum value found in the tree\n def get_max(self):\n if self.right is None: # if there's nothing to the right\n return self.value # this is the maximum value\n else: # but if there is something to the right\n return self.right.get_max() # it's on the right, so check there\n\n # Call the function `cb` on the value of each node\n # You may use a recursive or iterative approach\n def for_each(self, cb):\n cb(self.value) # call the function cb for the current value\n if self.right is not None: # and if there's anything to the right\n self.right.for_each(cb) # apply this for_each function to the right\n if self.left is not None: # and if there's anything to the left\n self.left.for_each(cb) # apply this for_each function to the left\n \n # DAY 2 Project -----------------------\n\n # Print all the values in order from low to high\n # Hint: Use a recursive, depth first traversal\n def in_order_print(self, node):\n if node is None: # if we're not at a node\n return # there's nothing to print, so return\n else: # otherwise, if we are at a node\n self.in_order_print(node.left) # go as far along the left as we can\n print(node.value) # and print the value we find\n self.in_order_print(node.right) # nowhere else on left, so go right\n\n # Print the value of every node, starting with the given node,\n # in an iterative breadth first traversal\n def bft_print(self, node):\n queue = Queue()\n queue.enqueue(node)\n while queue.len() > 0:\n current_node = queue.dequeue()\n print(current_node.value)\n if current_node.right is not None:\n queue.enqueue(current_node.right)\n if current_node.left is not None:\n queue.enqueue(current_node.left)\n\n # Print the value of every node, starting with the given node,\n # in an iterative depth first traversal\n def dft_print(self, node):\n stack = Stack()\n stack.push(node)\n while stack.len() > 0:\n current_node = stack.pop()\n print(current_node.value)\n if current_node.right is not None:\n stack.push(current_node.right)\n if current_node.left is not None:\n stack.push(current_node.left)\n\n # STRETCH Goals -------------------------\n # Note: Research may be required\n\n # Print In-order recursive DFT\n def pre_order_dft(self, node):\n pass\n\n # Print Post-order recursive DFT\n def post_order_dft(self, node):\n pass\n","sub_path":"binary_search_tree/binary_search_tree.py","file_name":"binary_search_tree.py","file_ext":"py","file_size_in_byte":4446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"137620534","text":"from obj.psr import ProductServiceRequest\r\nfrom obj.psr_field import ProductServiceRequestField\r\n\r\nfrom PyQt4 import QtCore, QtGui\r\n\r\nimport widget.finale.asset.icons_rc\r\n\r\nclass PSRRawDataTableViewModel(QtCore.QAbstractTableModel):\r\n def __init__(self, parent=None):\r\n super(PSRRawDataTableViewModel, self).__init__(parent)\r\n \r\n self.psrs = []\r\n self.filtered_indexes = []\r\n \r\n def columnCount(self, parent):\r\n if len(self.psrs) == 0:\r\n return 0\r\n elif len(self.psrs) == 1:\r\n return 2\r\n else:\r\n return len(self.psrs)\r\n \r\n def rowCount(self, parent):\r\n if len(self.psrs) == 0: return 0\r\n else:\r\n return len(self.filtered_indexes)\r\n \r\n def data(self, index, role = QtCore.Qt.DisplayRole):\r\n if not index.isValid(): return None\r\n \r\n if len(self.psrs) == 1:\r\n if (index.column(), role) == (0, QtCore.Qt.DisplayRole):\r\n data = self.psrs[0].fields[self.filtered_indexes[index.row()]].current_data\r\n return QtCore.QString(data) if data is not None else ''\r\n \r\n if (index.column(), role) == (1, QtCore.Qt.DisplayRole):\r\n data = self.psrs[0].fields[self.filtered_indexes[index.row()]].new_data\r\n return QtCore.QString(data) if data is not None else ''\r\n \r\n if (index.column(), role) == (1, QtCore.Qt.EditRole):\r\n data = self.psrs[0].fields[self.filtered_indexes[index.row()]].new_data\r\n return QtCore.QString(data) if data is not None else ''\r\n \r\n if (index.column(), role) == (1, QtCore.Qt.DecorationRole):\r\n data = self.psrs[0].fields[self.filtered_indexes[index.row()]].new_data\r\n if data is not None:\r\n return QtGui.QPixmap(\":icon/pencil.png\")\r\n \r\n if len(self.psrs) > 1:\r\n if role == QtCore.Qt.DisplayRole:\r\n return QtCore.QString(self.psrs[index.column()].fields[self.filtered_indexes[index.row()]].current_data)\r\n \r\n return None\r\n \r\n def headerData(self, section, orientation, role = QtCore.Qt.DisplayRole):\r\n horizontal_headers = ['Current Data', 'New Data']\r\n \r\n if len(self.psrs) == 1:\r\n if (role, orientation) == (QtCore.Qt.DisplayRole, QtCore.Qt.Horizontal):\r\n return horizontal_headers[section]\r\n \r\n if (role, orientation) == (QtCore.Qt.DisplayRole, QtCore.Qt.Vertical):\r\n return self.psrs[0].fields[self.filtered_indexes[section]].display_name\r\n \r\n if len(self.psrs) > 1:\r\n if (role, orientation) == (QtCore.Qt.DisplayRole, QtCore.Qt.Horizontal):\r\n return self.psrs[section].psr_number\r\n \r\n if (role, orientation) == (QtCore.Qt.DisplayRole, QtCore.Qt.Vertical):\r\n return self.psrs[0].fields[self.filtered_indexes[section]].display_name\r\n \r\n if (role, orientation) == (QtCore.Qt.TextAlignmentRole, QtCore.Qt.Horizontal):\r\n return QtCore.Qt.AlignLeft\r\n \r\n if (role, orientation) == (QtCore.Qt.TextAlignmentRole, QtCore.Qt.Vertical):\r\n return QtCore.Qt.AlignRight | QtCore.Qt.AlignTop\r\n \r\n return QtCore.QAbstractTableModel.headerData(self, section, orientation, role)\r\n \r\n def flags(self, index):\r\n if len(self.psrs) == 1:\r\n if index.column() == 1:\r\n if self.psrs[0].fields[self.filtered_indexes[index.row()]].write_element_type != 'Invalid / Not editable':\r\n return QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled\r\n else:\r\n return QtCore.Qt.ItemIsEnabled\r\n else:\r\n return QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled\r\n \r\n if len(self.psrs) > 1:\r\n return QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled\r\n \r\n def setData(self, index, value, role = QtCore.Qt.EditRole):\r\n if index.column() == 1 and role == QtCore.Qt.EditRole:\r\n self.psrs[0].fields[self.filtered_indexes[index.row()]].new_data = value\r\n self.dataChanged.emit(index, index)\r\n return True\r\n return False","sub_path":"widget/finale/obj/psr_raw_data_table_view_model.py","file_name":"psr_raw_data_table_view_model.py","file_ext":"py","file_size_in_byte":4362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"172508522","text":"import os\nimport datetime\nimport boto3\nfrom botocore.client import Config\n\nclient = boto3.client('s3', config=Config(signature_version='s3v4'))\n\nAWS_ACCESS_KEY_ID = os.getenv('ACCESS_KEY_ID')\nAWS_SECRET_ACCESS_KEY = os.getenv('SECRET_ACCESS_KEY')\nAWS_FILE_EXPIRE = 200\nAWS_PRELOAD_METADATA = True\nAWS_QUERYSTRING_AUTH = True\n\nDEFAULT_FILE_STORAGE = 'chronus.aws.utils.MediaRootS3BotoStorage'\nSTATICFILES_STORAGE = 'chronus.aws.utils.StaticRootS3BotoStorage'\nAWS_STORAGE_BUCKET_NAME = 'chronus-bucket'\nS3DIRECT_REGION = 'eu-west-3'\nS3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME\nMEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME\nMEDIA_ROOT = MEDIA_URL\nSTATIC_URL = S3_URL + 'static/'\nADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'\n\ntwo_months = datetime.timedelta(days=61)\ndate_two_months_later = datetime.date.today() + two_months\nexpires = date_two_months_later.strftime(\"%A, %d %B %Y 20:00:00 GMT\")\n\nAWS_HEADERS = { \n 'Expires': expires,\n 'Cache-Control': 'max-age=%d' % (int(two_months.total_seconds()), ),\n}","sub_path":"chronus/aws/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"560029510","text":"# -*- encoding: utf-8 -*-\n#\n# Copyright © 2020—2021 Mergify SAS\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 unittest import mock\n\nfrom mergify_engine import check_api\nfrom mergify_engine import github_types\nfrom mergify_engine.tests.unit import conftest\n\n\nasync def test_summary_synchronization_cache(\n context_getter: conftest.ContextGetterFixture,\n) -> None:\n async def items(*args, **kwargs):\n if False:\n yield\n return\n\n async def post_check(*args, **kwargs):\n return mock.Mock(\n status_code=200,\n json=mock.Mock(\n return_value=github_types.GitHubCheckRun(\n {\n \"head_sha\": \"ce587453ced02b1526dfb4cb910479d431683101\",\n \"details_url\": \"https://example.com\",\n \"status\": \"completed\",\n \"conclusion\": \"neutral\",\n \"name\": \"neutral\",\n \"id\": 1236,\n \"app\": {\n \"id\": 1234,\n \"name\": \"CI\",\n \"owner\": {\n \"type\": \"User\",\n \"id\": 1234,\n \"login\": \"goo\",\n \"avatar_url\": \"https://example.com\",\n },\n },\n \"external_id\": \"\",\n \"pull_requests\": [],\n \"before\": \"4eef79d038b0327a5e035fd65059e556a55c6aa4\",\n \"after\": \"4eef79d038b0327a5e035fd65059e556a55c6aa4\",\n \"started_at\": \"\",\n \"completed_at\": \"\",\n \"html_url\": \"https://example.com\",\n \"check_suite\": {\"id\": 1234},\n \"output\": {\n \"summary\": \"\",\n \"title\": \"It runs!\",\n \"text\": \"\",\n \"annotations\": [],\n \"annotations_count\": 0,\n \"annotations_url\": \"https://example.com\",\n },\n }\n )\n ),\n )\n\n client = mock.AsyncMock()\n client.auth.get_access_token.return_value = \"\"\n client.items = items\n client.post.side_effect = post_check\n\n ctxt = await context_getter(github_types.GitHubPullRequestNumber(6))\n ctxt.repository.installation.client = client\n assert await ctxt.get_cached_last_summary_head_sha() is None\n await ctxt.set_summary_check(\n check_api.Result(check_api.Conclusion.SUCCESS, \"foo\", \"bar\")\n )\n\n assert await ctxt.get_cached_last_summary_head_sha() == \"the-head-sha\"\n await ctxt.clear_cached_last_summary_head_sha()\n\n assert await ctxt.get_cached_last_summary_head_sha() is None\n","sub_path":"mergify_engine/tests/unit/test_synchronize.py","file_name":"test_synchronize.py","file_ext":"py","file_size_in_byte":3426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"428174453","text":"import numpy as np\nimport cv2\nimport os\nimport json\nfrom input_dir import INPUT_DIR\n\n\n\ndef create_images_SfM_folder(image_base_name, extension=\"jpg\", stride=1):\n '''\n If non existant this function will create a folder INPUT_DIR/../images_SfM\n This folder will contain the 104 first images of INPUT_DIR\n The first input of this function is the base name of the images in INPUT_DIR and the extension\n Eg: if the images are like Tool1.jpg, Tool2.jpg ... then the base name is Tool\n The second input is the step between two successive images\n Eg: if the images are like Tool1.jpg, Tool2.jpg ... and the stride is 10\n Then the selected images will be Tool1.jpg, Tool11.jp, Tool21.jpg ...\n '''\n print(\"Taking the 104 first images to perform Structure from Motion\\n\\n\")\n images_SfM_dir = os.path.join(INPUT_DIR, '../images_SfM')\n if not os.path.exists(images_SfM_dir):\n os.mkdir(images_SfM_dir)\n count = 0\n i = 0\n while count<104 and (i+stride)= k. Returns\n overlap length 0 if there are no such overlaps.\"\"\"\n reada, readb = None, None\n best_olen = 0\n for a, b in itertools.permutations(reads, 2):\n olen = overlap(a, b, min_length=k)\n if olen > best_olen:\n reada, readb = a, b\n best_olen = olen\n return reada, readb, best_olen\n\n\ndef smart_greedy_scs(reads, k):\n \"\"\" Greedy shortest-common-superstring merge.\n Repeat until no edges (overlaps of length >= k)\n remain. \"\"\"\n pairs_olen, pairs_count = smart_overlap_map(reads, k)\n sorted_pairs_olen = sorted(pairs_olen.items(), key=operator.itemgetter(1), reverse=True)\n read_a, read_b, olen = sorted_pairs_olen[0][0][0], sorted_pairs_olen[0][0][1], sorted_pairs_olen[0][1]\n while olen > 0:\n reads.remove(read_a)\n reads.remove(read_b)\n reads.append(read_a + read_b[olen:])\n pairs_olen, pairs_count = smart_overlap_map(reads, k)\n if pairs_olen != {}:\n sorted_pairs_olen = sorted(pairs_olen.items(), key=operator.itemgetter(1), reverse=True)\n read_a, read_b, olen = sorted_pairs_olen[0][0][0], sorted_pairs_olen[0][0][1], sorted_pairs_olen[0][1]\n else:\n read_a, read_b, olen = pick_maximal_overlap(reads, k)\n return ''.join(reads)\n\n\nif __name__ == '__main__':\n # Question 1, 2\n shortest_sup_list = revised_scs(['CCT', 'CTT', 'TGC', 'TGG', 'GAT', 'ATT'])\n print(\"Length of the shortest common superstring:\", len(shortest_sup_list[0]))\n print(\"How many different shortest common superstrings:\", len(shortest_sup_list))\n\n # Question 3, 4\n reads_filename = 'ads1_week4_reads.fastq'\n fastq_reads, _ = readFastq(reads_filename)\n\n genome = smart_greedy_scs(fastq_reads, 10)\n print(len(genome))\n print(genome.count('A'))\n print(genome.count('T'))\n","sub_path":"Genomic_Algorithms/Algorithm4_assemble.py","file_name":"Algorithm4_assemble.py","file_ext":"py","file_size_in_byte":4488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"477791126","text":"# -*-coding:Latin-1 -*\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mlmodule.mlmodule import ML\n\nclass TP1() :\n\n def __init__(self):\n return\n\n def q1(self):\n \"\"\"\n Draw two gaussian distributions g1, g2,\n g1 :\n - mean = [0,2]\n - cov = [[0.9, 0.4],[0.4, 0.3]]\n - n = 500\n g2 :\n - mean = [2,3]\n - cov = [[0.2, 0.8],[0.2, 1]]\n - n = 200\n \"\"\"\n ml = ML()\n g1 = ml.mvnrnd( [0,2] , [[0.9, 0.4],[0.4, 0.3]] , 500 )\n g2 = ml.mvnrnd( [2,3] , [[0.2, 0.8],[0.2, 1.0]] , 200 )\n\n fig = plt.figure()\n fig.suptitle('Gaussian distributions')\n\n x_1, y_1 = g1\n plt.plot(x_1, y_1, 'x', label=\"n : 500\")\n\n x_2, y_2 = g2\n plt.plot(x_2, y_2, 'o', label=\"n : 200\")\n\n plt.legend(loc='upper left')\n plt.axis('equal')\n plt.show()\n\n def q2(self) :\n \"\"\"\n In 200 times loop :\n - Generate n points from gaussian distribution X\n - Get the MLE estimation of mean from X\n - Store in err[] the L1-norm of estimation - theorical mean\n Plot err\n \"\"\"\n ml = ML()\n err = []\n mean = [1,2]\n cov = [ [1,0] , [0,0] ]\n\n for n in range(1, 201):\n X = ml.mvnrnd(mean, cov, n)\n [m, c] = ml.mlegauss(X)\n\n diff = np.array(m) - np.array(mean)\n err.append(diff.tolist())\n\n x, y = [ [i[0] for i in err], [i[1] for i in err] ]\n\n plt.plot(x, y, 'x',)\n plt.axis('equal')\n plt.show()\n","sub_path":"TP1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"137599755","text":"# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance\n# with the License. A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES\n# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and\n# limitations under the License.\nimport pytest\nfrom assertpy import assert_that\nfrom compute_fleet_status import get_status_with_last_updated_time, update_status_with_last_updated_time\n\n\n@pytest.mark.parametrize(\n \"no_error\",\n [True, False],\n)\ndef test_get_status_with_last_updated_time(no_error, mocker, capsys):\n if no_error:\n mocker.patch(\n \"compute_fleet_status.get_dynamo_db_data\",\n return_value={\"lastStatusUpdatedTime\": \"2022-01-14T04:40:47.653Z\", \"status\": \"PROTECTED\"},\n )\n else:\n mocker.patch(\n \"compute_fleet_status.get_dynamo_db_data\",\n side_effect=Exception(\"Failed when retrieving data from DynamoDB with error\"),\n )\n\n try:\n get_status_with_last_updated_time(\"table\", \"us-east-1\")\n readouterr = capsys.readouterr()\n assert_that(readouterr.out).contains(\n '{\\n \"lastStatusUpdatedTime\": \"2022-01-14T04:40:47.653Z\",\\n \"status\": \"PROTECTED\"\\n}\\n'\n )\n except Exception as e:\n assert_that(e.args[0]).contains(\"Failed when retrieving data from DynamoDB with error\")\n\n\n@pytest.mark.parametrize(\n \"current_status\",\n [\n \"PROTECTED\",\n \"RUNNING\",\n \"STOPPED\",\n ],\n)\ndef test_update_status_with_last_updated_time(current_status, mocker):\n mocker.patch(\n \"compute_fleet_status.get_dynamo_db_data\",\n return_value={\"lastStatusUpdatedTime\": \"2022-01-14T04:40:47.653Z\", \"status\": current_status},\n )\n update_item_mock = mocker.patch(\"compute_fleet_status.update_item\")\n\n try:\n update_status_with_last_updated_time(\"table\", \"us-east-1\", \"PROTECTED\")\n if current_status == \"PROTECTED\":\n update_item_mock.assert_not_called()\n else:\n update_item_mock.assert_called_once()\n except Exception as e:\n assert_that(e.args[0]).contains(\n \"Failed when updating fleet status with error: Could not update compute fleet status from 'STOPPED' \"\n \"to PROTECTED.\"\n )\n","sub_path":"test/unit/compute_fleet_status/test_compute_fleet_status.py","file_name":"test_compute_fleet_status.py","file_ext":"py","file_size_in_byte":2545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"233951962","text":"# Version log:\n# v1.0 initial version created.\n# v1.1 removed depreciated scipy.imread, added skimage, imageio to read input\n\n\nimport os\nimport scipy\nfrom glob import glob\nimport numpy as np\nfrom skimage import transform\nfrom config import *\n# import imageio\n\n\ndef transform_image(path):\n\t# print(\"reading {}\".format(path))\n\t# removed in v1.1\n\timage = scipy.misc.imread(path).astype(np.float)\n\treturn np.array(image)/127.5 - 1\n\t# cropped_image = scipy.misc.imresize(image, [256, 256])\n\t# image = imageio.imread(path, as_gray=False) \n\t# cropped_image = transform.resize(image, (256,256), preserve_range=True, mode='constant')\n\t# return np.array(cropped_image)/127.5 - 1 #normalization\n\ndef inverse_transform_image(data):\n\tdata = np.clip(data, -1, 1)\n\toutput = np.array((data+1.) * 127.5, dtype='uint8')\n\treturn output\n\ndef merge_images(images, size):\n\theigh, width = images.shape[1], images.shape[2]\n\timg = np.zeros((heigh * size[0], width * size[1], 3))\n\tfor index, image in enumerate(images):\n\t\ti = index% size[1]\n\t\tj = index // size[1]\n\t\timg[j * heigh:j * heigh + heigh, i * width:i * width + width, :] = image\n\treturn img\n\n############# the functions below are exported #############\n\ndef init_style_dict(path): #path = './data/**/'\n\tlabel_dict = {}\n\tstyle_folders = glob(path, recursive=True)[1:]\n\tfor index, path in enumerate(style_folders):\n\t\tclass_name = path.split('/')[-2]\n\t\tlabel_dict[class_name] = index\n\tprint(label_dict)\n\treturn label_dict\n\ndef get_images_path(path, filename_pattern): #dir = './data' pattern = '*/*.jpg'\n\treturn glob(os.path.join(path, filename_pattern))\n\ndef get_images(sample_files):\n\tsamples = [transform_image(sample_file) for sample_file in sample_files]\n\tsamples = np.array(samples).astype(np.float32)\n\treturn samples\n\ndef get_images_label(images_path, label_dict):\n\tret = []\n\tfor path in images_path:\n\t\tlabel_str = path.split('/')\n\t\tret.append(np.eye(class_)[np.array(label_dict[label_str[-2]])])\n\treturn ret\n\ndef save_images(images, size, images_path):\n\tconverted_ = inverse_transform_image(images)\n\t# merged_ = merge_images(converted_, size)\n\timage = np.squeeze(merge_images(converted_, size))\n\t# imageio.imwrite(images_path, image)\n\tscipy.misc.imsave(images_path, image)\n","sub_path":"phase1/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"31098616","text":"import warnings\nfrom abc import ABC, abstractmethod\n\nimport cv2\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\nfrom sklearn.exceptions import NotFittedError\nfrom sklearn.preprocessing import StandardScaler\n\nfrom ..wdtypes import *\nfrom ..utils.text_utils import (\n get_texts,\n pad_sequences,\n build_embeddings_matrix,\n)\nfrom ..utils.dense_utils import LabelEncoder\nfrom ..utils.image_utils import SimplePreprocessor, AspectAwarePreprocessor\nfrom ..utils.fastai_transforms import Vocab\n\n\nclass BasePreprocessor(ABC):\n \"\"\"Base Abstract Class of All Preprocessors.\"\"\"\n\n @abstractmethod\n def __init__(self, *args):\n pass\n\n @abstractmethod\n def fit(self, df: pd.DataFrame):\n raise NotImplementedError(\"Preprocessor must implement this method\")\n\n @abstractmethod\n def transform(self, df: pd.DataFrame):\n raise NotImplementedError(\"Preprocessor must implement this method\")\n\n @abstractmethod\n def fit_transform(self, df: pd.DataFrame):\n raise NotImplementedError(\"Preprocessor must implement this method\")\n\n\nclass WidePreprocessor(BasePreprocessor):\n r\"\"\"Preprocessor to prepare the wide input dataset\n\n This Preprocessor prepares the data for the wide, linear component. This\n linear model is implemented via an Embedding layer that is connected to\n the output neuron. ``WidePreprocessor`` simply numerically encodes all the\n unique values of all categorical columns ``wide_cols + crossed_cols``. See\n the Example below.\n\n Parameters\n ----------\n wide_cols: List[str]\n List with the name of the columns that will label encoded and passed\n through the Wide model\n crossed_cols: List[Tuple[str, str]]\n List of Tuples with the name of the columns that will be `'crossed'`\n and then label encoded. e.g. [('education', 'occupation'), ...]\n\n Attributes\n ----------\n wide_crossed_cols: :obj:`List`\n List with the names of all columns that will be label encoded\n feature_dict: :obj:`Dict`\n Dictionary where the keys are the result of pasting `colname + '_' +\n column value` and the values are the corresponding mapped integer.\n\n Examples\n --------\n >>> import pandas as pd\n >>> from pytorch_widedeep.preprocessing import WidePreprocessor\n >>> df = pd.DataFrame({'color': ['r', 'b', 'g'], 'size': ['s', 'n', 'l']})\n >>> wide_cols = ['color']\n >>> crossed_cols = [('color', 'size')]\n >>> wide_preprocessor = WidePreprocessor(wide_cols=wide_cols, crossed_cols=crossed_cols)\n >>> X_wide = wide_preprocessor.fit_transform(df)\n >>> X_wide\n array([[1, 4],\n [2, 5],\n [3, 6]])\n >>> wide_preprocessor.feature_dict\n {'color_r': 1, 'color_b': 2, 'color_g': 3, 'color_size_r-s': 4, 'color_size_b-n': 5, 'color_size_g-l': 6}\n >>> wide_preprocessor.inverse_transform(X_wide)\n color color_size\n 0 r r-s\n 1 b b-n\n 2 g g-l\n \"\"\"\n\n def __init__(\n self,\n wide_cols: List[str],\n crossed_cols=None,\n ):\n super(WidePreprocessor, self).__init__()\n self.wide_cols = wide_cols\n self.crossed_cols = crossed_cols\n\n def fit(self, df: pd.DataFrame) -> BasePreprocessor:\n \"\"\"Fits the Preprocessor and creates required attributes\"\"\"\n df_wide = self._prepare_wide(df)\n self.wide_crossed_cols = df_wide.columns.tolist()\n vocab = self._make_global_feature_list(df_wide[self.wide_crossed_cols])\n # leave 0 as padding index\n self.feature_dict = {v: i + 1 for i, v in enumerate(vocab)}\n return self\n\n def transform(self, df: pd.DataFrame) -> np.array:\n r\"\"\"Returns the processed dataframe\"\"\"\n try:\n self.feature_dict\n except AttributeError:\n raise NotFittedError(\n \"This WidePreprocessor instance is not fitted yet. \"\n \"Call 'fit' with appropriate arguments before using this estimator.\"\n )\n df_wide = self._prepare_wide(df)\n encoded = np.zeros([len(df_wide), len(self.wide_crossed_cols)], dtype=np.long)\n for col_i, col in enumerate(self.wide_crossed_cols):\n encoded[:, col_i] = df_wide[col].apply(\n lambda x: self.feature_dict[col + \"_\" + str(x)]\n if col + \"_\" + str(x) in self.feature_dict\n else 0\n )\n return encoded.astype(\"int64\")\n\n def inverse_transform(self, encoded: np.ndarray) -> pd.DataFrame:\n r\"\"\"Takes as input the output from the ``transform`` method and it will\n return the original values.\n\n Parameters\n ----------\n encoded: np.ndarray\n array with the output of the ``transform`` method\n \"\"\"\n decoded = pd.DataFrame(encoded, columns=self.wide_crossed_cols)\n inverse_dict = {k: v for v, k in self.feature_dict.items()}\n decoded = decoded.applymap(lambda x: inverse_dict[x])\n for col in decoded.columns:\n rm_str = \"\".join([col, \"_\"])\n decoded[col] = decoded[col].apply(lambda x: x.replace(rm_str, \"\"))\n return decoded\n\n def fit_transform(self, df: pd.DataFrame) -> np.ndarray:\n \"\"\"Combines ``fit`` and ``transform``\"\"\"\n return self.fit(df).transform(df)\n\n def _make_global_feature_list(self, df: pd.DataFrame) -> List:\n vocab = []\n for column in df.columns:\n vocab += self._make_column_feature_list(df[column])\n return vocab\n\n def _make_column_feature_list(self, s: pd.Series) -> List:\n return [s.name + \"_\" + str(x) for x in s.unique()]\n\n def _cross_cols(self, df: pd.DataFrame):\n df_cc = df.copy()\n crossed_colnames = []\n for cols in self.crossed_cols:\n cols = list(cols)\n for c in cols:\n df_cc[c] = df_cc[c].astype(\"str\")\n colname = \"_\".join(cols)\n df_cc[colname] = df_cc[cols].apply(lambda x: \"-\".join(x), axis=1)\n crossed_colnames.append(colname)\n return df_cc[crossed_colnames]\n\n def _prepare_wide(self, df: pd.DataFrame):\n if self.crossed_cols is not None:\n df_cc = self._cross_cols(df)\n return pd.concat([df[self.wide_cols], df_cc], axis=1)\n else:\n return df.copy()[self.wide_cols]\n\n\nclass DensePreprocessor(BasePreprocessor):\n r\"\"\"Preprocessor to prepare the deepdense input dataset\n\n Parameters\n ----------\n embed_cols: List[Union[str, Tuple[str, int]]]\n List containing the name of the columns that will be represented by\n embeddings or a Tuple with the name and the embedding dimension. e.g.:\n [('education',32), ('relationship',16)\n continuous_cols: List[str]\n List with the name of the so called continuous cols\n scale: bool\n Bool indicating whether or not to scale/Standarise continuous cols.\n Should \"almost always\" be True.\n default_embed_dim: Int, Default=8\n Dimension for the embeddings used in the Deep-Dense model\n already_standard: List[str], Optional,\n List with the name of the continuous cols that do not need to be\n Standarised.\n\n Attributes\n ----------\n label_encoder: :obj:`LabelEncoder`\n see :class:`pytorch_widedeep.utils.dense_utils.LabelEncder`\n embed_cols: :obj:`List`\n List with the columns that will be represented by embeddings\n embed_dim: :obj:`Dict`\n Dictionary where keys are the embed cols and values are the embed\n dimensions\n standardize_cols: :obj:`List`\n List of the columns that will be standarized\n deep_column_idx: :obj:`Dict`\n Dictionary where keys are column names and values are column indexes.\n This will be neccesary to slice tensors\n scaler: :obj:`StandardScaler`\n an instance of :class:`sklearn.preprocessing.StandardScaler`\n\n Examples\n --------\n >>> import pandas as pd\n >>> from pytorch_widedeep.preprocessing import DensePreprocessor\n >>> df = pd.DataFrame({'color': ['r', 'b', 'g'], 'size': ['s', 'n', 'l'], 'age': [25, 40, 55]})\n >>> embed_cols = [('color',5), ('size',5)]\n >>> cont_cols = ['age']\n >>> deep_preprocessor = DensePreprocessor(embed_cols=embed_cols, continuous_cols=cont_cols)\n >>> deep_preprocessor.fit_transform(df)\n array([[ 0. , 0. , -1.22474487],\n [ 1. , 1. , 0. ],\n [ 2. , 2. , 1.22474487]])\n >>> deep_preprocessor.embed_dim\n {'color': 5, 'size': 5}\n >>> deep_preprocessor.deep_column_idx\n {'color': 0, 'size': 1, 'age': 2}\n \"\"\"\n\n def __init__(\n self,\n embed_cols: List[Union[str, Tuple[str, int]]] = None,\n continuous_cols: List[str] = None,\n scale: bool = True,\n default_embed_dim: int = 8,\n already_standard: Optional[List[str]] = None,\n ):\n super(DensePreprocessor, self).__init__()\n\n self.embed_cols = embed_cols\n self.continuous_cols = continuous_cols\n self.already_standard = already_standard\n self.scale = scale\n self.default_embed_dim = default_embed_dim\n\n assert (self.embed_cols is not None) or (\n self.continuous_cols is not None\n ), \"'embed_cols' and 'continuous_cols' are 'None'. Please, define at least one of the two.\"\n\n def fit(self, df: pd.DataFrame) -> BasePreprocessor:\n \"\"\"Fits the Preprocessor and creates required attributes\"\"\"\n if self.embed_cols is not None:\n df_emb = self._prepare_embed(df)\n self.label_encoder = LabelEncoder(df_emb.columns.tolist()).fit(df_emb)\n self.embeddings_input: List = []\n for k, v in self.label_encoder.encoding_dict.items():\n self.embeddings_input.append((k, len(v), self.embed_dim[k]))\n if self.continuous_cols is not None:\n df_cont = self._prepare_continuous(df)\n if self.scale:\n df_std = df_cont[self.standardize_cols]\n self.scaler = StandardScaler().fit(df_std.values)\n else:\n warnings.warn(\"Continuous columns will not be normalised\")\n return self\n\n def transform(self, df: pd.DataFrame) -> np.ndarray:\n \"\"\"Returns the processed ``dataframe`` as a np.ndarray\"\"\"\n if self.embed_cols is not None:\n df_emb = self._prepare_embed(df)\n df_emb = self.label_encoder.transform(df_emb)\n if self.continuous_cols is not None:\n df_cont = self._prepare_continuous(df)\n if self.scale:\n try:\n self.scaler.mean_\n except AttributeError:\n raise NotFittedError(\n \"This DensePreprocessor instance is not fitted yet. \"\n \"Call 'fit' with appropriate arguments before using this estimator.\"\n )\n df_std = df_cont[self.standardize_cols]\n df_cont[self.standardize_cols] = self.scaler.transform(df_std.values)\n try:\n df_deep = pd.concat([df_emb, df_cont], axis=1)\n except NameError:\n try:\n df_deep = df_emb.copy()\n except NameError:\n df_deep = df_cont.copy()\n self.deep_column_idx = {k: v for v, k in enumerate(df_deep.columns)}\n return df_deep.values\n\n def inverse_transform(self, encoded: np.ndarray) -> pd.DataFrame:\n r\"\"\"Takes as input the output from the ``transform`` method and it will\n return the original values.\n\n Parameters\n ----------\n encoded: np.ndarray\n array with the output of the ``transform`` method\n \"\"\"\n decoded = pd.DataFrame(encoded, columns=self.deep_column_idx.keys())\n # embeddings back to original category\n if self.embed_cols is not None:\n if isinstance(self.embed_cols[0], tuple):\n emb_c: List = [c[0] for c in self.embed_cols]\n else:\n emb_c = self.embed_cols.copy()\n for c in emb_c:\n decoded[c] = decoded[c].map(self.label_encoder.inverse_encoding_dict[c])\n # continuous_cols back to non-standarised\n try:\n decoded[self.continuous_cols] = self.scaler.inverse_transform(\n decoded[self.continuous_cols]\n )\n except AttributeError:\n pass\n return decoded\n\n def fit_transform(self, df: pd.DataFrame) -> np.ndarray:\n \"\"\"Combines ``fit`` and ``transform``\"\"\"\n return self.fit(df).transform(df)\n\n def _prepare_embed(self, df: pd.DataFrame) -> pd.DataFrame:\n if isinstance(self.embed_cols[0], tuple):\n self.embed_dim = dict(self.embed_cols) # type: ignore\n embed_colname = [emb[0] for emb in self.embed_cols]\n else:\n self.embed_dim = {e: self.default_embed_dim for e in self.embed_cols} # type: ignore\n embed_colname = self.embed_cols # type: ignore\n return df.copy()[embed_colname]\n\n def _prepare_continuous(self, df: pd.DataFrame) -> pd.DataFrame:\n if self.scale:\n if self.already_standard is not None:\n self.standardize_cols = [\n c for c in self.continuous_cols if c not in self.already_standard\n ]\n else:\n self.standardize_cols = self.continuous_cols\n return df.copy()[self.continuous_cols]\n\n\nclass TextPreprocessor(BasePreprocessor):\n r\"\"\"Preprocessor to prepare the deeptext input dataset\n\n Parameters\n ----------\n text_col: str\n column in the input dataframe containing the texts\n max_vocab: int, default=30000\n Maximum number of token in the vocabulary\n min_freq: int, default=5\n Minimum frequency for a token to be part of the vocabulary\n maxlen: int, default=80\n Maximum length of the tokenized sequences\n word_vectors_path: str, Optional\n Path to the pretrained word vectors\n verbose: int, default 1\n Enable verbose output.\n\n Attributes\n ----------\n vocab: :obj:`Vocab`\n an instance of :class:`pytorch_widedeep.utils.fastai_transforms.Vocab`\n tokens: :obj:`List`\n List with Lists of str containing the tokenized texts\n embedding_matrix: :obj:`np.ndarray`\n Array with the pretrained embeddings\n\n Examples\n ---------\n >>> import pandas as pd\n >>> from pytorch_widedeep.preprocessing import TextPreprocessor\n >>> df_train = pd.DataFrame({'text_column': [\"life was like a box of chocolates\",\n ... \"You never know what you're gonna get\"]})\n >>> text_preprocessor = TextPreprocessor(text_col='text_column', max_vocab=25, min_freq=1, maxlen=10)\n >>> text_preprocessor.fit_transform(df_train)\n The vocabulary contains 24 tokens\n array([[ 1, 1, 1, 1, 10, 11, 12, 13, 14, 15],\n [ 5, 9, 16, 17, 18, 9, 19, 20, 21, 22]], dtype=int32)\n >>> df_te = pd.DataFrame({'text_column': ['you never know what is in the box']})\n >>> text_preprocessor.transform(df_te)\n array([[ 1, 1, 9, 16, 17, 18, 0, 0, 0, 13]], dtype=int32)\n \"\"\"\n\n def __init__(\n self,\n text_col: str,\n max_vocab: int = 30000,\n min_freq: int = 5,\n maxlen: int = 80,\n word_vectors_path: Optional[str] = None,\n verbose: int = 1,\n ):\n super(TextPreprocessor, self).__init__()\n self.text_col = text_col\n self.max_vocab = max_vocab\n self.min_freq = min_freq\n self.maxlen = maxlen\n self.word_vectors_path = word_vectors_path\n self.verbose = verbose\n\n def fit(self, df: pd.DataFrame) -> BasePreprocessor:\n \"\"\"Builds the vocabulary\"\"\"\n texts = df[self.text_col].tolist()\n tokens = get_texts(texts)\n self.vocab = Vocab.create(\n tokens, max_vocab=self.max_vocab, min_freq=self.min_freq\n )\n if self.verbose:\n print(\"The vocabulary contains {} tokens\".format(len(self.vocab.stoi)))\n return self\n\n def transform(self, df: pd.DataFrame) -> np.ndarray:\n \"\"\"Returns the padded, `numericalised` sequences\"\"\"\n try:\n self.vocab\n except AttributeError:\n raise NotFittedError(\n \"This TextPreprocessor instance is not fitted yet. \"\n \"Call 'fit' with appropriate arguments before using this estimator.\"\n )\n texts = df[self.text_col].tolist()\n self.tokens = get_texts(texts)\n sequences = [self.vocab.numericalize(t) for t in self.tokens]\n padded_seq = np.array([pad_sequences(s, maxlen=self.maxlen) for s in sequences])\n if self.word_vectors_path is not None:\n self.embedding_matrix = build_embeddings_matrix(\n self.vocab, self.word_vectors_path, self.min_freq\n )\n return padded_seq\n\n def fit_transform(self, df: pd.DataFrame) -> np.ndarray:\n \"\"\"Combines ``fit`` and ``transform``\"\"\"\n return self.fit(df).transform(df)\n\n\nclass ImagePreprocessor(BasePreprocessor):\n r\"\"\"Preprocessor to prepare the deepimage input dataset. The Preprocessing\n consists simply on resizing according to their aspect ratio\n\n Parameters\n ----------\n img_col: str\n name of the column with the images filenames\n img_path: str\n path to the dicrectory where the images are stored\n width: Int, default=224\n width of the resulting processed image. 224 because the default\n architecture used by WideDeep is ResNet\n height: Int, default=224\n width of the resulting processed image. 224 because the default\n architecture used by WideDeep is ResNet\n verbose: Int, default 1\n Enable verbose output.\n\n Attributes\n ----------\n aap: :obj:`AspectAwarePreprocessor`\n an instance of :class:`pytorch_widedeep.utils.image_utils.AspectAwarePreprocessor`\n spp: :obj:`SimplePreprocessor`\n an instance of :class:`pytorch_widedeep.utils.image_utils.SimplePreprocessor`\n normalise_metrics: :obj:`Dict`\n Dict containing the normalisation metrics of the image dataset, i.e.\n mean and std for the R, G and B channels\n\n Examples\n --------\n >>> import pandas as pd\n >>>\n >>> from pytorch_widedeep.preprocessing import ImagePreprocessor\n >>>\n >>> path_to_image1 = 'tests/test_data_utils/images/galaxy1.png'\n >>> path_to_image2 = 'tests/test_data_utils/images/galaxy2.png'\n >>>\n >>> df_train = pd.DataFrame({'images_column': [path_to_image1]})\n >>> df_test = pd.DataFrame({'images_column': [path_to_image2]})\n >>> img_preprocessor = ImagePreprocessor(img_col='images_column', img_path='.', verbose=0)\n >>> resized_images = img_preprocessor.fit_transform(df_train)\n >>> new_resized_images = img_preprocessor.transform(df_train)\n\n .. note:: Normalising metrics will only be computed when the\n ``fit_transform`` method is run. Running ``transform`` only will not\n change the computed metrics and running ``fit`` only simply\n instantiates the resizing functions.\n\n \"\"\"\n\n def __init__(\n self,\n img_col: str,\n img_path: str,\n width: int = 224,\n height: int = 224,\n verbose: int = 1,\n ):\n super(ImagePreprocessor, self).__init__()\n self.img_col = img_col\n self.img_path = img_path\n self.width = width\n self.height = height\n self.verbose = verbose\n\n def fit(self, df: pd.DataFrame) -> BasePreprocessor:\n r\"\"\"Simply instantiates the Preprocessors\n :obj:`AspectAwarePreprocessor`` and :obj:`SimplePreprocessor` for image\n resizing.\n\n See\n :class:`pytorch_widedeep.utils.image_utils.AspectAwarePreprocessor`\n and :class:`pytorch_widedeep.utils.image_utils.SimplePreprocessor`.\n\n \"\"\"\n self.aap = AspectAwarePreprocessor(self.width, self.height)\n self.spp = SimplePreprocessor(self.width, self.height)\n self._compute_normalising_metrics = True\n return self\n\n def transform(self, df: pd.DataFrame) -> np.ndarray:\n \"\"\"Resizes the images to the input height and width.\"\"\"\n try:\n self.aap\n except AttributeError:\n raise NotFittedError(\n \"This ImagePreprocessor instance is not fitted yet. \"\n \"Call 'fit' with appropriate arguments before using this estimator.\"\n )\n image_list = df[self.img_col].tolist()\n if self.verbose:\n print(\"Reading Images from {}\".format(self.img_path))\n imgs = [cv2.imread(\"/\".join([self.img_path, img])) for img in image_list]\n\n # finding images with different height and width\n aspect = [(im.shape[0], im.shape[1]) for im in imgs]\n aspect_r = [a[0] / a[1] for a in aspect]\n diff_idx = [i for i, r in enumerate(aspect_r) if r != 1.0]\n\n if self.verbose:\n print(\"Resizing\")\n resized_imgs = []\n for i, img in tqdm(enumerate(imgs), total=len(imgs), disable=self.verbose != 1):\n if i in diff_idx:\n resized_imgs.append(self.aap.preprocess(img))\n else:\n # if aspect ratio is 1:1, no need for AspectAwarePreprocessor\n resized_imgs.append(self.spp.preprocess(img))\n\n if self._compute_normalising_metrics:\n if self.verbose:\n print(\"Computing normalisation metrics\")\n # mean and std deviation will only be computed when the fit method\n # is called\n mean_R, mean_G, mean_B = [], [], []\n std_R, std_G, std_B = [], [], []\n for rsz_img in resized_imgs:\n (mean_b, mean_g, mean_r), (std_b, std_g, std_r) = cv2.meanStdDev(\n rsz_img\n )\n mean_R.append(mean_r)\n mean_G.append(mean_g)\n mean_B.append(mean_b)\n std_R.append(std_r)\n std_G.append(std_g)\n std_B.append(std_b)\n self.normalise_metrics = dict(\n mean={\n \"R\": np.mean(mean_R) / 255.0,\n \"G\": np.mean(mean_G) / 255.0,\n \"B\": np.mean(mean_B) / 255.0,\n },\n std={\n \"R\": np.mean(std_R) / 255.0,\n \"G\": np.mean(std_G) / 255.0,\n \"B\": np.mean(std_B) / 255.0,\n },\n )\n self._compute_normalising_metrics = False\n return np.asarray(resized_imgs)\n\n def fit_transform(self, df: pd.DataFrame) -> np.ndarray:\n \"\"\"Combines ``fit`` and ``transform``\"\"\"\n return self.fit(df).transform(df)\n","sub_path":"pytorch_widedeep/preprocessing/_preprocessors.py","file_name":"_preprocessors.py","file_ext":"py","file_size_in_byte":22770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"293707325","text":"from django.test import TestCase\nfrom django.contrib.auth import get_user_model\nfrom apps.oidc.claims import get_claims_provider\nfrom apps.accounts.models import UserProfile\nfrom .models import AttestedCredentialData\n\nUserModel = get_user_model()\n\n\nclass ClaimProviderTests(TestCase):\n\n def setUp(self):\n self.test_user = UserModel.objects.create_user(\n \"test_user\",\n \"test@example.com\",\n \"123456\")\n UserProfile.objects.create(\n user=self.test_user)\n\n self.dev_user = UserModel.objects.create_user(\n \"dev_user\",\n \"dev@example.com\",\n \"123456\")\n AttestedCredentialData.objects.create(\n user=self.dev_user)\n UserProfile.objects.create(\n user=self.dev_user)\n\n def test_get_claims(self):\n cp = get_claims_provider()(user=self.dev_user)\n claims = cp.get_claims()\n self.assertEqual(claims[\"email\"], \"dev@example.com\")\n self.assertEqual(claims['vot'], \"P1.C2\")\n self.assertEqual(claims['aal'], \"2\")\n\n def test_get_claims_no_change(self):\n cp = get_claims_provider()(user=self.test_user)\n claims = cp.get_claims()\n self.assertEqual(claims[\"email\"], \"test@example.com\")\n self.assertEqual(claims['vot'], \"P1.C1\")\n self.assertEqual(claims['aal'], \"1\")\n","sub_path":"apps/fido/test_claims_provider.py","file_name":"test_claims_provider.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"338096279","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom tweepy import Stream\nfrom tweepy import OAuthHandler\nfrom tweepy.streaming import StreamListener\nimport json\nimport sentiment_mod as s\n\n# consumer key, consumer secret, access token, access secret.\n\nckey = '5WTo3uWBaiisgkpfj4Uxo93z3'\ncsecret = 'x1DJU6U2ZaWolxjDax0wpoI6vMmJsTwSI0070NWzuYj4dKHUGY'\natoken = '70351928-5fdWGmR6sw4oorlZtB0N0jHfh56dYzEBejLvLKFaz'\nasecret = '4nGh4GKrRe839V8j91qrtrZMLxSGNL1UGqorx7K671iP8'\n\n\nclass listener(StreamListener):\n\n def on_data(self, data):\n\n all_data = json.loads(data)\n tweet = all_data['text']\n (sentiment_value, confidence) = s.sentiment(tweet)\n print (tweet, sentiment_value, confidence)\n\n if confidence * 100 >= 80:\n output = open('twitter-out.txt', 'a')\n output.write(sentiment_value)\n output.write('\\n')\n output.close()\n\n return True\n\n def on_error(self, status):\n print (status)\n\n\nauth = OAuthHandler(ckey, csecret)\nauth.set_access_token(atoken, asecret)\n\ntwitterStream = Stream(auth, listener())\ntwitterStream.filter(track=['rock'])\n","sub_path":"twitter_analysis.py","file_name":"twitter_analysis.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"563635205","text":"\"\"\"User admin classes\"\"\"\r\n\r\n# Django\r\nfrom django.contrib import admin\r\nfrom django.contrib.auth.admin import UserAdmin as BaseUserAdmin\r\n\r\n# Models\r\nfrom users.models import Profile\r\n\r\nfrom django.contrib.auth.models import User\r\n\r\n# Register your models here.\r\n@admin.register(Profile) # Decorador\r\n\r\nclass ProfileAdmin(admin.ModelAdmin):\r\n \"\"\"Profile admin.\"\"\"\r\n # pass\r\n list_display = ('pk','user', 'website', 'biography', 'phone_number', 'picture')\r\n list_display_links = ('pk','user')\r\n list_editable = ('phone_number','website', 'picture')\r\n \r\n search_fields = (\r\n 'user__email',\r\n 'user__name'\r\n 'user__first_name',\r\n 'user__last_name',\r\n 'phone_number'\r\n )\r\n\r\n list_filter = (\r\n 'created',\r\n 'modified',\r\n 'user__is_active',\r\n 'user__is_staff'\r\n )\r\n\r\n fieldsets = (\r\n \r\n ('Profile', {\r\n 'fields':(\r\n 'user', \r\n 'picture'\r\n ),\r\n }),\r\n ('Extra Info!', {\r\n 'fields': ((\r\n 'website',\r\n 'phone_number',),\r\n ('biography'),\r\n\r\n )}),\r\n \r\n ('Metadata', { \r\n 'fields':(\r\n 'created',\r\n 'modified',\r\n )\r\n }),\r\n\r\n )\r\n \r\n readonly_fields = ('created', 'modified')\r\n\r\nclass ProfileInline(admin.StackedInline):\r\n \"\"\"Profile in-line admin for users.\"\"\"\r\n\r\n model = Profile\r\n can_delete = False\r\n verbose_name_plural = 'profiles'\r\n\r\n\r\n\r\nclass UserAdmin(BaseUserAdmin):\r\n \"\"\"Add profile admin to base user admin.\"\"\"\r\n inlines = (ProfileInline,)\r\n list_display = (\r\n 'username',\r\n 'email',\r\n 'first_name',\r\n 'last_name',\r\n 'is_active',\r\n 'is_staff'\r\n )\r\n \r\nadmin.site.unregister(User)\r\nadmin.site.register(User, UserAdmin)\r\n\r\n\r\n ","sub_path":"users/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"213813100","text":"def tamBolen(sayi):\r\n\r\n tam_bolenler=[]\r\n\r\n for i in range (2,sayi): #bu araarda bolenleri append ediyor.\r\n if sayi%i==0:\r\n tam_bolenler.append(i)\r\n\r\n return tam_bolenler\r\n\r\n\r\nwhile True:\r\n sayi=input(\"sayi gir\")\r\n\r\n if sayi==\"q\":\r\n print(\"sonlandı\")\r\n break\r\n else:\r\n sayi=int(sayi)\r\n print(tamBolen(sayi))","sub_path":"Fonksiyonlar/tambolen.py","file_name":"tambolen.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"567060981","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\nimport sys\nimport os\nimport cProfile\nimport pstats\nfrom timeit import default_timer as time\nimport argparse\n\nimport numpy as np\nfrom mayavi import mlab\nfrom matplotlib.colors import BoundaryNorm\n\n_viscid_root = os.path.realpath(os.path.dirname(__file__) + '/../../src/viscid/') #pylint: disable=C0301\nif not _viscid_root in sys.path:\n sys.path.append(_viscid_root)\n\nfrom viscid import logger\nimport tracer\nfrom viscid import vutil\nfrom viscid import readers\nfrom viscid import field\nfrom viscid.plot import mpl\nfrom viscid.plot import mvi\nfrom viscid.plot.mpl import plt\nfrom viscid.calculator import streamline\nfrom viscid.calculator import seed\n# import topo_numba\n\ngsize = (32, 32, 16)\nx1 = -10.0; x2 = -5.0 #pylint: disable=C0321\ny1 = -5.0; y2 = 5.0 #pylint: disable=C0321\nz1 = -5.0; z2 = 5.0 #pylint: disable=C0321\nvol = seed.Volume((z1, y1, x1), (z2, y2, x2), gsize)\n\ndef trace_fortran(fld_bx, fld_by, fld_bz):\n gx, gy, gz = fld_bx.get_crds_cc(('x', 'y', 'z'))\n nz, ny, nx = fld_bx.shape\n\n t0 = time()\n bx_farr = np.array(np.ravel(fld_bx.data, order='K').reshape((nx, ny, nz), order=\"F\")) #pylint: disable=C0301\n by_farr = np.array(np.ravel(fld_by.data, order='K').reshape((nx, ny, nz), order=\"F\")) #pylint: disable=C0301\n bz_farr = np.array(np.ravel(fld_bz.data, order='K').reshape((nx, ny, nz), order=\"F\")) #pylint: disable=C0301\n\n topo = np.zeros(gsize, order='F', dtype='int32')\n nsegs = np.zeros((1,), order='F', dtype='int32')\n\n # logger.info((np.ravel(bx_farr, order='K') == np.ravel(fld_bx.data, order='K')).all()) #pylint: disable=C0301\n # logger.info((np.ravel(by_farr, order='K') == np.ravel(fld_by.data, order='K')).all()) #pylint: disable=C0301\n # logger.info((np.ravel(bz_farr, order='K') == np.ravel(fld_bz.data, order='K')).all()) #pylint: disable=C0301\n # logger.info(\"bx_arr\")\n # logger.info(bx_farr.strides)\n # logger.info(bx_farr.flags)\n # logger.info(\"topo\")\n # logger.info(topo.strides)\n # logger.info(topo.shape)\n\n tracer.get_topo(gx, gy, gz, bx_farr, by_farr, bz_farr, topo,\n x1, x2, y1, y2, z1, z2, nsegs)\n t1 = time()\n\n t = t1 - t0\n print(\"total segments calculated: {0:.05e}\".format(float(nsegs)))\n print(\"time: {0:.4}s ... {1:.4}s/segment\".format(t, t / float(nsegs)))\n\n topo_fld = vol.wrap_field(topo, name=\"FortTopo\")\n return None, topo_fld\n\ndef trace_cython(fld_bx, fld_by, fld_bz):\n # print(\"Cython...\")\n B = field.scalar_fields_to_vector([fld_bx, fld_by, fld_bz], name=\"B_cc\",\n _force_layout=field.LAYOUT_INTERLACED)\n t0 = time()\n lines, topo = None, None\n lines, topo = streamline.streamlines(B, vol, ds0=0.02, ibound=3.7,\n maxit=5000, output=streamline.OUTPUT_BOTH,\n method=streamline.EULER1,\n tol_lo=0.005, tol_hi=0.1,\n fac_refine=0.75, fac_coarsen=1.5)\n t1 = time()\n topo_fld = vol.wrap_field(topo, name=\"CyTopo\")\n\n # cmap = plt.get_cmap('spectral')\n # levels = [4, 5, 6, 7, 8, 13, 14, 16, 17]\n # norm = BoundaryNorm(levels, cmap.N)\n # mpl.plot(topo_fld, \"y=0\", cmap=cmap, norm=norm, show=False)\n # # mpl.plot_streamlines2d(lines[::5], \"y\", topology=topo[::5], show=False)\n # # mpl.plot_streamlines(lines, topology=topo, show=False)\n # mpl.mplshow()\n\n # topo_src = mvi.add_field(topo_fld, center='node')\n # mvi.plot_lines(mlab.pipeline, lines[::5], topo[::5], opacity=0.8,\n # tube_radius=0.02)\n # mvi.plod_earth_3d(mlab.pipeline)\n # mlab.show()\n\n nsegs = 1 # keep from divding by 0 is no streamlines\n if lines is not None:\n nsegs = 0\n for line in lines:\n nsegs += len(line[0])\n\n t = t1 - t0\n print(\"total segments calculated: \", nsegs)\n print(\"time: {0:.4}s ... {1:.4}s/segment\".format(t, t / float(nsegs)))\n\n return lines, topo_fld\n\ndef trace_numba(fld_bx, fld_by, fld_bz):\n B = field.scalar_fields_to_vector([fld_bx, fld_by, fld_bz], name=\"B_cc\",\n _force_layout=field.LAYOUT_INTERLACED)\n topo_arr = np.empty(gsize, order='C', dtype='int')\n lines, topo = None, None\n t0 = time()\n nsegs = topo_numba.get_topo(B, topo_arr, x1, x2, y1, y2, z1, z2)\n t1 = time()\n topo_fld = vol.wrap_field(topo, name=\"CyTopo\")\n return t1 - t0, nsegs, lines, topo_fld\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Test xdmf\")\n parser.add_argument(\"--show\", \"--plot\", action=\"store_true\")\n parser.add_argument('file', nargs=\"?\", default=None)\n args = vutil.common_argparse(parser)\n\n # f3d = readers.load_file(_viscid_root + '/../../sample/sample.3df.xdmf')\n # b3d = f3d['b']\n # bx, by, bz = b3d.component_fields() #pylint: disable=W0612\n\n if args.file is None:\n # args.file = \"/Users/kmaynard/dev/work/cen4000/cen4000.3d.xdmf\"\n # args.file = \"/Users/kmaynard/dev/work/tmp/cen2000.3d.004045.xdmf\"\n args.file = \"~/dev/work/api_05_180_0.00_5e2.3d.007200.xdmf\"\n f3d = readers.load_file(args.file)\n\n bx = f3d[\"bx\"]\n by = f3d[\"by\"]\n bz = f3d[\"bz\"]\n\n profile = False\n\n print(\"Fortran...\")\n if profile:\n cProfile.runctx(\"lines, topo_fort = trace_fortran(bx, by, bz)\",\n globals(), locals(), \"topo_fort.prof\")\n s = pstats.Stats(\"topo_fort.prof\")\n s.strip_dirs().sort_stats(\"cumtime\").print_stats(10)\n else:\n lines, topo_fort = trace_fortran(bx, by, bz)\n\n print(\"Cython...\")\n if profile:\n cProfile.runctx(\"lines, topo_cy = trace_cython(bx, by, bz)\",\n globals(), locals(), \"topo_cy.prof\")\n s = pstats.Stats(\"topo_cy.prof\")\n s.strip_dirs().sort_stats(\"cumtime\").print_stats(15)\n else:\n lines, topo_cy = trace_cython(bx, by, bz)\n # print(\"Same? \",(np.ravel(topo_fort.data, order='K') ==\n # np.ravel(topo_cy.data, order='K')).all())\n\n # print(\"Numba...\")\n # t, nsegs, lines, topo_nb = trace_numba(bx, by, bz)\n # print(\"total segments calculated: \", nsegs)\n # print(\"time: {0:.4}s ... {1:.4}s/segment\".format(t, t / float(nsegs)))\n # print(\"Same? \",(np.ravel(topo_fort.data, order='K') ==\n # np.ravel(topo_nb.data, order='K')).all())\n\nif __name__ == \"__main__\":\n main()\n\n##\n## EOF\n##\n","sub_path":"scratch/fortran_trace/stream_bench.py","file_name":"stream_bench.py","file_ext":"py","file_size_in_byte":6427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"152264436","text":"#!/usr/bin/python\nimport SimpleHTTPServer\nimport SocketServer\nimport sys\n\nprint(\"Starting python server...\") # do we need this?\nif 'sys.argv' in locals():\n port = sys.argv(1)\nelse:\n port = 9000\nHandler = SimpleHTTPServer.SimpleHTTPRequestHandler\nhttpd = SocketServer.TCPServer((\"\", port), Handler)\nhttpd.serve_forever()\n\n# need to chmod +x","sub_path":"server-files/http-server.py","file_name":"http-server.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"425077490","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jun 30 09:00:53 2020\r\n\r\n@author: vishal\r\n\"\"\"\r\n\r\n\r\nlist=[\"Cse\",\"Mech\",\"Ece\",\"Civil\"]\r\nn=len(list)\r\nprint(\"Accesing the list elements\")\r\nfor i in range(0,n):\r\n print(\"list\",[i],\"=\",list[i])\r\n ","sub_path":"Module4_A2_List(Access&print).py","file_name":"Module4_A2_List(Access&print).py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"240197528","text":"# TODO: add tests for ping and health\n# TODO: refactor create_alert to take args instead of the whole body\n# TODO: add tests where the percolator doc exists in a different index\n\nimport requests\nimport json\nimport uuid\n\nfrom datetime import datetime, timezone\n\nAPI_URL = \"http://127.0.0.1:5000\"\nES_URL = \"localhost:9200\"\nES_URL_QS = {\"es_url\": ES_URL}\n\nclass AlertCRUD:\n def check_ping(self):\n res = requests.get(\"%s/ping/\" % API_URL)\n try:\n ping = res.json()\n assert(res.status_code == 200 and ping[\"status\"] == \"OK\")\n except:\n print(res.text)\n raise\n\n # TODO: refactor this when create is refactored in the API\n def index_alert(self, alert_id):\n headers = {\"content-type\": \"application/json\"}\n alert_body = {\n \"query\": {\n \"filtered\": {\n \"query\": {\n \"match\": {\n \"msg\": {\n \"query\": \"IndexMissingException\"\n }\n }\n },\n \"filter\": {\n \"bool\": {\n \"must\": [\n {\n \"indices\": {\n \"indices\": [\n \"logstash-*\"\n ],\n \"filter\": {}\n }\n },\n {\n \"range\": {\n \"@timestamp\": {\n \"gte\": \"now-30m\",\n \"time_zone\": \"+1:00\"\n }\n }\n }\n ]\n }\n }\n }\n },\n \"xavierAlertObjectMeta\": {\n \"title\": \"example demo alert 10.5\",\n \"description\": \"this is an example alert for demo purposes\",\n \"owner\": \"mbadran\",\n \"permissions\": \"644\",\n \"enabled\": True,\n \"index\": [\"logstash-*\"],\n \"schedule\": \"*/5 * * * *\",\n \"throttle\": \"60\",\n \"state\": \"READY\",\n \"output\": [{\n \"email\": {\n \"enabled\": True,\n \"throttle\": \"600\",\n \"to\": [\"mebadran@gmail.com\"],\n \"from\": \"xavier@example.com\",\n \"subject\": \"Alert from Xavier\",\n \"body\": \"$full$\"\n }\n }]\n }\n }\n res = requests.put(\"%s/alerts/%s/\" % (API_URL, alert_id), params=ES_URL_QS, data=json.dumps(alert_body), headers=headers)\n try:\n create_res = res.json()\n assert(res.status_code == 201 and create_res[\"_id\"] == alert_id and create_res[\"created\"] == True)\n except:\n print(res.text)\n raise\n\n return alert_id\n\n def get_alert(self, alert_id):\n res = requests.get(\"%s/alerts/%s/\" % (API_URL, alert_id), params=ES_URL_QS)\n try:\n get_res = res.json()\n assert(res.status_code == 200 and get_res[\"_id\"] == alert_id)\n except:\n print(res.text)\n raise\n\n def update_alert(self, alert_id):\n headers = {\"content-type\": \"application/json\"}\n alert_body = {\n \"query\": {\n \"filtered\": {\n \"query\": {\n \"match\": {\n \"msg\": {\n \"query\": \"IndexMissingException\"\n }\n }\n },\n \"filter\": {\n \"bool\": {\n \"must\": [\n {\n \"indices\": {\n \"indices\": [\n \"logstash-*\"\n ],\n \"filter\": {}\n }\n },\n {\n \"range\": {\n \"@timestamp\": {\n \"gte\": \"now-30m\",\n \"time_zone\": \"+1:00\"\n }\n }\n }\n ]\n }\n }\n }\n },\n \"xavierAlertObjectMeta\": {\n \"title\": \"example demo alert 10.6\",\n \"description\": \"this is an updated example alert for demo purposes\",\n \"owner\": \"mbadran\",\n \"permissions\": \"644\",\n \"enabled\": True,\n \"index\": [\"logstash-*\"],\n \"schedule\": \"*/5 * * * *\",\n \"throttle\": \"60\",\n \"state\": \"READY\",\n \"output\": [{\n \"email\": {\n \"enabled\": True,\n \"throttle\": \"600\",\n \"to\": [\"mebadran@gmail.com\"],\n \"from\": \"xavier@example.com\",\n \"subject\": \"Alert from Xavier\",\n \"body\": \"$full$\"\n }\n }]\n }\n }\n res = requests.put(\"%s/alerts/%s/\" % (API_URL, alert_id), params=ES_URL_QS, data=json.dumps(alert_body), headers=headers)\n try:\n update_res = res.json()\n assert(res.status_code == 200 and update_res[\"_id\"] == alert_id and update_res[\"_version\"] == 2)\n except:\n print(res.text)\n raise\n\n return alert_id\n\n def delete_alert(self, alert_id):\n res = requests.delete(\"%s/alerts/%s/\" % (API_URL, alert_id), params=ES_URL_QS)\n try:\n delete_res = res.json()\n assert(res.status_code == 200 and delete_res[\"_id\"] == alert_id and delete_res[\"found\"] == True)\n except:\n print(res.text)\n raise\n\nclass DocCRUD:\n def check_ping(self):\n res = requests.get(\"%s/ping/\" % API_URL)\n try:\n ping = res.json()\n assert(res.status_code == 200 and ping[\"status\"] == \"OK\")\n except:\n print(res.text)\n raise\n\n def index_doc(self, doc_id):\n headers = {\"content-type\": \"application/json\"}\n doc_body = {\n \"tweet\": {\n \"content\": \"hello world\",\n \"description\": \"this is an example doc for demo purposes\",\n \"author\": \"mbadran\",\n }\n }\n res = requests.put(\"%s/docs/.xavier/pytest/%s/\" % (API_URL, doc_id), params=ES_URL_QS, data=json.dumps(doc_body), headers=headers)\n try:\n create_res = res.json()\n assert(res.status_code == 201 and create_res[\"_id\"] == doc_id and create_res[\"created\"] == True)\n except:\n print(res.text)\n raise\n\n return doc_id\n\n def get_doc(self, doc_id):\n res = requests.get(\"%s/docs/.xavier/%s/\" % (API_URL, doc_id), params=ES_URL_QS)\n try:\n get_res = res.json()\n assert(res.status_code == 200 and get_res[\"_id\"] == doc_id)\n except:\n print(res.text)\n raise\n\n def update_doc(self, doc_id):\n headers = {\"content-type\": \"application/json\"}\n doc_body = {\n \"tweet\": {\n \"content\": \"hello world\",\n \"description\": \"this is an example doc for demo purposes\",\n \"author\": \"mbadran\",\n }\n }\n res = requests.put(\"%s/docs/.xavier/pytest/%s/\" % (API_URL, doc_id), params=ES_URL_QS, data=json.dumps(doc_body), headers=headers)\n try:\n update_res = res.json()\n assert(res.status_code == 200 and update_res[\"_id\"] == doc_id and update_res[\"_version\"] == 2)\n except:\n print(res.text)\n raise\n\n return doc_id\n\n def delete_doc(self, doc_id):\n res = requests.delete(\"%s/docs/.xavier/pytest/%s/\" % (API_URL, doc_id), params=ES_URL_QS)\n try:\n delete_res = res.json()\n assert(res.status_code == 200 and delete_res[\"_id\"] == doc_id and delete_res[\"found\"] == True)\n except:\n print(res.text)\n raise\n\n# NOTE: the percolator finds queries that match docs, but only when those queries\n# exist in the same index as the doc. bummer.\nclass Percolator:\n def index_doc(self, doc_id):\n headers = {\"content-type\": \"application/json\"}\n doc_body = {\n \"@timestamp\": _get_now_timestamp(),\n \"host\": \"127.0.0.1\",\n \"category\": \"audit\",\n \"dyno\": \"localhost\",\n \"es_url\": \"localhost:9200\",\n \"level\": \"error\",\n \"msg\": \"TransportError(404, 'IndexMissingException[[fubar] missing]')\",\n \"response_status\": 404,\n \"source\": \"upstream\"\n }\n # res = requests.put(\"%s/docs/.xavier/pytest/%s/\" % (API_URL, doc_id), params=ES_URL_QS, data=json.dumps(doc_body), headers=headers)\n res = requests.put(\"%s/docs/.xavier/pytest_percolate/%s/\" % (API_URL, doc_id), params=ES_URL_QS, data=json.dumps(doc_body), headers=headers)\n try:\n create_res = res.json()\n assert(res.status_code == 201 and create_res[\"_id\"] == doc_id and create_res[\"created\"] == True)\n except:\n print(res.text)\n raise\n\n return doc_id\n\n def percolate(self, doc_id, trigger):\n params = ES_URL_QS\n params[\"trigger\"] = trigger\n\n # res = requests.get(\"%s/percolate/logstash-2015.02.28/xavier-api/%s\" % (API_URL, doc_id), params=ES_URL_QS)\n # res = requests.get(\"%s/percolate/.xavier/pytest/%s\" % (API_URL, doc_id), params=ES_URL_QS)\n res = requests.get(\"%s/percolate/.xavier/pytest_percolate/%s\" % (API_URL, doc_id), params=params)\n # TODO: remove me when happy\n try:\n percolate_res = res.json()\n # if the 404 doc has been created, percolate should return matches[] array that is larger than 1\n # TODO: set the return format to just the query _ids.\n # assert(res.status_code == 200 and percolate_res[\"_id\"] == doc_id)\n assert(res.status_code == 200 and percolate_res[\"matches\"])\n except:\n print(res.text)\n raise\n\n # the params value persists in the class for some reason\n params[\"trigger\"] = None\n\n def delete_doc(self, doc_id):\n res = requests.delete(\"%s/docs/.xavier/pytest_percolate/%s/\" % (API_URL, doc_id), params=ES_URL_QS)\n try:\n delete_res = res.json()\n assert(res.status_code == 200 and delete_res[\"_id\"] == doc_id and delete_res[\"found\"] == True)\n except:\n print(res.text)\n raise\n\ndef _get_now_timestamp():\n return datetime.now(timezone.utc).isoformat()\n\ndef _get_random_id():\n random_id = str(uuid.uuid4()).replace(\"-\", \"\").lower()[:8]\n return \"pytest_%s\" % random_id\n\n# test the CRUD lifecycle for alerts\ndef testAlertCRUD():\n alert_id = _get_random_id()\n\n alert = AlertCRUD()\n alert.check_ping()\n alert.index_alert(alert_id)\n alert.get_alert(alert_id)\n alert.update_alert(alert_id)\n alert.delete_alert(alert_id)\n\n# test the CRUD lifecycle for docs\ndef testDocCRUD():\n doc_id = _get_random_id()\n\n doc = DocCRUD()\n doc.check_ping()\n doc.index_doc(doc_id)\n doc.get_doc(doc_id)\n doc.update_doc(doc_id)\n doc.delete_doc(doc_id)\n\n# test the percolator on an existing doc\ndef testPercolateID(trigger=\"false\"):\n # create an alert\n alert_id = _get_random_id() + \"_alert\"\n alert = AlertCRUD()\n alert.index_alert(alert_id)\n\n # create a 404 doc and percolate it\n doc_id = _get_random_id() + \"_doc\"\n percolator = Percolator()\n percolator.index_doc(doc_id)\n percolator.percolate(doc_id, trigger)\n\n # clean up\n alert.delete_alert(alert_id)\n percolator.delete_doc(doc_id)\n\n# testAlertCRUD()\n# testDocCRUD()\n# # testSearch()\n# testPercolateID()\n# # testPercolateBody()\ntestPercolateID(trigger=\"true\")\n# # testPercolateBodyAndTrigger()\n# # testCreateAndPercolate()\n# # testCreateAndPercolateAndTrigger()\n# # testUpdateAndPercolate()\n# # testUpdateAndPercolateAndTrigger()","sub_path":"tests/test_suite.py","file_name":"test_suite.py","file_ext":"py","file_size_in_byte":12826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"453306062","text":"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport re\n\n\"\"\"\n获取制定话题下,所有的问题以及链接\n\n\"\"\"\n\nvisited_pages = set()\nbaseUrl = \"http://www.zhihu.com\"\ntopicUrl = baseUrl + \"/topic/19564408/questions\"\ndef get_questions(pageUrl):\n global visited_pages\n html = urlopen(pageUrl)\n bsObj = BeautifulSoup(html, \"html5lib\")\n for link in bsObj.findAll(\"a\", {\"class\": \"question_link\"}):\n if 'href' in link.attrs:\n question_link = link.attrs['href']\n if question_link not in visited_pages:\n visited_pages.add(question_link)\n print(baseUrl + question_link)\n print(link.get_text())\n for link in bsObj.findAll(\"a\"):\n if 'href' in link.attrs:\n if '?' in link.attrs['href']:\n if topicUrl + link.attrs['href'] not in visited_pages:\n visited_pages.add(topicUrl + link.attrs['href'])\n print(topicUrl + link.attrs['href'])\n get_questions(topicUrl + link.attrs['href'])\n\nget_questions(topicUrl)\n","sub_path":"zhihu_crawler/get_all_questions.py","file_name":"get_all_questions.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"149424925","text":"# -*- coding:utf-8 -*-\n# \n# Author: YIN MIAO\n# Time: 2019/3/31 17:35\n\nfrom keras.datasets import cifar10\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation, Dropout, Flatten\nfrom keras.utils import to_categorical\nfrom keras.callbacks import TensorBoard\nfrom keras import optimizers\nimport keras.backend as K\nimport numpy as np\nimport tensorflow as tf\nimport t3f\nimport sys\n\nnum_epoch = 100\n\nsess = tf.InteractiveSession()\nK.set_session(sess)\n\n__console__ = sys.stdout\nfout = open('./finetuning.txt', 'w')\n\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\nx_train = x_train / 127.5 - 1.0\nx_test = x_test / 127.5 -1.0\n\ny_train = to_categorical(y_train, num_classes=10)\ny_test = to_categorical(y_test, num_classes=10)\n\nmodel = Sequential()\nmodel.add(Flatten(input_shape=(32, 32, 3)))\nmodel.add(Dense(1024, activation='relu'))\nmodel.add(Dense(256, activation='relu'))\nmodel.add(Dense(10))\nmodel.add(Activation('softmax'))\n\nsys.stdout = fout\nmodel.summary()\nsys.stdout = __console__\nfout.flush()\n\noptimizer = optimizers.Adam(lr=1e-3)\nmodel.compile(\n optimizer=optimizer,\n loss='categorical_crossentropy',\n metrics=['accuracy']\n)\n\nmodel.fit(x_train, y_train,\n epochs=num_epoch,\n batch_size=32,\n validation_data=(x_test, y_test),\n callbacks=[TensorBoard(log_dir='./logs/dense2tt-finetuning')])\n\nsys.stdout = fout\nloss, acc = model.evaluate(x_test, y_test)\nprint('loss:', loss, 'acc:', acc)\nfout.flush()\n\nW1 = model.trainable_weights[0]\nb1 = model.get_weights()[1]\nW2 = model.trainable_weights[2]\nb2 = model.get_weights()[3]\nother_params = model.get_weights()[4:]\n\nW1_tt = t3f.to_tt_matrix(W1,\n shape=[[4, 8, 4, 8, 3], [4, 4, 4, 4, 4]],\n max_tt_rank=9)\nW2_tt = t3f.to_tt_matrix(W2,\n shape=[[4, 8, 4, 8], [4, 4, 4, 4]],\n max_tt_rank=9)\n\ntt_rank2 = W2_tt.get_tt_ranks()[1]\nW1_tt_cores = sess.run(W1_tt.tt_cores)\nW2_tt_cores = sess.run(W2_tt.tt_cores)\n\nmodel = Sequential()\nmodel.add(Flatten(input_shape=(32, 32, 3)))\ntt_layer1 = t3f.nn.KerasDense(\n input_dims=[4, 8, 4, 8, 3],\n output_dims=[4, 4, 4, 4, 4],\n tt_rank=9,\n activation='relu',\n bias_initializer=0\n)\nmodel.add(tt_layer1)\ntt_layer2 = t3f.nn.KerasDense(\n input_dims=[4, 8, 4, 8],\n output_dims=[4, 4, 4, 4],\n tt_rank=9,\n activation='relu',\n bias_initializer=0\n)\nmodel.add(tt_layer2)\nmodel.add(Dense(10))\nmodel.add(Activation('softmax'))\n\nmodel.summary()\n\noptimizer = optimizers.Adam(lr=1e-3)\nmodel.compile(\n optimizer=optimizer,\n loss='categorical_crossentropy',\n metrics=['accuracy']\n)\nprint('new acc:', model.evaluate(x_test, y_test)[1])\n\nsys.stdout = __console__\nvars = list()\nvars.extend(W1_tt_cores)\nvars.append(b1)\nvars.extend(W2_tt_cores)\nvars.append(b2)\nvars.extend(other_params)\nmodel.set_weights(vars)\n\nsys.stdout = __console__\nmodel.fit(x_train, y_train,\n epochs=num_epoch,\n batch_size=32,\n validation_data=(x_test, y_test)\n)\nsys.stdout = fout\nloss, acc = model.evaluate(x_test, y_test)\nprint('loss:', loss, 'acc:', acc)\nfout.close()\n\n\n\n","sub_path":"t3fnets/cifar10/tt-dense-ft.py","file_name":"tt-dense-ft.py","file_ext":"py","file_size_in_byte":3142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"185097834","text":"class Solution:\n def subsets(self, nums):\n res = []\n temp = []\n self.backtrack(res, temp, 0, nums)\n return res\n\n def backtrack(self, res, out, idx, nums):\n res.append(out[:])\n for i in range(idx, len(nums)):\n out.append(nums[i])\n self.backtrack(res, out, i+1, nums)\n out.pop()\n\n\nif __name__ == \"__main__\":\n nums = [1, 2, 3]\n print(Solution().subsets(nums))\n","sub_path":"Subsets.py","file_name":"Subsets.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"305410771","text":"#\n# Copyright (c) 2015 \n# All rights reserved.\n#\n#\n# @NETFPGA_LICENSE_HEADER_START@\n#\n# Licensed to NetFPGA C.I.C. (NetFPGA) under one or more contributor\n# license agreements. See the NOTICE file distributed with this work for\n# additional information regarding copyright ownership. NetFPGA licenses this\n# file to you under the NetFPGA Hardware-Software License, Version 1.0 (the\n# \"License\"); you may not use this file except in compliance with the\n# License. You may obtain a copy of the License at:\n#\n# http://www.netfpga-cic.org\n#\n# Unless required by applicable law or agreed to in writing, Work distributed\n# under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations under the License.\n#\n# @NETFPGA_LICENSE_HEADER_END@\n#\n\nimport os\n\n\ndef parsePing(path):\n try:\n fh = open(path, \"r\")\n line = fh.readline()\n except IOError:\n print(\"Error reading Ping log file. Ensure file exists and is readable.\")\n return\n if not line.startswith(\"rtt min/avg/max/mdev = \"):\n print(\"Error parsing Ping log file\")\n return\n slashIndex = line[23:].find(\"/\")\n try:\n minLat = float(line[23:23 + slashIndex])\n except ValueError:\n print(\"Error parsing Ping log file\")\n return\n return minLat\n\n\ndef parseIperf(path):\n try:\n fh = open(path, \"r\")\n line = fh.readline()\n except IOError:\n print(\"Error reading iPerf log file. Ensure file exists and is readable.\")\n return\n try:\n bits = int(line[line.rfind(\",\") + 1:])\n except ValueError:\n print(\"Error parsing iPerf log file\")\n return None\n return bits\n\n\ndef parseMemcached(path):\n try:\n fh = open(path, \"r\")\n line = fh.readline()\n except IOError:\n print(\"Error reading Memcached log file. Ensure file exists and is readable.\")\n return\n if not line.startswith(\"Totals\"):\n print(\"Error parsing Memcached log file\")\n return\n started = False # have we reached the float yet\n first = 0\n last = 0\n i = 6\n while True:\n if not started and line[i] == \" \": # get to the float\n i = i + 1\n continue\n elif started and line[i] == \" \": # we've reached the end of the float\n last = i\n break\n elif not started: # we've reached the start of the float\n started = True\n first = i\n elif line[i] == \"\\n\": # we've failed at parsing\n print(\"Error parsing Memcached log file\")\n return None\n i = i + 1\n try:\n value = float(line[first:last])\n except ValueError:\n print(\"Error parsing Memcached log file\")\n return None\n return value\n\n\ndef customParse(parseFile):\n if not os.path.exists(parseFile):\n print(\"ERROR - Custom parse script file no longer exists\")\n return\n local_dict = locals()\n global_dict = globals()\n with open(parseFile, 'rb') as file:\n # user script must create file custom_results_parsed.log in current working directory\n # the created file must contain the measured metric on the first line, and the y axis label on the second line\n exec(compile(file.read(), parseFile, 'exec'), global_dict, local_dict)\n try:\n fh = open(\"custom_results_parsed.log\", \"r\")\n line1 = fh.readline().strip()\n line2 = fh.readline().strip()\n except IOError:\n print(\"Error reading 'custom_results_parsed.log'. Ensure file exists and is readable.\")\n return\n try:\n metric = float(line1)\n except ValueError:\n print(\"Error parsing value from 'custom_results_parsed.log'.\")\n return None, None\n return metric, line2\n\n\ndef parseBWLog(path):\n try:\n fh = open(path, \"r\")\n except IOError:\n print(\"Error reading NRG log file '\" + path + \"'. Ensure file exists and is readable.\")\n return\n values = []\n for i in range(0, 4096):\n line = fh.readline()\n value = int(line[line.rfind(\",\") + 1:])\n if value != 0:\n values.append(value)\n return values\n\n\ndef parseIPGBurstLog(path): # parses both IPG and Burst log files\n try:\n fh = open(path, \"r\")\n except IOError:\n print(\"Error reading NRG log file '\" + path + \"'. Ensure file exists and is readable.\")\n return\n occurrences = []\n IPGBurst = []\n for i in range(0, 4096):\n line = fh.readline()\n value = int(line[line.rfind(\",\") + 1:])\n if value != 0:\n occurrences.append(value)\n ipgburst = int(line[0:line.find(\",\")])\n IPGBurst.append(ipgburst)\n return (IPGBurst, occurrences)\n","sub_path":"NRG/sw/gui/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":4809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"297139320","text":"from bisect import bisect_left\nfin = open('highcard.in')\nfout = open('highcard.out', 'w')\n\nn = int(fin.readline())\nopp = []\nfor i in range(n):\n opp.append(int(fin.readline()))\n\nme = []\nfor i in range(1, 2 * n + 1):\n if i not in opp:\n me.append(i)\n\nopp.sort()\nme.sort()\n\nfout.write(str(bisect_left(opp, me[-1])))\n","sub_path":"usaco/highcard.py","file_name":"highcard.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"247808201","text":"# -*- coding: utf-8 -*-\nimport os\nfrom werkzeug.contrib.cache import RedisCache\n\n'''\n Used for finding environment variables through configuration\n if a default is not given, the site will raise an exception\n'''\ndef get_env_variable(var_name, default=-1):\n try:\n return os.environ[var_name]\n except KeyError:\n if default != -1:\n return default\n error_msg = \"Set the %s os.environment variable\" % var_name\n raise Exception(error_msg)\n\n''' Base directory of where the site is held '''\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\n''' CSRF (cross site forgery) for signing POST requests to server '''\nCSRF_EN = True\n\n''' Secret key should be set in environment var '''\nSECRET_KEY = get_env_variable(\"REP_SECRET_KEY\", \"default-engon.mg-secr3t\")\n\n''' Default debugging to True '''\nDEBUG = True\nSQLALCHEMY_ECHO = True\n\n''' \n Details for connecting to the database, credentials set as environment\n variables.\n'''\nSQLALCHEMY_DATABASE_URI = \"mysql://{0}:{1}@{2}/{3}\".format(\n get_env_variable(\"REP_DB_USER\", \"repuorg_prod\"), \n get_env_variable(\"REP_DB_PW\", \"wairep\"), \n get_env_variable(\"REP_DB_HOST\", \"localhost\"),\n get_env_variable(\"REP_DB_NAME\", \"repuorg_prod\"))\n\n''' If user prefers to connect via socket set env var '''\nif \"REP_DB_SOCKET\" in os.environ:\n SQLALCHEMY_DATABASE_URI += \"?unix_socket=\" + get_env_variable(\"REP_DB_SOCKET\",\"\")\n\n''' If an env var for production is set turn off all debugging support '''\nif \"REP_PRODUCTION\" in os.environ:\n SQLALCHEMY_ECHO = False\n DEBUG = False\n\n''' Available languages '''\nLANGUAGES = {\n 'en': 'English',\n 'pt': 'Português',\n 'es': 'Espanhol'\n}\n\n''' For full text search '''\nWHOOSH_BASE = os.path.join(basedir, 'search.db')\n\n''' \n Setup redis caching connection to be used throughout the site. Credentials\n are set in their respective env vars.\n'''\nREDIS = RedisCache(host=get_env_variable(\"REP_REDIS_HOST\", \"localhost\"), \n port=get_env_variable(\"REP_REDIS_PORT\", 6379), \n password=get_env_variable(\"REP_REDIS_PW\", None), default_timeout=2591999)\n\n'''\n Oauth tokens set in environment variables from their respecive sources\n'''\nGOOGLE_OAUTH_ID = get_env_variable(\"REP_OAUTH_GOOGLE_ID\",\"435227753548-rgttj4p82lvqeaasfhsseioea5hab6f2.apps.googleusercontent.com\")\nGOOGLE_OAUTH_SECRET = get_env_variable(\"REP_OAUTH_GOOGLE_SECRET\",\"w0id6iiDwlKE1gy4sfElOfFk\")\nTWITTER_OAUTH_ID = get_env_variable(\"REP_OAUTH_TWITTER_ID\",\"Es49zEZiVnSfAvYtOcZ8nEiWP\")\nTWITTER_OAUTH_SECRET = get_env_variable(\"REP_OAUTH_TWITTER_SECRET\",\"WLzbai91qJdTD0BSMUg53ZgZ7ffR5qJ96y3chjuhocgacZcDJa\")\nFACEBOOK_OAUTH_ID = get_env_variable(\"REP_OAUTH_FACEBOOK_ID\",\"243144002561736\")\nFACEBOOK_OAUTH_SECRET = get_env_variable(\"REP_OAUTH_FACEBOOK_SECRET\",\"c2a3097c726eaca041c08e4d92c21686\")\n\n# email server GMAIL\nMAIL_PORT = 465\nMAIL_USE_TLS = False\nMAIL_USE_SSL = True\nMAIL_PASSWORD = 'repuorg'\nMAIL_SERVER = 'server.croquiteca.com.br'\nMAIL_USERNAME = 'contato@engon.org'\n\n# administrator list\nADMINS = ['mariohmol@gmail.com']\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"209105123","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 4 16:53:24 2018\n\n@author: eunsook\n\"\"\"\nimport torch\nimport torch.nn as nn\nimport torch.utils as utils\nimport torch.nn.init as init\nimport torch.utils.data as data\nimport torchvision.utils as v_utils\nimport torchvision.transforms as transforms\nfrom torch.autograd import Variable\nimport torchvision.datasets as dset\n\ndef conv_block(in_dim, out_dim, act_fn):\n model = nn.Sequential(\n nn.Conv2d(in_dim, out_dim, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm2d(out_dim),\n act_fn,\n )\n return model\n\n#%%\ndef conv_trans_block(in_dim, out_dim, act_fn):\n model = nn.Sequential(\n nn.ConvTranspose2d(in_dim, out_dim, kernel_size=3, stride=2, padding=1, output_padding=1),\n nn.BatchNorm2d(out_dim),\n act_fn,\n )\n return model\n#%%\ndef maxpool():\n pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)\n return pool\n#%%\ndef conv_block_2(in_dim, out_dim, act_fn):\n model = nn.Sequential(\n conv_block(in_dim, out_dim, act_fn),\n nn.Conv2d(out_dim, out_dim, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm2d(out_dim)\n )\n return model\n#%%\ndef conv_block_3(in_dim, out_dim, act_fn):\n model = nn.Sequential(\n conv_block(in_dim, out_dim, act_fn),\n conv_block(out_dim, out_dim, act_fn),\n nn.Conv2d(out_dim, out_dim, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm2d(out_dim),\n )\n return model\n#%%\nclass UnetGenerator(nn.Module):\n \n def __init__(self, in_dim, out_dim, num_filter):\n super(UnetGenerator, self).__init__()\n self.in_dim = in_dim\n self.out_dim = out_dim\n self.num_filter = num_filter\n act_fn = nn.LeakyReLU(0.2, inplace=True)\n \n print(\"\\n----------Init U-Net-----------\\n\")\n \n self.down_1 = conv_block_2(self.in_dim, self.num_filter, act_fn)\n self.pool_1 = maxpool()\n self.down_2 = conv_block_2(self.num_filter*1, self.num_filter*2, act_fn)\n self.pool_2 = maxpool()\n self.down_3 = conv_block_2(self.num_filter*2, self.num_filter*4, act_fn)\n self.pool_3 = maxpool()\n self.down_4 = conv_block_2(self.num_filter*4, self.num_filter*8, act_fn)\n self.pool_4 = maxpool()\n \n self.bridge = conv_block_2(self.num_filter*8, self.num_filter*16, act_fn)\n \n self.trans_1 = conv_trans_block(self.num_filter*16, self.num_filter*8, act_fn)\n self.up_1 = conv_block_2(self.num_filter*16, self.num_filter*8, act_fn)\n self.trans_2 = conv_trans_block(self.num_filter*8, self.num_filter*4, act_fn)\n self.up_2 = conv_block_2(self.num_filter*8, self.num_filter*4, act_fn)\n self.trans_3 = conv_trans_block(self.num_filter*4, self.num_filter*2, act_fn)\n self.up_3 = conv_block_2(self.num_filter*4, self.num_filter*2, act_fn)\n self.trans_4 = conv_trans_block(self.num_filter*2, self.num_filter*1, act_fn)\n self.up_4 = conv_block_2(self.num_filter*2, self.num_filter*1, act_fn)\n \n self.out = nn.Sequential(\n nn.Conv2d(self.num_filter, self.out_dim, 3, 1, 1),\n nn.Tanh(),\n )\n \n def forward(self, input):\n print(\"\\n--------forward-------\\n\")\n \n down_1 = self.down_1(input)\n pool_1 = self.pool_1(down_1)\n down_2 = self.down_2(pool_1)\n pool_2 = self.pool_2(down_2)\n down_3 = self.down_3(pool_2)\n pool_3 = self.pool_3(down_3)\n down_4 = self.down_4(pool_3)\n pool_4 = self.pool_4(down_4)\n \n bridge = self.bridge(pool_4)\n \n trans_1 = self.trans_1(bridge)\n concat_1 = torch.cat([trans_1, down_4], dim=1)\n up_1 = self.up_1(concat_1)\n trans_2 = self.trans_2(up_1)\n concat_2 = torch.cat([trans_2, down_3], dim=1)\n up_2 = self.up_2(concat_2)\n trans_3 = self.trans_3(up_2)\n concat_3 = torch.cat([trans_3, down_2], dim=1)\n up_3 = self.up_3(concat_3)\n trans_4 = self.trans_4(up_3)\n concat_4 = torch.cat([trans_4, down_1], dim=1)\n up_4 = self.up_4(concat_4)\n \n out = self.out(up_4)\n \n return out\n \n#%% main.py\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport argparse\n#%%\nif __name__ == \"__main__\":\n#%%\n #parser = argparse.ArgumentParser()\n #parser.add_argument(\"--batch_size\", type=int, default=1, help=\"batch size\")\n #parser.add_argument(\"--num_gpu\", type=int, default=1, help=\"number of gpus\")\n #args = parser.parse_args()\n \n #hyperparameters\n batch_size = 1 #args.batch_size\n img_size = 256\n lr = 0.0002\n epoch = 100\n \n #input pipeline\n #image augmentation\n img_dir = \"./maps\"\n img_data = dset.ImageFolder(root=img_dir, transform = transforms.Compose([\n transforms.Scale(size=img_size),\n transforms.CenterCrop(size=(img_size,img_size*2)),\n transforms.ToTensor(),\n ]))\n \n img_batch = data.DataLoader(img_data, batch_size=batch_size, \n shuffle=True, num_workers=2)\n \n # initiate Generator\n '''\n if args.network == \"unet\":\n #generator = nn.DataParallel(UnetGenerator(3, 3, 64), device_ids=[i for i in range(args.num_gpu)]).cuda()\n generator = UnetGenerator(3, 3, 64)\n else:\n generator = UnetGenerator(3, 3, 64)\n print(\"\\n--------not selected--------\\n\")\n '''\n generator = UnetGenerator(3, 3, 64)\n # loss function & optimizer\n recon_loss_func = nn.MSELoss()\n gen_optimizer = torch.optim.Adam(generator.parameters(), lr=lr)\n \n #training\n file = open('./unet_mse_loss', 'w')\n for i in range(epoch):\n for _, (image, label) in enumerate(img_batch):\n satel_image, map_image = torch.chunk(image, chunks=2, dim=3)\n \n gen_optimizer.zero_grad()\n \n# x = Variable(satel_image).cuda(0)\n# y_ = Variable(map_image).cuda(0)\n x = Variable(satel_image)\n y_ = Variable(map_image)\n y = generator.forward(x)\n \n loss = recon_loss_func(y, y_)\n file.write(str(loss)+\"\\n\")\n loss.backward()\n gen_optimizer.step()\n \n if _ % 400 == 0:\n print(i)\n print(loss)\n v_utils.save_image(x.cpu().data, \"./result/original_image_{}_{}.png\".format(i, _))\n v_utils.save_image(y_.cpu().data, \"./result/label_image_{}_{}.png\".format(i, _))\n v_utils.save_image(y.cpu().data, \"./result/gen_image_{}_{}.png\".format(i,_))\n torch.save(generator, './model/{}.pkl'.format(\"unet\"))\n \n ","sub_path":"U-Net/U-Net_Basic.py","file_name":"U-Net_Basic.py","file_ext":"py","file_size_in_byte":6934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"576077950","text":"x = str(input('Введите натуральное число: '))\n\neven = 0\nodd = 0\n\nfor i in x:\n if int(i) % 2 == 0:\n even += 1\n else:\n odd += 1\n\nprint(f'В числе {x} {even} четных и {odd} нечетных цифр.')\n","sub_path":"hometask02.py","file_name":"hometask02.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"259338517","text":"import os\nfrom uuid import uuid4\nimport time\n\nfrom django.db import models\nfrom django.conf import settings\n\nfrom PIL import Image\nfrom io import BytesIO\nfrom django.core.files.base import ContentFile\nfrom imageresize import imageresize\n\n\ndef user_profile_image_rename(instance, filename):\n now = time.localtime(time.time())\n upload_to = 'user/{}/{}/{}/'.format(time.strftime('%Y', now), time.strftime('%m', now), time.strftime('%d', now))\n file_ext = filename.split('.')[-1]\n file_name = '{}.{}'.format(uuid4().hex, file_ext)\n\n return os.path.join(upload_to, file_name)\n\n\nclass UserProfile(models.Model):\n user = models.OneToOneField(settings.AUTH_USER_MODEL)\n nickname = models.CharField(max_length=128, unique=True)\n comment = models.TextField(blank=True)\n image = models.ImageField(upload_to=user_profile_image_rename, null=True, blank=True)\n connects = models.ManyToManyField(\n settings.AUTH_USER_MODEL,\n related_name='connect_set',\n blank=True\n )\n ignores = models.ManyToManyField(\n settings.AUTH_USER_MODEL,\n related_name='ignore_set',\n blank=True\n )\n\n def __str__(self):\n return '{} ({})'.format(self.user.username, self.nickname)\n\n def save(self):\n uploaded_image = Image.open(self.image)\n resized_image = imageresize.resize_cover(uploaded_image, [200, 200])\n\n resized_image_io = BytesIO()\n resized_image.save(resized_image_io, format='PNG')\n\n temp_name = self.image.name\n self.image.delete(save=False)\n self.image.save(\n temp_name,\n content=ContentFile(resized_image_io.getvalue()),\n save=False\n )\n\n super(UserProfile, self).save()\n","sub_path":"profiles/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"434436354","text":"# TO-DO: Complete the selection_sort() function below\ndef selection_sort(arr):\n # loop through n-1 elements\n for i in range(0, len(arr) - 1):\n rest_of_list = arr[i:]\n next_smallest_i = rest_of_list.index(min(rest_of_list)) + i\n # swap\n current = arr[i]\n arr[i] = arr[next_smallest_i]\n arr[next_smallest_i] = current\n\n return arr\n\n\n# TO-DO: implement the Bubble Sort function below\ndef bubble_sort(arr):\n swapped = True\n while swapped:\n times_swapped = 0\n for i in range(len(arr)-1):\n first = arr[i]\n second = arr[i+1]\n if first > second:\n arr[i] = second\n arr[i+1] = first\n times_swapped += 1\n if times_swapped is 0:\n swapped = False\n\n\n return arr\n\n'''\nSTRETCH: implement the Counting Sort function below\n\nCounting sort is a sorting algorithm that works on a set of data where\nwe specifically know the maximum value that can exist in that set of\ndata. The idea behind this algorithm then is that we can create \"buckets\"\nfrom 0 up to the max value. This is most easily done by initializing an\narray of 0s whose length is the max value + 1 (why do we need this \"+ 1\"?).\n\nEach buckets[i] then is responsible for keeping track of how many times \nwe've seen `i` in the input set of data as we iterate through it.\nOnce we know exactly how many times each piece of data in the input set\nshowed up, we can construct a sorted set of the input data from the \nbuckets. \n\nWhat is the time and space complexity of the counting sort algorithm?\n'''\ndef counting_sort(arr, maximum=None):\n # exception for empty list\n if len(arr) is 0:\n return []\n # get max if none is provided\n if not maximum:\n maximum = max(arr)\n # error message if there are negative numbers in arr\n if min(arr) < 0:\n return \"Error, negative numbers not allowed in Count Sort\"\n # create buckets for all possible values in arr\n buckets = [0] * (maximum + 1)\n # count the values\n for x in arr:\n buckets[x] += 1\n # created a sorted array using the numbers from buckets as indeces\n for i in range(1, len(buckets)):\n buckets[i] += buckets[i-1]\n output = [0] * len(arr)\n for x in arr:\n output[buckets[x]-1] = x\n buckets[x] -= 1\n\n return output\n","sub_path":"src/iterative_sorting/iterative_sorting.py","file_name":"iterative_sorting.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"395725490","text":"# micropython ESP32\n# ARTIX7 specific functions\n\n# AUTHOR=EMARD\n# LICENSE=BSD\n\nfrom time import sleep_ms\nfrom machine import Pin\nfrom micropython import const\nfrom struct import pack, unpack\nfrom uctypes import addressof\n\nimport jtag\nfrom jtag import *\njtag.irlen=6\nfrom proglib import *\n\nflash_read_size = const(2048)\nflash_write_size = const(256)\nflash_erase_size = const(65536)\nflash_erase_cmd = { 4096:0x20, 32768:0x52, 65536:0xD8, 262144:0xD8 } # erase commands from FLASH PDF\nflash_erase_cmd = flash_erase_cmd[flash_erase_size]\n\nmagic=bytearray([0x59,0xA6,0x59,0xA6])\nwrenable=magic+bytearray([0,8,6])\nwrdisable=magic+bytearray([0,8,4])\nread_status=magic+bytearray([0,16,5,0])\nstatus=bytearray(2)\ndummy4=bytearray(4)\nnone=bytearray(0)\n\ndef idcode():\n bitbang_jtag_on()\n #jtag.led.on()\n reset_tap()\n runtest_idle(1,0)\n sir(9)\n id_bytes = bytearray(4)\n sdr_response(id_bytes)\n #jtag.led.off()\n bitbang_jtag_off()\n return unpack(\" capture DR\n send_tms(0) # -> shift DR\n jtag.swspi.write(a)\n jtag.swspi.write(b[:-1])\n send_data_byte_reverse(b[-1],1,8) # last byte -> exit 1 DR\n send_tms(0) # -> pause DR\n send_tms(1) # -> exit 2 DR\n send_tms(1) # -> update DR\n send_tms(1) # -> select DR scan\n\n# USER1 send a, recv b\n# a can be 0-size\n# after b, it reads one dummy bit\n@micropython.viper\ndef user1_send_recv(a,b):\n sir(2) # USER1\n send_tms(0) # -> capture DR\n send_tms(0) # -> shift DR\n jtag.swspi.write(a)\n jtag.swspi.readinto(b)\n send_tms(1) # -> exit 1 DR, dummy bit\n send_tms(0) # -> pause DR\n send_tms(1) # -> exit 2 DR\n send_tms(1) # -> update DR\n\n# common JTAG open for both program and flash\ndef common_open():\n spi_jtag_on()\n jtag.hwspi.init(sck=Pin(gpio_tcknc)) # avoid TCK-glitch\n bitbang_jtag_on()\n #jtag.led.on()\n reset_tap()\n runtest_idle(1,0)\n\n# call this before sending the bitstram\n# FPGA will enter programming mode\n# after this TAP will be in \"shift DR\" state\ndef prog_open():\n common_open()\n sir(0x3F) # BYPASS\n sir(0xB) # JPROGRAM\n runtest_idle(1,20)\n check_response(sir(0x14), mask=0x10, expected=0x10, message=\"FAIL ISC_NOOP\")\n sir(5) # CFG_IN\n # ---------- bitstream begin -----------\n # manually walk the TAP\n # we will be sending one long DR command\n send_tms(0) # -> capture DR\n send_tms(0) # -> shift DR # NOTE sent with 1 TCK glitch\n # switch from bitbanging to SPI mode\n jtag.hwspi.init(sck=Pin(gpio_tck)) # 1 TCK-glitch TDI=0\n # we are lucky that format of the bitstream tolerates\n # any leading and trailing junk bits. If it weren't so,\n # HW SPI JTAG acceleration wouldn't work.\n # to upload the bitstream:\n # FAST SPI mode\n #jtag.hwspi.write(block)\n # SLOW bitbanging mode\n #for byte in block:\n # send_data_byte_reverse(byte,0)\n\ndef prog_stream_done():\n # switch from hardware SPI to bitbanging done after prog_stream()\n jtag.hwspi.init(sck=Pin(gpio_tcknc)) # avoid TCK-glitch\n spi_jtag_off()\n\n# call this after uploading all of the bitstream blocks,\n# this will exit FPGA programming mode and start the bitstream\n# returns status True-OK False-Fail\ndef prog_close():\n bitbang_jtag_on()\n send_tms(1) # -> exit 1 DR\n send_tms(0) # -> pause DR\n send_tms(1) # -> exit 2 DR\n send_tms(1) # -> update DR\n #send_tms(0) # -> idle, disabled here as runtest_idle does the same\n runtest_idle(1,10)\n # ---------- bitstream end -----------\n sir(0xC) # JSTART\n runtest_idle(2000,0)\n reset_tap()\n #jtag.led.off()\n bitbang_jtag_off()\n return True\n\n# call this before sending the flash image\n# FPGA will enter flashing mode\n# TAP should be in \"select DR scan\" state\n@micropython.viper\ndef flash_open():\n file=\"jtagspi%08x.bit.gz\" % idcode()\n prog_stream(open_file(file,True))\n if not prog_close():\n print(\"%s failed\" % file)\n common_open()\n reset_tap()\n runtest_idle(1,0)\n # ---------- flashing begin -----------\n # 0x60 and other SPI flash commands here are bitreverse() values\n # of flash commands found in SPI FLASH datasheet.\n # e.g. 0x1B here is actually 0xD8 in datasheet, 0x60 is is 0x06 etc.\n\n@micropython.viper\ndef flash_wait_status(n:int):\n retry=n\n while retry > 0:\n user1_send(none,read_status)\n user1_send_recv(none,status)\n if (int(status[1]) & 1) == 0:\n break\n sleep_ms(1)\n retry -= 1\n if retry <= 0:\n print(\"error %d flash status 0x%02X & 1 != 0\" % (n,status[1]))\n\ndef flash_erase_block(addr=0):\n user1_send(none,wrenable)\n flash_wait_status(1001)\n req=magic+bytearray([0,32,flash_erase_cmd,addr>>16,addr>>8,addr]) # 6=SPI WRITE ENABLE\n user1_send(none,req)\n flash_wait_status(2002)\n\ndef flash_write_block(block, addr=0):\n user1_send(none,wrenable)\n flash_wait_status(114)\n # 6 = SPI WRITE ENABLE, 2 = WRITE BLOCK followed by 3-byte address and 256-byte data block\n bits=(4+len(block))*8\n req=magic+bytearray([bits>>8,bits,2,addr>>16,addr>>8,addr])\n user1_send(req,block)\n flash_wait_status(1004)\n\n# data is bytearray of to-be-read length\n# max 2048 bytes\ndef flash_read_block(data, addr=0):\n # first is the request 3=READ BLOCK, 3-byte address, 256-byte data\n bits=(len(data)+4)*8\n req=magic+bytearray([bits>>8,bits,3,addr>>16,addr>>8,addr])\n user1_send(req,data)\n # collects response from previous command\n user1_send_recv(dummy4,data)\n\n# call this after uploading all of the flash blocks,\n# this will exit FPGA flashing mode and start the bitstream\n@micropython.viper\ndef flash_close():\n # switch from SPI to bitbanging\n # ---------- flashing end -----------\n user1_send(none,wrdisable)\n sir(0xD) # JSHUTDOWN\n sir(0xB) # JPROGRAM\n runtest_idle(2000,20)\n sir(0x3F) # BYPASS\n runtest_idle(2000,0)\n spi_jtag_off()\n reset_tap()\n #jtag.led.off()\n bitbang_jtag_off()\n","sub_path":"rbp/parts/artix7lib.py","file_name":"artix7lib.py","file_ext":"py","file_size_in_byte":5761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"360507552","text":"import wandb\nimport yaml\nimport argparse\nfrom pathlib import Path\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"Versions raw dataset in Weights & Biases\")\n parser.add_argument(\n '--config',\n type=lambda p: Path(p).absolute(),\n default=Path(__file__).absolute().parents[1] / \"configs/test.yaml\",\n help=\"Path to configuration file\")\n args = parser.parse_args()\n\n with open(args.config, 'r') as stream:\n config = yaml.safe_load(stream)\n\n data_dir = Path(config[\"data\"][\"data_dir\"]).absolute()\n print(\"CONFIGURATION:\")\n print(f\"Source directory: {data_dir}\")\n ref_link = \"file://\" + str(data_dir)\n print(f\"Reference link: {ref_link}\")\n\n run = wandb.init(project=config[\"wandb\"][\"project\"],\n job_type=\"data\", tags=config[\"wandb\"][\"tags\"])\n artifact = wandb.Artifact(\"lidc-idri-cts\", type=\"dataset\",\n description=\"Sample of ten chest CTs from LIDC-IDRI dataset, converted to npy files, including metadata\")\n artifact.add_reference(ref_link)\n run.log_artifact(artifact)\n","sub_path":"scripts/init_data.py","file_name":"init_data.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"396624342","text":"import sys\n\nimport socketio\nfrom worker import Worker\nfrom PyQt5.QtCore import QThread, QUrl, Qt\nfrom PyQt5.QtWebEngineWidgets import QWebEngineView\nfrom PyQt5.QtWidgets import QApplication, QDesktopWidget, QHBoxLayout, QLabel, QVBoxLayout, QWidget\n\nsio = socketio.Client()\n\nclass Window(QWidget):\n def __init__(self):\n super().__init__()\n # setting title\n self.setWindowTitle(\"Python\")\n self.showFullScreen()\n # setting geometry\n resolution = QDesktopWidget().screenGeometry(-1)\n screenWidth = resolution.width()\n screenHeight = resolution.height()\n self.setGeometry(0, 0, screenWidth, screenHeight)\n # calling method\n self.UiComponents()\n # showing all the widgets\n self.show()\n\n def UiComponents(self):\n vbox = QVBoxLayout(self)\n hbox = QHBoxLayout()\n\n self.label = QLabel()\n self.label.setText('#: ')\n self.label.setFixedHeight(20)\n\n self.label2 = QLabel()\n self.label2.setText('CÓDIGO: ______') \n self.label2.setFixedHeight(20)\n\n hbox.addWidget(self.label, alignment=Qt.AlignLeft)\n hbox.addWidget(self.label2, alignment=Qt.AlignRight)\n\n vbox.addLayout(hbox)\n\n self.webEngineView = QWebEngineView()\n self.navigate_to_url('https://sostaskillbox.it/')\n vbox.addWidget(self.webEngineView)\n\n self.setLayout(vbox)\n self.show()\n\n self.thread = QThread()\n self.worker = Worker(self, sio)\n self.worker.moveToThread(self.thread)\n\n self.thread.started.connect(self.worker.run)\n self.thread.finished.connect(self.thread.deleteLater)\n\n self.worker.url_changed.connect(self.navigate_to_url)\n self.worker.message.connect(self.notify)\n self.worker.room.connect(self.room_name)\n\n self.thread.start()\n\n def navigate_to_url(self, page): # Does not receive the Url\n self.webEngineView.setUrl(QUrl(page))\n\n def notify(self, message):\n self.label.setText('#: {}'.format(message))\n\n def room_name(self, room): \n self.label2.setText('CÓDIGO: {}'.format(room))\n\n\n def closeEvent(self, event):\n # sio.emit('close', {})\n # sio.disconnect()\n event.ignore() # let the window close\n\ndef main():\n app = QApplication(sys.argv)\n w = Window()\n sys.exit(app.exec())\n\nif __name__ == \"__main__\":\n try:\n main()\n except Exception as e:\n sio.emit('close', {})\n sio.disconnect()\n print(e.message)","sub_path":"rpi/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"614003988","text":"\"\"\"blog URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.8/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Add an import: from blog import urls as blog_urls\n 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))\n\"\"\"\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\nfrom posts.views import Index, newBlog, blogPost, subComment, editBlog\nfrom django.contrib.auth.decorators import login_required\n\nurlpatterns = [\n url(r'^$', Index.as_view(), name='main'),\n url(r'^new$', login_required(newBlog.as_view()), name='new'),\n url(r'^(?P[-\\w]+)/(?P[\\d]+)/subcomment', login_required(subComment.as_view()), name='post_subcomment'),\n url(r'^(?P[-\\w]+)/(?P[\\d]+)', subComment.as_view(), name='subcomment'),\n url(r'^(?P[-\\w]+)/edit$', login_required(editBlog.as_view()), name='edit'),\n url(r'^(?P[-\\w]+)/edit_post$', login_required(editBlog.as_view()), name='edit_post'),\n url(r'^(?P[-\\w]+)', blogPost.as_view(), name='blogpost'),\n url(r'^(?P[-\\w]+)/comment', login_required(blogPost.as_view()), name='comment'),\n]\n","sub_path":"blog/posts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"310784502","text":"import csv\nimport os\nfrom django.core.management.base import BaseCommand, CommandError\nfrom gam_app.models import *\n\n\nclass Command(BaseCommand):\n help = \"Check that all image records in the database have a coresponding dzi file\"\n def handle(self, *args, **options):\n images = Imagen.objects.all()\n db_records = []\n for image in images:\n db_records.append(image.nombre_del_archivo + '.dzi')\n files = []\n #print(image.nombre_del_archivo)\n for file in os.listdir('/mnt/dzis'):\n if '.dzi' in file:\n files.append(file)\n else:\n continue\n\n #files with no db record\n with open('/tmp/file_no_db.txt', 'w') as nodb:\n for file in files:\n if file in db_records:\n continue\n else:\n nodb.write(file + '\\n')\n\n #db entries with no files\n with open('/tmp/db_no_file.txt', 'w') as dbnof:\n for record in db_records:\n if record in files:\n continue\n else:\n dbnof.write(record)\n","sub_path":"gam_app/management/commands/verify_files.py","file_name":"verify_files.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"50981765","text":"# uncompyle6 version 3.6.7\n# Python bytecode 2.3 (62011)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.linux-i686/egg/pyclearsilver/profiler.py\n# Compiled at: 2004-05-24 13:56:39\nimport time, who_calls, neo_cgi\nPROFILER_DATA = []\nPROFILER_START = 0\nPROFILER_ENABLED = 0\nPROFILER_DEPTH = 0\n\ndef enable():\n global PROFILER_DATA\n global PROFILER_ENABLED\n global PROFILER_START\n PROFILER_START = time.time()\n PROFILER_ENABLED = 1\n PROFILER_DATA = []\n\n\ndef disable():\n global PROFILER_DATA\n global PROFILER_ENABLED\n global PROFILER_START\n PROFILER_START = 0\n PROFILER_ENABLED = 0\n PROFILER_DATA = []\n\n\ndef hdfExport(prefix, hdf):\n n = 0\n for p in PROFILER_DATA:\n hdf.setValue('%s.%d.when' % (prefix, n), '%5.2f' % p.when)\n hdf.setValue('%s.%d.time' % (prefix, n), '%5.2f' % p.length)\n hdf.setValue('%s.%d.klass' % (prefix, n), p.klass)\n hdf.setValue('%s.%d.what' % (prefix, n), ' ' * p.depth + p.what)\n hdf.setValue('%s.%d.where' % (prefix, n), neo_cgi.htmlEscape(p.where))\n\n\nclass Profiler:\n __module__ = __name__\n\n def __init__(self, klass, what):\n global PROFILER_DEPTH\n if not PROFILER_ENABLED:\n return\n self.when = time.time() - PROFILER_START\n self.klass = klass\n self.where = who_calls.pretty_who_calls()\n self.what = what\n self.length = 0\n self.depth = PROFILER_DEPTH\n PROFILER_DEPTH = PROFILER_DEPTH + 1\n PROFILER_DATA.append(self)\n\n def end(self):\n global PROFILER_DEPTH\n if not PROFILER_ENABLED:\n return\n self.length = time.time() - self.when - PROFILER_START\n PROFILER_DEPTH = PROFILER_DEPTH - 1\n if PROFILER_DEPTH < 0:\n PROFILER_DEPTH = 0\n\n\nclass ProfilerCursor:\n __module__ = __name__\n\n def __init__(self, real_cursor):\n self.real_cursor = real_cursor\n\n def execute(self, query, args=None):\n p = Profiler('SQL', query)\n r = self.real_cursor.execute(query, args)\n p.end()\n return r\n\n def __getattr__(self, key):\n return getattr(self.real_cursor, key)","sub_path":"pycfiles/pyclearsky-0.3.0-py2.py3-none-any/profiler.py","file_name":"profiler.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"440544135","text":"#!/usr/bin/env python\n# license removed for brevity\nimport rospy\nfrom std_msgs.msg import String\nimport time\nimport sys\nimport socket\n\n\ndef talker():\n pub = rospy.Publisher('JY', String, queue_size=10) #Inicialiacion del publisher por el topico JY\n rospy.init_node('JY', anonymous=True) #Inicialiacion del nodo JY\n rate = rospy.Rate(0.000000000000000000001)\n\n while not rospy.is_shutdown():\n data, ip = socket.recvfrom(1024) #Data que le llega del socket 1024\n rospy.loginfo(data)\n pub.publish(data) #Publicador de la variable\n socket.sendto(data, ip)\n\nif __name__ == '__main__':\n socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n socket.bind((\"10.42.0.1\", 9999)) #Inicializacion del servidor en el puerto 9999\n\n try:\n talker()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"StudenProjects/2019A/roberto/src/Server1.py","file_name":"Server1.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"135481146","text":"\n\nfrom xai.brain.wordbase.nouns._poacher import _POACHER\n\n#calss header\nclass _POACHERS(_POACHER, ):\n\tdef __init__(self,): \n\t\t_POACHER.__init__(self)\n\t\tself.name = \"POACHERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"poacher\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_poachers.py","file_name":"_poachers.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"337145749","text":"#!/usr/bin/env python\n# coding: utf-8\n\nfrom argparse import (\n ArgumentParser,\n ZERO_OR_MORE\n)\n\nparser = ArgumentParser(\n prog=\"optimoida\",\n description=\"Optimize the image file by TinyPNG API.\"\n)\n\nparser.add_argument(\n \"path\",\n action=\"store\",\n metavar=\"PATH\",\n nargs=ZERO_OR_MORE,\n help=\"The image file or directory path.\")\n\nparser.add_argument(\n \"--dev\",\n action=\"store_true\",\n help=\"Run optimoida with development mode.\")\n","sub_path":"optimoida/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"486797172","text":"#Problem 2:https://leetcode.com/problems/find-k-closest-elements/\n#Test Cases passed on Leetcode \n#Binary Search Used\n#Time Complexity-O(log(n-k))\n#Space Complexity-O(k)\n\nclass Solution:\n def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:\n #Binary search approach used\n left = 0\n right = len(arr) - k\n \n while left < right:\n mid = left + (right - left)//2\n #Did not take absolute since there can be duplicates in the array\n if x - arr[mid] >arr[mid + k] - x:\n left = mid + 1\n else:\n right = mid\n return arr[left : left + k]","sub_path":"Problem2_KclosestElements.py","file_name":"Problem2_KclosestElements.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"639508777","text":"## /*******************************************************************************\n## * Copyright (c) 2000, 2004 IBM Corporation and others.\n## * All rights reserved. This program and the accompanying materials\n## * are made available under the terms of the Eclipse Public License v1.0\n## * which accompanies this distribution, and is available at\n## * http://www.eclipse.org/legal/epl-v10.html\n## *\n## * Contributors:\n## * IBM Corporation - initial API and implementation\n## *******************************************************************************/\n## /*\n## * Tree example snippet: create a tree\n## *\n## * For a list of all SWT example snippets see\n## * http://www.eclipse.org/swt/snippets/\n## */\nfrom org.eclipse.swt import SWT\nfrom org.eclipse.swt.widgets import Display, Shell, Tree, TreeItem, Menu, MenuItem, Listener\nfrom org.eclipse.swt.layout import FillLayout\n\ndisplay = Display()\nshell = Shell(display)\nshell.setLayout(FillLayout())\n\nbar = Menu(shell, SWT.BAR)\nshell.setMenuBar(bar)\nfileItem = MenuItem(bar, SWT.CASCADE)\nfileItem.setText(\"&File\")\nsubmenu = Menu(shell, SWT.DROP_DOWN)\nfileItem.setMenu(submenu)\nitem = MenuItem(submenu, SWT.PUSH)\nitem.setText(\"New TreeItem\")\n\ntree = Tree(shell, SWT.BORDER)\nfor i in range(4):\n iItem = TreeItem(tree, 0)\n iItem.setText(\"Initial - \" + str(i))\ntree.setEnabled(False)\n\nclass TreeAddListener(Listener):\n def handleEvent(self, e):\n item = TreeItem(tree, 0)\n item.setText(\"Added - 0\")\n \nitem.addListener(SWT.Selection, TreeAddListener())\n\n\nshell.setSize(200, 200)\nshell.open()\nwhile not shell.isDisposed():\n if not display.readAndDispatch():\n display.sleep()\n\ndisplay.dispose()\n","sub_path":"swt/trees/add_rows/target_ui.py","file_name":"target_ui.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"599490854","text":"def extract(m, row, col):\n res = []\n for i in range(len(m)):\n if (i != row):\n r = m[i].copy()\n r.pop(col)\n res.append(r)\n return res\n\ndef calc_det(m):\n if len(m) != len(m[0]):\n raise Exception(\"Not a square matrix!\")\n\n if len(m) == 3:\n from task6 import calc_det3x3\n return calc_det3x3(m)\n\n det = 0\n\n for i in range(len(m)):\n det += ((-1) ** (i + 2)) * m[0][i] * calc_det(extract(m, 0, i))\n\n return det\n\nif __name__ == '__main__':\n m = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]\n\n print(\"m: \" + str(m))\n print(\"det: \" + str(calc_det(m)))\n","sub_path":"src/task9.py","file_name":"task9.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"120637647","text":"#\n# this is a piece of code MAC users will need to place in\n# ~/.casa/init.py\n#\nimport os\nimport sys\nfrom os.path import join\n\ntry:\n admit_path = os.environ['ADMIT']\n sys.path.append(admit_path)\n os.environ[\"PATH\"] += os.pathsep + join(admit_path,'bin')\n os.environ[\"PATH\"] += os.pathsep + '/usr/local/bin/'\nexcept KeyError:\n print(\"ADMIT path not defined. If you wish to use ADMIT, source the admit_start.[c]sh file.\")\n","sub_path":"scripts/casa.init.py","file_name":"casa.init.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"516780881","text":"'''\r\nCreated on Sep 9, 2013\r\n\r\n@author: Steven\r\n'''\r\nimport numpy as np\r\nimport scipy.integrate as intg\r\nfrom scipy.stats import poisson\r\nimport time\r\nfrom scipy.interpolate import InterpolatedUnivariateSpline as spline\r\ntry:\r\n from pathos import multiprocessing as mp\r\n HAVE_POOL = True\r\nexcept ImportError:\r\n HAVE_POOL = False\r\n\r\n\r\ndef power_to_corr_ogata(power, k, r, N=640, h=0.005):\r\n \"\"\"\r\n Use Ogata's method for Hankel Transforms in 3D for nu=0 (nu=1/2 for 2D)\r\n to convert a given power spectrum to a correlation function.\r\n \"\"\"\r\n lnk = np.log(k)\r\n spl = spline(lnk, power)\r\n roots = np.arange(1, N + 1)\r\n t = h*roots\r\n s = np.pi*np.sinh(t)\r\n x = np.pi*roots*np.tanh(s/2)\r\n\r\n dpsi = 1 + np.cosh(s)\r\n dpsi[dpsi != 0] = (np.pi*t*np.cosh(t) + np.sinh(s))/dpsi[dpsi != 0]\r\n sumparts = np.pi*np.sin(x)*dpsi*x\r\n\r\n allparts = sumparts*spl(np.log(np.divide.outer(x, r))).T\r\n return np.sum(allparts, axis=-1)/(2*np.pi**2*r**3)\r\n\r\ndef corr_to_power_ogata(corr, r, k, N=640, h=0.005):\r\n \"\"\"\r\n Use Ogata's method for Hankel Transforms in 3D for nu=0 (nu=1/2 for 2D)\r\n to convert a given correlation function to a power spectrum\r\n \"\"\"\r\n return 8*np.pi**3 * power_to_corr_ogata(corr,r,k,N,h)\r\n\r\ndef power_to_corr_ogata_matrix(power, k, r, N=640, h=0.005):\r\n \"\"\"\r\n Use Ogata's method for Hankel Transforms in 3D for nu=0 (nu=1/2 for 2D)\r\n to convert a given power spectrum to a correlation function.\r\n\r\n In this case, `power` is a (r,k) matrix, and the computation is slightly\r\n faster for less recalculations than looping over the original.\r\n \"\"\"\r\n lnk = np.log(k)\r\n roots = np.arange(1, N + 1)\r\n t = h*roots\r\n s = np.pi*np.sinh(t)\r\n x = np.pi*roots*np.tanh(s/2)\r\n\r\n dpsi = 1 + np.cosh(s)\r\n dpsi[dpsi != 0] = (np.pi*t*np.cosh(t) + np.sinh(s))/dpsi[dpsi != 0]\r\n sumparts = np.pi*np.sin(x)*dpsi*x\r\n\r\n out = np.zeros(len(r))\r\n for ir, rr in enumerate(r):\r\n spl = spline(lnk, power[ir, :])\r\n allparts = sumparts*spl(np.log(x/rr))\r\n out[ir] = np.sum(allparts)/(2*np.pi**2*rr**3)\r\n return out\r\n\r\n\r\ndef power_to_corr(power_func, R):\r\n \"\"\"\r\n Calculate the correlation function given a power spectrum\r\n\r\n Parameters\r\n ----------\r\n power_func : callable\r\n A callable function which returns the natural log of power given lnk\r\n\r\n R : array_like\r\n The values of separation/scale to calculate the correlation at.\r\n\r\n \"\"\"\r\n if not np.iterable(R):\r\n R = [R]\r\n\r\n corr = np.zeros_like(R)\r\n\r\n # the number of steps to fit into a half-period at high-k. 6 is better than 1e-4.\r\n minsteps = 8\r\n\r\n # set min_k, 1e-6 should be good enough\r\n mink = 1e-6\r\n\r\n temp_min_k = 1.0\r\n\r\n for i, r in enumerate(R):\r\n # getting maxk here is the important part. It must be a half multiple of\r\n # pi/r to be at a \"zero\", it must be >1 AND it must have a number of half\r\n # cycles > 38 (for 1E-5 precision).\r\n\r\n min_k = (2*np.ceil((temp_min_k*r/np.pi - 1)/2) + 0.5)*np.pi/r\r\n maxk = max(501.5*np.pi/r, min_k)\r\n\r\n # Now we calculate the requisite number of steps to have a good dk at hi-k.\r\n nk = np.ceil(np.log(maxk/mink)/np.log(maxk/(maxk - np.pi/(minsteps*r))))\r\n\r\n lnk, dlnk = np.linspace(np.log(mink), np.log(maxk), nk, retstep=True)\r\n P = power_func(lnk)\r\n integ = P*np.exp(lnk)**2*np.sin(np.exp(lnk)*r)/r\r\n\r\n corr[i] = (0.5/np.pi**2)*intg.simps(integ, dx=dlnk)\r\n\r\n return corr\r\n\r\n\r\ndef exclusion_window(k, r):\r\n \"\"\"Top hat window function\"\"\"\r\n x = k*r\r\n return 3*(np.sin(x) - x*np.cos(x))/x**3\r\n\r\n# def fill_array(i,masses,sgal,centres,halo_profile,ncen,indx,pos):\r\n# m,n,ctr = masses[i], sgal[i],centres[i]\r\n#\r\n# # for i, (m, n, ctr) in enumerate(zip(masses, sgal, centres)):\r\n# #end = begin + sgal[i]\r\n# pos[ncen+indx[i]:ncen+indx[i+1]] = halo_profile.populate(n, m, ba=1, ca=1, centre=ctr)\r\n\r\ndef populate(centres, masses, halomodel=None, profile=None, hodmod=None, edges=None):\r\n \"\"\"\r\n Populate a series of DM halos with galaxies given a HOD model.\r\n\r\n Parameters\r\n ----------\r\n centres : (N,3)-array\r\n The cartesian co-ordinates of the centres of the halos\r\n\r\n masses : array_like\r\n The masses (in M_sun/h) of the halos\r\n\r\n halomodel : type :class:`halomod.HaloModel`\r\n A HaloModel object pre-instantiated. One can either use this, or\r\n *both* `halo_profile` and `hodmod` arguments.\r\n\r\n profile : type :class:`halo_profile.Profile`\r\n A density halo_profile to use.\r\n\r\n hodmod : object of type :class:`hod.HOD`\r\n A HOD model to use to populate the dark matter.\r\n\r\n edges : float, len(2) iterable, or (2,3)-array\r\n Periodic box edges. If float, defines the upper limit of cube, with lower limit at zero.\r\n If len(2) iterable, defines edges of cube.\r\n If (2,3)-array, specifies edges of arbitrary rectangular prism.\r\n\r\n Returns\r\n -------\r\n pos : array\r\n (N,3)-array of positions of galaxies.\r\n\r\n halo : array\r\n (N)-array of associated haloes (by index)\r\n\r\n H : int\r\n Number of central galaxies. The first H galaxies in pos/halo correspond to centrals.\r\n \"\"\"\r\n if halomodel is not None:\r\n profile = halomodel.halo_profile\r\n hodmod = halomodel.hod\r\n\r\n masses = np.array(masses)\r\n\r\n # Define which halos have central galaxies.\r\n cgal = np.random.binomial(1, hodmod.central_occupation(masses))\r\n cmask = cgal > 0\r\n central_halos = np.arange(len(masses))[cmask]\r\n\r\n if hodmod._central:\r\n masses = masses[cmask]\r\n centres = centres[cmask]\r\n\r\n # Calculate the number of satellite galaxies in halos\r\n # Using ns, rather than ns, gives the correct answer for both central condition and not.\r\n # Note that other parts of the algorithm also need to be changed if central condition is not true.\r\n # if hodmod._central:\r\n # sgal = poisson.rvs(hodmod.ns(masses[cmask]))\r\n # else:\r\n sgal = poisson.rvs(hodmod.ns(masses))\r\n\r\n # Get an array ready, hopefully speeds things up a bit\r\n ncen = np.sum(cgal)\r\n nsat = np.sum(sgal)\r\n\r\n pos = np.empty((ncen + nsat, 3))\r\n halo = np.empty(ncen+nsat)\r\n\r\n # Assign central galaxy positions\r\n halo[:ncen] = central_halos\r\n if hodmod._central:\r\n pos[:ncen, :] = centres\r\n else:\r\n pos[:ncen, :] = centres[cmask]\r\n\r\n\r\n smask = sgal > 0\r\n # if hodmod._central:\r\n # sat_halos = central_halos[np.arange(len(masses[cmask]))[smask]]\r\n # else:\r\n if hodmod._central:\r\n sat_halos = central_halos[np.arange(len(masses))[smask]]\r\n else:\r\n sat_halos = np.arange(len(masses))[smask]\r\n\r\n sgal = sgal[smask]\r\n centres = centres[smask]\r\n masses = masses[smask]\r\n\r\n # Now go through each halo and calculate galaxy positions\r\n start = time.time()\r\n halo[ncen:] = np.repeat(sat_halos,sgal)\r\n indx = np.concatenate(([0],np.cumsum(sgal))) + ncen\r\n\r\n# print \"SMASHING THIS NOW\"\r\n def fill_array(i):\r\n m,n,ctr = masses[i], sgal[i],centres[i]\r\n pos[indx[i]:indx[i+1],:] = profile.populate(n, m, ba=1, ca=1, centre=ctr)\r\n\r\n if HAVE_POOL:\r\n mp.ProcessingPool(mp.cpu_count()).map(fill_array,list(range(len(masses))))\r\n else:\r\n for i in range(len(masses)):\r\n fill_array(i)\r\n\r\n nhalos_with_gal = len(set(central_halos.tolist()+sat_halos.tolist()))\r\n\r\n print(\"Took \", time.time() - start, \" seconds, or \", (time.time() - start)/nhalos_with_gal, \" each halo.\")\r\n print(\"NhalosWithGal: \", nhalos_with_gal, \", Ncentrals: \", ncen,\", NumGal: \", len(halo), \", MeanGal: \", float(\r\n len(halo))/nhalos_with_gal, \", MostGal: \", sgal.max() + 1 if len(sgal)>0 else 1)\r\n\r\n if edges is None:\r\n pass\r\n elif np.isscalar(edges):\r\n edges = np.array([[0, 0, 0], [edges, edges, edges]])\r\n elif np.array(edges).shape == (2,):\r\n edges = np.array([[edges[0]]*3, [edges[1]]*3])\r\n\r\n if edges is not None:\r\n for j in range(3):\r\n d = pos[:, j] - edges[0][j]\r\n pos[d < 0, j] = edges[1][j] + d[d < 0]\r\n d = pos[:, j] - edges[1][j]\r\n pos[d > 0, j] = edges[0][j] + d[d > 0]\r\n\r\n return pos, halo.astype(\"int\"), ncen\r\n","sub_path":"halomod/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":8316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"103771346","text":"# -*- coding: utf-8 -*-\nimport unittest\n\nimport six\nfrom mongoengine import connect, Document, StringField\nfrom mongoengine import signals\nfrom mongoengine.connection import register_db, disconnect\n\nsignal_output = []\n\n\nclass BaseSignalTests(unittest.TestCase):\n\n maxDiff = None\n\n def get_signal_output(self, fn, *args, **kwargs):\n # Flush any existing signal output\n global signal_output\n signal_output = []\n fn(*args, **kwargs)\n return signal_output\n\n\nclass ConnectSignalTests(BaseSignalTests):\n \"\"\"\n Testing signals before/after connecting.\n \"\"\"\n\n def setUp(self):\n # Save up the number of connected signals so that we can check at\n # the end that all the signals we register get properly unregistered\n self.pre_signals = (\n len(signals.pre_connect.receivers),\n len(signals.post_connect.receivers),\n )\n\n self.pre_connect = lambda sender, settings: signal_output.append(\n 'pre_connect: sender={sender} settings={settings!r}'.format(\n sender=sender,\n settings=sorted(settings.keys()),\n )\n )\n self.post_connect = lambda sender, settings, connection: signal_output.append(\n 'post_connect: sender={sender} settings={settings!r} connection={connection!r}'.format(\n sender=sender,\n settings=sorted(settings.keys()),\n connection=type(connection),\n )\n )\n signals.pre_connect.connect(self.pre_connect)\n signals.post_connect.connect(self.post_connect)\n\n # make sure we're not connected already\n disconnect()\n disconnect('nondefault')\n\n def tearDown(self):\n signals.pre_connect.disconnect(self.pre_connect)\n signals.post_connect.disconnect(self.post_connect)\n # Check that all our signals got disconnected properly.\n post_signals = (\n len(signals.pre_connect.receivers),\n len(signals.post_connect.receivers),\n )\n self.assertEqual(self.pre_signals, post_signals)\n\n def test_new_connection(self):\n \"\"\" Call to connect() should fire the pre/post signals. \"\"\"\n self.assertEqual(self.get_signal_output(connect), [\n \"pre_connect: sender=default settings=['host', 'port', 'read_preference']\",\n \"post_connect: sender=default settings=['host', 'port', 'read_preference'] connection=\",\n ])\n self.assertEqual(self.get_signal_output(connect, 'nondefault'), [\n \"pre_connect: sender=nondefault settings=['host', 'port', 'read_preference']\",\n \"post_connect: sender=nondefault settings=['host', 'port', 'read_preference'] connection=\",\n ])\n\n def test_unknown_alias_connection(self):\n \"\"\" Call to connect() should not fire the pre/post signals for unknown db alias. \"\"\"\n\n def test_already_connected(self):\n \"\"\" Repeat call to connect() should not fire the pre/post signals. \"\"\"\n connect(alias='default', host='mongo')\n self.assertEqual(self.get_signal_output(connect), [])\n\n\nclass DocumentSignalTests(BaseSignalTests):\n \"\"\"\n Testing signals before/after saving and deleting.\n \"\"\"\n\n def setUp(self):\n connect(alias='default', host='mongo')\n register_db('mongoenginetest')\n\n @six.python_2_unicode_compatible\n class Author(Document):\n name = StringField()\n\n def __str__(self):\n return str(self.name)\n\n @classmethod\n def pre_init(cls, sender, document, *args, **kwargs):\n signal_output.append('pre_init signal, %s' % cls.__name__)\n signal_output.append(str(kwargs['values']))\n\n @classmethod\n def post_init(cls, sender, document, **kwargs):\n signal_output.append('post_init signal, %s' % document)\n\n @classmethod\n def pre_save(cls, sender, document, **kwargs):\n signal_output.append('pre_save signal, %s' % document)\n\n @classmethod\n def post_save(cls, sender, document, **kwargs):\n signal_output.append('post_save signal, %s' % document)\n if 'created' in kwargs:\n if kwargs['created']:\n signal_output.append('Is created')\n else:\n signal_output.append('Is updated')\n\n @classmethod\n def pre_delete(cls, sender, document, **kwargs):\n signal_output.append('pre_delete signal, %s' % document)\n\n @classmethod\n def post_delete(cls, sender, document, **kwargs):\n signal_output.append('post_delete signal, %s' % document)\n\n @classmethod\n def pre_bulk_insert(cls, sender, documents, **kwargs):\n signal_output.append('pre_bulk_insert signal, %s' % documents)\n\n @classmethod\n def post_bulk_insert(cls, sender, documents, **kwargs):\n signal_output.append('post_bulk_insert signal, %s' % documents)\n if kwargs.get('loaded', False):\n signal_output.append('Is loaded')\n else:\n signal_output.append('Not loaded')\n self.Author = Author\n\n @six.python_2_unicode_compatible\n class Another(Document):\n name = StringField()\n\n def __str__(self):\n return str(self.name)\n\n @classmethod\n def pre_init(cls, sender, document, **kwargs):\n signal_output.append(\n 'pre_init Another signal, %s' % cls.__name__)\n signal_output.append(str(kwargs['values']))\n\n @classmethod\n def post_init(cls, sender, document, **kwargs):\n signal_output.append('post_init Another signal, %s' % document)\n\n @classmethod\n def pre_save(cls, sender, document, **kwargs):\n signal_output.append('pre_save Another signal, %s' % document)\n\n @classmethod\n def post_save(cls, sender, document, **kwargs):\n signal_output.append('post_save Another signal, %s' % document)\n if 'created' in kwargs:\n if kwargs['created']:\n signal_output.append('Is created')\n else:\n signal_output.append('Is updated')\n\n @classmethod\n def pre_delete(cls, sender, document, **kwargs):\n signal_output.append('pre_delete Another signal, %s' % document)\n\n @classmethod\n def post_delete(cls, sender, document, **kwargs):\n signal_output.append(\n 'post_delete Another signal, %s' % document)\n\n self.Another = Another\n # Save up the number of connected signals so that we can check at\n # the end that all the signals we register get properly unregistered\n self.pre_signals = (\n len(signals.pre_init.receivers),\n len(signals.post_init.receivers),\n len(signals.pre_save.receivers),\n len(signals.post_save.receivers),\n len(signals.pre_delete.receivers),\n len(signals.post_delete.receivers),\n len(signals.pre_bulk_insert.receivers),\n len(signals.post_bulk_insert.receivers),\n )\n\n signals.pre_init.connect(Author.pre_init, sender=Author)\n signals.post_init.connect(Author.post_init, sender=Author)\n signals.pre_save.connect(Author.pre_save, sender=Author)\n signals.post_save.connect(Author.post_save, sender=Author)\n signals.pre_delete.connect(Author.pre_delete, sender=Author)\n signals.post_delete.connect(Author.post_delete, sender=Author)\n signals.pre_bulk_insert.connect(Author.pre_bulk_insert, sender=Author)\n signals.post_bulk_insert.connect(Author.post_bulk_insert, sender=Author)\n\n signals.pre_init.connect(Another.pre_init, sender=Another)\n signals.post_init.connect(Another.post_init, sender=Another)\n signals.pre_save.connect(Another.pre_save, sender=Another)\n signals.post_save.connect(Another.post_save, sender=Another)\n signals.pre_delete.connect(Another.pre_delete, sender=Another)\n signals.post_delete.connect(Another.post_delete, sender=Another)\n\n def tearDown(self):\n signals.pre_init.disconnect(self.Author.pre_init)\n signals.post_init.disconnect(self.Author.post_init)\n signals.post_delete.disconnect(self.Author.post_delete)\n signals.pre_delete.disconnect(self.Author.pre_delete)\n signals.post_save.disconnect(self.Author.post_save)\n signals.pre_save.disconnect(self.Author.pre_save)\n signals.pre_bulk_insert.disconnect(self.Author.pre_bulk_insert)\n signals.post_bulk_insert.disconnect(self.Author.post_bulk_insert)\n\n signals.pre_init.disconnect(self.Another.pre_init)\n signals.post_init.disconnect(self.Another.post_init)\n signals.post_delete.disconnect(self.Another.post_delete)\n signals.pre_delete.disconnect(self.Another.pre_delete)\n signals.post_save.disconnect(self.Another.post_save)\n signals.pre_save.disconnect(self.Another.pre_save)\n\n # Check that all our signals got disconnected properly.\n post_signals = (\n len(signals.pre_init.receivers),\n len(signals.post_init.receivers),\n len(signals.pre_save.receivers),\n len(signals.post_save.receivers),\n len(signals.pre_delete.receivers),\n len(signals.post_delete.receivers),\n len(signals.pre_bulk_insert.receivers),\n len(signals.post_bulk_insert.receivers),\n )\n\n self.assertEqual(self.pre_signals, post_signals)\n\n def test_model_signals(self):\n \"\"\" Model saves should throw some signals. \"\"\"\n\n def create_author():\n self.Author(name='Bill Shakespeare')\n\n def bulk_create_author_with_load():\n a1 = self.Author(name='Bill Shakespeare')\n self.Author.objects.insert([a1], load_bulk=True)\n\n def bulk_create_author_without_load():\n a1 = self.Author(name='Bill Shakespeare')\n self.Author.objects.insert([a1], load_bulk=False)\n\n self.assertEqual(self.get_signal_output(create_author), [\n \"pre_init signal, Author\",\n \"{'name': 'Bill Shakespeare'}\",\n \"post_init signal, Bill Shakespeare\",\n ])\n\n a1 = self.Author(name='Bill Shakespeare')\n self.assertEqual(self.get_signal_output(a1.save), [\n \"pre_save signal, Bill Shakespeare\",\n \"post_save signal, Bill Shakespeare\",\n \"Is created\"\n ])\n\n a1.reload()\n a1.name = 'William Shakespeare'\n self.assertEqual(self.get_signal_output(a1.save), [\n \"pre_save signal, William Shakespeare\",\n \"post_save signal, William Shakespeare\",\n \"Is updated\"\n ])\n\n self.assertEqual(self.get_signal_output(a1.delete), [\n 'pre_delete signal, William Shakespeare',\n 'post_delete signal, William Shakespeare',\n ])\n\n signal_output = self.get_signal_output(bulk_create_author_with_load)\n\n # The output of this signal is not entirely deterministic. The reloaded\n # object will have an object ID. Hence, we only check part of the output\n self.assertEqual(\n signal_output[3],\n \"pre_bulk_insert signal, []\")\n self.assertEqual(\n signal_output[-2:],\n [\"post_bulk_insert signal, []\",\n \"Is loaded\"])\n\n self.assertEqual(\n self.get_signal_output(bulk_create_author_without_load),\n [\"pre_init signal, Author\",\n \"{'name': 'Bill Shakespeare'}\",\n \"post_init signal, Bill Shakespeare\",\n \"pre_bulk_insert signal, []\",\n \"post_bulk_insert signal, []\",\n \"Not loaded\"])\n\n self.Author.objects.delete()\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":12337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"92029635","text":"import datetime\nfrom app.emails.apply import prijava_februar\nfrom app.handlers.base import Handler\nfrom app.models.auth import User\nfrom app.models.course import CourseType, Course, CourseApplication\nfrom app.utils.decorators import admin_required\n\n\nclass AdminCourseApplicationDetailsHandler(Handler):\n @admin_required\n def get(self, application_id):\n application = CourseApplication.get_by_id(int(application_id))\n params = {\"application\": application}\n self.render_template(\"admin/application_details.html\", params)\n\n @admin_required\n def post(self, application_id):\n application = CourseApplication.get_by_id(int(application_id))\n application.payment_status = bool(self.request.get(\"paid\"))\n application.price = float(self.request.get(\"price\"))\n application.put()\n self.redirect_to(\"course-details\", course_id=application.course_id)\n\n\nclass AdminCourseApplicationDeleteHandler(Handler):\n @admin_required\n def get(self, application_id):\n application = CourseApplication.get_by_id(int(application_id))\n params = {\"application\": application}\n self.render_template(\"admin/application_delete.html\", params)\n\n @admin_required\n def post(self, application_id):\n application = CourseApplication.get_by_id(int(application_id))\n application.deleted = True\n application.put()\n course = Course.get_by_id(int(application.course_id))\n course.taken -= 1\n course.put()\n self.redirect_to(\"course-details\", course_id=application.course_id)\n\n\n# TODO: just temporary, delete after feb 2015\nclass TempPrijavaHandler(Handler):\n def post(self):\n hidden = self.request.get(\"hidden\")\n if hidden:\n return self.redirect_to(\"temp\")\n else:\n ime = self.request.get(\"firstname\")\n priimek = self.request.get(\"lastname\")\n email = self.request.get(\"email\").strip()\n naslov = self.request.get(\"address\")\n starost = self.request.get(\"age\")\n telefon = self.request.get(\"phone2\")\n kraj_tecaja = self.request.get(\"country\")\n kotizacija = self.request.get(\"sleepover\")\n prenosnik = self.request.get(\"prenosnik\")\n majica = self.request.get(\"majica\")\n\n if ime and priimek and email and naslov and starost and telefon and kraj_tecaja and kotizacija and prenosnik and majica:\n user = User.get_by_email(email)\n\n if not user:\n # add to database\n user = User.create(first_name=ime, last_name=priimek, email=email, address=naslov, dob=starost, phone_number=telefon)\n\n add_user_to_course(user=user, kraj_tecaja=kraj_tecaja, kotizacija=float(kotizacija), prenosnik=prenosnik, majica=majica)\n\n # send email\n prijava_februar(ime, priimek, email, naslov, starost, telefon, kraj_tecaja, kotizacija, prenosnik, majica)\n params = {\"error\": \"Prijava oddana! :)\"}\n else:\n params = {\"error\": \"Prosim izpolni vsa polja\"}\n self.render_template(\"public/main2.html\", params)\n\n\n# TODO: just temporary, delete after feb 2015\ndef add_user_to_course(user, kraj_tecaja, kotizacija, prenosnik, majica):\n course_type = CourseType.query(CourseType.title == \"SmartNinja Vikend Slovenia\").get()\n if not course_type:\n course_type = CourseType()\n course_type.title = \"SmartNinja Vikend Slovenia\"\n course_type.put()\n\n course = None\n\n price = [97.00, 147.00, 197.00]\n\n if kraj_tecaja == \"Ljubljana\":\n course = Course.query(Course.title == \"SmartNinja Vikend Ljubljana\").get()\n if not course:\n course = Course.create(title=\"SmartNinja Vikend Ljubljana\", city=\"Ljubljana\", start_date=datetime.date(2015, 2, 7),\n end_date=datetime.date(2015, 2, 8), description=\"\", price=price, place=\"\",\n course_type=course_type.get_id, currency=\"EUR\", spots=10)\n elif kraj_tecaja == \"Maribor\":\n course = Course.query(Course.title == \"SmartNinja Vikend Maribor\").get()\n if not course:\n course = Course.create(title=\"SmartNinja Vikend Maribor\", city=\"Maribor\", start_date=datetime.date(2015, 2, 14),\n end_date=datetime.date(2015, 2, 15), description=\"\", price=price, place=\"\",\n course_type=course_type.get_id, currency=\"EUR\", spots=10)\n elif kraj_tecaja == \"NovaGorica\":\n course = Course.query(Course.title == \"SmartNinja Vikend Nova Gorica\").get()\n if not course:\n course = Course.create(title=\"SmartNinja Vikend Nova Gorica\", city=\"Nova Gorica\", start_date=datetime.date(2015, 2, 28),\n end_date=datetime.date(2015, 3, 1), description=\"\", price=price, place=\"\",\n course_type=course_type.get_id, currency=\"EUR\", spots=10)\n\n if course:\n course_app = CourseApplication.create(course_title=course.title, course_id=course.get_id, student_name=user.get_full_name,\n student_id=user.get_id, student_email=user.email, price=kotizacija, currency=\"EUR\",\n laptop=prenosnik, shirt=majica)\n course.taken += 1\n course.put()","sub_path":"app/handlers/apply.py","file_name":"apply.py","file_ext":"py","file_size_in_byte":5417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"325312173","text":"import os\nimport subprocess\nimport time\n\nimport grpc\nimport pytest\n\nimport dataclay\n\n\n@pytest.fixture(scope=\"session\")\ndef docker_compose_command():\n return \"docker compose\"\n\n\n@pytest.fixture(scope=\"session\")\ndef docker_compose_file(pytestconfig):\n return os.path.join(str(pytestconfig.rootdir), \"tests/functional\", \"docker-compose.yml\")\n\n\n@pytest.fixture(scope=\"session\")\ndef deploy_dataclay(docker_ip, docker_services):\n \"\"\"Ensure that services are up and responsive.\"\"\"\n\n mds_port = docker_services.port_for(\"metadata-service\", 16587)\n grpc.channel_ready_future(grpc.insecure_channel(f\"127.0.0.1:{mds_port}\")).result(timeout=10)\n\n # backend_port = docker_services.port_for(\"backend\", 6867)\n # grpc.channel_ready_future(grpc.insecure_channel(f\"127.0.0.1:{backend_port}\")).result(timeout=10)\n\n\n@pytest.fixture(scope=\"session\")\ndef client(deploy_dataclay):\n client = dataclay.client(\n host=\"127.0.0.1\", username=\"testuser\", password=\"s3cret\", dataset=\"testuser\"\n )\n client.start()\n yield client\n client.stop()\n","sub_path":"tests/functional/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"191301646","text":"from direct.showbase.ShowBase import ShowBase\nfrom panda3d.core import Texture\n\ndata = open(\"/tmp/yabee_exported\", \"r\").read()\nbase = ShowBase()\negg_file = base.loader.loadModel(data)\n\nfor tex in render.findAllTextures():\n if tex.get_num_components() == 3:\n tex.setFormat(Texture.F_srgb)\n elif tex.get_num_components() == 4:\n tex.setFormat(Texture.F_srgb_alpha)\n\nname = \"/tmp/{0}.bam\".format(egg_file.get_name())\negg_file.writeBamFile(name)\n\n","sub_path":"yabee_libs/egg_worker.py","file_name":"egg_worker.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"388482984","text":"import os\nos.chdir(\"FlexNet Upgrades/Lego\")\nimport random\nimport matplotlib.pyplot as plt\nimport datetime\nimport time\nimport cv2\nimport pickle\nfrom tqdm import tqdm\nimport numpy as np\n\nimport FlexNet as flex\n\nimport torch\nfrom torchvision import datasets, models, transforms\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\n# For reproducibility\nseed = 3\ntorch.manual_seed(seed)\nnp.random.seed(seed)\nrandom.seed(seed)\ntorch.cuda.manual_seed_all(seed)\ntorch.backends.cudnn.benchmark = False\ntorch.backends.cudnn.deterministic = True\n\nbase_dir = \"C:/Datasets/PJF-30/data/\"\nsave_dir = \"C:/Datasets/PJF-30/safe/\"\ncategorys = [[1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11, 12, 13]]\n\ntrain = []\ntest = []\n\nif False:\n for indx, cat in tqdm(enumerate(categorys)):\n out_train = []\n out_test = []\n for subindx, dir in tqdm(enumerate(cat)):\n path = base_dir + str(dir) + \"/comp/\"\n for num, img in enumerate(os.listdir(path)):\n try:\n img_in = cv2.imread((path + \"/\" + img), cv2.IMREAD_COLOR)\n img_resz = cv2.resize(img_in, (224, 224))\n if num < 2000:\n out_train.append([img_resz, indx, dir])\n else:\n out_test.append([img_resz, indx, dir])\n except Exception as e: pass\n random.shuffle(train)\n random.shuffle(test)\n train += out_train #[:6000]\n test += out_test #[:1500]\n print(len(train), len(test))\n\n # train = np.array(train)\n pickle_out = open((save_dir + \"fl_lego.pickle\"),\"wb\")\n pickle.dump(train, pickle_out)\n pickle_out.close()\n pickle_out = open((save_dir + \"fl_lego_t.pickle\"),\"wb\")\n pickle.dump(test, pickle_out)\n pickle_out.close()\nelse:\n pickle_in = open(save_dir + \"fl_lego.pickle\",\"rb\")\n train = pickle.load(pickle_in)\n pickle_in = open(save_dir + \"fl_lego_t.pickle\",\"rb\")\n test = pickle.load(pickle_in)\nl = len(train)\nlt = len(test)\nprint(len(train), len(test))\nrandom.shuffle(train)\nrandom.shuffle(test)\n\ntrain_on_gpu = torch.cuda.is_available()\ntheCPU = torch.device(\"cpu\")\n\nif not train_on_gpu:\n device = torch.device(\"cpu\")\n print('CUDA is not available. Training on CPU ...')\nelse:\n device = torch.device(\"cuda:0\")\n print('CUDA is available! Training on GPU ...')\n\nX, y, c, Xt, yt, ct = [], [], [], [], [], []\n\nfor features, cat, clas in train:\n X.append(features)\n y.append(clas)\n c.append(cat)\nfor features, cat, clas in test:\n Xt.append(features)\n yt.append(clas)\n ct.append(cat)\ntemp = np.array(y)\nprint(np.max(temp))\nX = np.array(X, dtype=np.float32) / 255\ny = np.array(y, dtype=np.int64)\nXt = np.array(Xt, dtype=np.float32) / 255\nyt = np.array(yt, dtype=np.int64)\nprint(np.max(X[0]), np.max(Xt[0]))\n\nX = torch.from_numpy(X)\ny = torch.from_numpy(y)\nX.to(torch.float32)\ny.to(torch.int64)\nprint(X.dtype, y.dtype)\nXt = torch.from_numpy(Xt)\nyt = torch.from_numpy(yt)\nXt.to(torch.float32)\nyt.to(torch.int64)\nprint(Xt.dtype, yt.dtype)\nprint(y[10:], yt[:10])\n\n# check = [0, 0]\n# for i in range(l):\n# check[c[i].numpy()] += 1\n# print(check)\n# check = [0, 0]\n# for i in range(lt):\n# check[ct[i].numpy()] += 1\n# print(check)\n\ntotal = 0\nclass_correct = 0\ncategory_correct = 0\n\ncat_check = [0, 0, 0]\ncat_total = [0, 0, 0]\nclass_check = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n\nfor i in tqdm(range(len(Xt))):\n input_tensor = Xt[i].view(-1, 3, 224, 224).to(device)\n correct_class = yt[i].cpu().numpy().tolist()\n predicted_category, predicted_class = flex.predict(input_tensor)\n if predicted_category == ct[i]:\n category_correct += 1\n cat_check[predicted_category] += 1\n cat_total[ct[i]] += 1\n if predicted_class == correct_class:\n class_correct += 1\n class_check[predicted_class-1] += 1\n total += 1\n\nprint(total, category_correct, class_correct)\nprint(\"--> \", round(category_correct / total, 3), round(class_correct / total, 3))\nprint(cat_check, class_check)\nprint(\"Category accuracy: \", [round(cat_check[i] / cat_total[i], 3) for i in range(len(cat_total))])\n\n# Test: 6500, 5755, 5209 --> 0.885, 0.801 (1m 1s)\n# Cat_Check: [1263, 1725, 2767] Class_Check: [420, 446, 375, 453, 422, 406, 414, 408, 409, 403, 480, 232, 341]\n# Category accuracy: [0.842, 0.863, 0.922]\n# Train: 26000, 25695, 24540 --> 0.988, 0.944 (3m 59s)\n# Cat_Check: [5927, 7850, 11918] Class_Check: [1967, 1977, 1974, 1975, 1961, 1952, 1962, 1935, 1892, 1908, 1996, 1314, 1727]\n# Category accuracy: [0.988, 0.981, 0.993]","sub_path":"FlexNet Upgrades/Lego/Test FlexNet.py","file_name":"Test FlexNet.py","file_ext":"py","file_size_in_byte":4614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"522643582","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Mar 25 12:43:48 2020\r\n\r\n@author: 22631228\r\n\"\"\"\r\n\r\n# Download 4 band planet scope scenes for Ba\r\n\r\nimport os\r\nimport json\r\nimport requests\r\nfrom requests.auth import HTTPBasicAuth\r\nimport time\r\nfrom os import environ\r\nfrom tqdm import tqdm\r\nimport zipfile\r\n\r\n# Some initial variables\r\n# Set API key (this should to be an environment variable)\r\napi_key = \"f6092e3140d849fe82dff89dffc64634\"\r\n\r\nitem_type = \"PSScene4Band\"\r\n\r\nasset_type = \"analytic_sr\"\r\n\r\nstart_date = \"2019-06-01T00:00:00.000Z\"\r\n\r\nend_date = \"2019-09-05T00:00:00.000Z\"\r\n\r\n# Filter scenes by cloud cover, date, and study site\r\nstudy_area = {\r\n \"type\": \"Polygon\",\r\n \"coordinates\": [\r\n [\r\n [\r\n 116.17584943771361,\r\n -31.995010634179685\r\n ],\r\n [\r\n 116.18241548538207,\r\n -31.995010634179685\r\n ],\r\n [\r\n 116.18241548538207,\r\n -31.98753089855013\r\n ],\r\n [\r\n 116.17584943771361,\r\n -31.98753089855013\r\n ],\r\n [\r\n 116.17584943771361,\r\n -31.995010634179685\r\n ]\r\n ]\r\n ]\r\n}\r\n\r\n# get images that overlap with our AOI\r\ngeometry_filter = {\r\n \"type\": \"GeometryFilter\",\r\n \"field_name\": \"geometry\",\r\n \"config\": study_area\r\n}\r\n\r\n# get images acquired within a date range\r\ndate_range_filter = {\r\n \"type\": \"DateRangeFilter\",\r\n \"field_name\": \"acquired\",\r\n \"config\": {\r\n \"gte\": start_date,\r\n \"lte\": end_date\r\n }\r\n}\r\n\r\n# only get images which have <50% cloud coverage\r\ncloud_cover_filter = {\r\n \"type\": \"RangeFilter\",\r\n \"field_name\": \"cloud_cover\",\r\n \"config\": {\r\n \"lte\": 0.5\r\n }\r\n}\r\n\r\n# combine our geo, date, cloud filters\r\ncombined_filter = {\r\n \"type\": \"AndFilter\",\r\n \"config\": [geometry_filter, date_range_filter, cloud_cover_filter]\r\n}\r\n\r\n# API request object\r\nsearch_request = {\r\n \"interval\": \"day\",\r\n \"item_types\": [item_type],\r\n \"filter\": combined_filter\r\n}\r\n\r\n# fire off the POST request\r\nsearch_result = \\\r\n requests.post(\r\n 'https://api.planet.com/data/v1/quick-search',\r\n auth=HTTPBasicAuth(api_key, ''),\r\n json=search_request)\r\n\r\n#print(json.dumps(search_result.json(), indent=1))\r\n\r\nimage_ids = [feature['id'] for feature in search_result.json()['features']]\r\nprint(image_ids)\r\n#image_ids = image_ids[0:4] # this is just for testing\r\n\r\n# study area for clipping server side\r\naoi_json = '''{\r\n \"type\": \"Polygon\",\r\n \"coordinates\": [\r\n [\r\n [\r\n 116.17584943771361,\r\n -31.995010634179685\r\n ],\r\n [\r\n 116.18241548538207,\r\n -31.995010634179685\r\n ],\r\n [\r\n 116.18241548538207,\r\n -31.98753089855013\r\n ],\r\n [\r\n 116.17584943771361,\r\n -31.98753089855013\r\n ],\r\n [\r\n 116.17584943771361,\r\n -31.995010634179685\r\n ]\r\n ]\r\n ]\r\n}'''\r\n\r\n# iterate over each scene in study area, within date range, and with < 50% cloud cover\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#r = requests.get(asset['_links']['_self'], auth=(api_key, ''))\r\nQUOTA_URL = 'https://api.planet.com/auth/v1/experimental/public/my/subscriptions'\r\n\r\nr = requests.get(QUOTA_URL, auth=(api_key, ''))\r\nl = r.json()\r\nl\r\n\r\n\r\n\r\n# clip scene and download\r\nloss = []\r\nfor i in image_ids:\r\n print(i)\r\n\r\n # Sent Scene ID\r\n scene_id = i\r\n txtfile = r\"D:\\#DATA\\EE_processing\\downloaded_scenes.txt\"\r\n # create / open file containing scenes already downloaded\r\n f = open(txtfile, \"r\")\r\n downloaded_scenes = f.read()\r\n\r\n if i not in downloaded_scenes:\r\n\r\n # Construct clip API payload\r\n clip_payload = {\r\n 'aoi': json.loads(aoi_json),\r\n 'targets': [\r\n {\r\n 'item_id': scene_id,\r\n 'item_type': item_type,\r\n 'asset_type': asset_type\r\n }\r\n ]\r\n }\r\n \r\n try:\r\n # Request clip of scene (This will take some time to complete)\r\n request = requests.post('https://api.planet.com/compute/ops/clips/v1', auth=(api_key, ''), json=clip_payload)\r\n clip_url = request.json()['_links']['_self']\r\n \r\n # Poll API to monitor clip status. Once finished, download and upzip the scene\r\n clip_succeeded = False\r\n while not clip_succeeded:\r\n \r\n # Poll API\r\n check_state_request = requests.get(clip_url, auth=(api_key, ''))\r\n \r\n # If clipping process succeeded , we are done\r\n if check_state_request.json()['state'] == 'succeeded':\r\n clip_download_url = check_state_request.json()['_links']['results'][0]\r\n clip_succeeded = True\r\n print(\"Clip of scene succeeded and is ready to download\")\r\n \r\n # Still activating. Wait 1 second and check again.\r\n else:\r\n print(\"...Still waiting for clipping to complete...\")\r\n time.sleep(15)\r\n \r\n # Download clip\r\n response = requests.get(clip_download_url, stream=True)\r\n with open( scene_id + '.zip', \"wb\") as handle:\r\n for data in tqdm(response.iter_content()):\r\n handle.write(data)\r\n \r\n # Unzip file\r\n zipped_item = zipfile.ZipFile(scene_id + '.zip')\r\n zipped_item.extractall(scene_id)\r\n \r\n del zipped_item\r\n # Delete zip file\r\n os.remove(scene_id + '.zip')\r\n \r\n # add scene id to list of downloaded scenes to avoid duplicating downloads\r\n f.close()\r\n f = open(txtfile, \"a\")\r\n f.write(i+'\\n')\r\n f.close()\r\n print('finished downloading scene')\r\n except:\r\n loss.append(i)\r\n print(loss, 'loss')\r\n \r\n\r\n\r\n\r\n# r = requests.get(asset['_links']['_self'], auth=(api_key, ''))\r\n# r.ok # checking to see if the asset link is all good \r\n\r\n# QUOTA_URL = 'https://api.planet.com/auth/v1/experimental/public/my/subscriptions'\r\n\r\n# r = requests.get(QUOTA_URL, auth=(api_key, ''))\r\n# l = r.json()\r\n\r\n\r\n# #2645\r\n\r\n","sub_path":"planet_download_RIP.py","file_name":"planet_download_RIP.py","file_ext":"py","file_size_in_byte":6370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"488787710","text":"# -*- coding: utf-8 -*-\nfrom osv import fields, osv\nfrom tools.translate import _\n\nclass projectScrumSandbox(osv.osv):\n _name = 'project.scrum.sandbox'\n \n _columns = {\n 'role_id': fields.many2one('project.scrum.role', \"As\", required=True),\n 'name' : fields.char('I want', size=128, required=True),\n 'for_then' : fields.char('For', size=128, required=True),\n 'project_id': fields.many2one('project.project', \"Project\", required=True, domain=[('is_scrum', '=', True)]),\n 'developer_id': fields.many2one('res.users', 'Developer'),\n }\n \n _defaults = {\n 'developer_id': lambda self, cr, uid, context: uid,\n }\n","sub_path":"project_scrum/project_scrum_sandbox.py","file_name":"project_scrum_sandbox.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"218370250","text":"#coding:utf-8\n\n#Windowsだと警告が出るが特に問題がないらしいのでこれで握りつぶす\n#参考(http://stackoverflow.com/questions/41658568/chunkize-warning-while-installing-gensim)\nimport warnings\nwarnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')\n\nfrom gensim.models.word2vec import Word2Vec\n\n\nif __name__ == \"__main__\":\n\n\tmodel = Word2Vec.load(\"word2vec.model\")\n\n\tfor factor in model.most_similar(positive=[\"Spain\", \"Athens\"], negative=[\"Madrid\"]):\n\t\tprint(\"%s %f\" % factor)\n","sub_path":"question90-99/question90_89.py","file_name":"question90_89.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"405205067","text":"import altair as alt\nimport pandas as pd\nfrom survey import df, attended, Question, survey\n\ndef sentiment(q):\n sent = Question(survey, q)\n g = sent.summary.reset_index().melt(['index'])\n return alt.Chart(g).mark_bar().encode(\n x = {\n \"field\": \"value\",\n \"stack\": \"normalize\",\n \"type\": \"quantitative\",\n \"axis\": { \"title\": None,\n \"format\": \"%\",\n },\n \"sort\": \"descending\"\n },\n y = {\n \"field\": \"index\",\n \"type\": \"nominal\",\n \"axis\": { \"title\": None,\n \"labelLimit\": 350,\n },\n },\n color = {\n \"field\": 'variable',\n \"type\": \"nominal\",\n \"legend\": { \"title\": None },\n \"scale\": { \"scheme\": \"pinkyellowgreen\"\n },\n \"sort\": \"descending\"\n },\n )\n","sub_path":"2019/diagrams/survey/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"335878094","text":"# Solver for Advent Of Code 2018 Day 09\r\n\r\n# First try takes to long for Part 2 (see ```calculate_highscore_with_list```)\r\n# Second try uses doubly linked list (for Part 2 around 16 seconds)\r\n\r\nimport time\r\n\r\n\r\n# def calculate_highscore_with_list(n_players: int, last_marble: int) -> int:\r\n# \"\"\"\r\n# Very slow solution. Fast solving of Part 1, but to slow for Part 2\r\n# Uses list for the circle.\r\n# \"\"\"\r\n# t_0 = time.time()\r\n# current_marble_pos = 0\r\n# player = 0\r\n# score = [0] * n_players\r\n# circle = [0]\r\n# debug_counter_max = 10000\r\n# debug_counter = 0\r\n# for marbel_to_place in range(1, last_marble+1):\r\n# debug_counter += 1\r\n# if debug_counter == debug_counter_max:\r\n# print(marbel_to_place, time.time() - t_0)\r\n# debug_counter = 0\r\n# player = player + 1 if player < n_players else 1\r\n# if marbel_to_place % 23 == 0:\r\n# score[player-1] += marbel_to_place\r\n# current_marble_pos -= 7\r\n# if current_marble_pos < 0:\r\n# current_marble_pos += len(circle)\r\n# score[player-1] += circle.pop(current_marble_pos)\r\n# else:\r\n# current_marble_pos = current_marble_pos + 2\r\n# if current_marble_pos > len(circle):\r\n# current_marble_pos = 1\r\n# circle.insert(current_marble_pos, marbel_to_place)\r\n# return max(score)\r\n\r\n\r\nclass Node:\r\n \"\"\" For creating a doubly linked list \"\"\"\r\n\r\n def __init__(self, value, prev=None, next=None):\r\n self.value = value\r\n self.prev = prev\r\n self.next = next\r\n\r\n def insert(self, value):\r\n new_node = Node(value, prev=self, next=self.next)\r\n self.next.prev = new_node\r\n self.next = new_node\r\n return new_node\r\n\r\n def remove(self):\r\n next_node = self.next\r\n self.prev.next = self.next\r\n self.next.prev = self.prev\r\n self.prev = None\r\n self.next = None\r\n return next_node\r\n\r\n def forward(self, distance):\r\n node = self\r\n for i in range(distance):\r\n node = node.next\r\n return node\r\n\r\n def backward(self, distance):\r\n node = self\r\n for i in range(distance):\r\n node = node.prev\r\n return node\r\n\r\n def __str__(self):\r\n return str(self.value)\r\n\r\n\r\ndef calculate_highscore(n_players: int, last_marble: int) -> int:\r\n player = 0\r\n score = [0] * n_players\r\n circle = Node(0)\r\n circle.next = circle\r\n circle.prev = circle\r\n for marbel_to_place in range(1, last_marble + 1):\r\n player = player + 1 if player < n_players else 1\r\n if marbel_to_place % 23 == 0:\r\n score[player - 1] += marbel_to_place\r\n circle = circle.backward(7)\r\n score[player - 1] += circle.value\r\n circle = circle.remove()\r\n else:\r\n circle = circle.forward(1)\r\n circle = circle.insert(marbel_to_place)\r\n return max(score)\r\n\r\n\r\nassert calculate_highscore(n_players=9, last_marble=25) == 32\r\nassert calculate_highscore(n_players=10, last_marble=1618) == 8317\r\nassert calculate_highscore(n_players=13, last_marble=7999) == 146373\r\nassert calculate_highscore(n_players=17, last_marble=1104) == 2764\r\nassert calculate_highscore(n_players=21, last_marble=6111) == 54718\r\nassert calculate_highscore(n_players=30, last_marble=5807) == 37305\r\n\r\nprint('Solution Day 09 Part 1: {}'.format(calculate_highscore(n_players=411, last_marble=72059)))\r\n\r\nt_0 = time.time()\r\nprint('Solution Day 09 Part 2: {}'.format(calculate_highscore(n_players=411, last_marble=7205900)))\r\nprint(' took {:.1f} seconds'.format(time.time() - t_0))\r\n","sub_path":"2018/09/solver09.py","file_name":"solver09.py","file_ext":"py","file_size_in_byte":3710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"27317122","text":"import numpy as np\r\nfrom sklearn.model_selection import train_test_split\r\nimport gzip\r\n\r\ndef read_data(filename):\r\n with gzip.open(filename) as input:\r\n s=[1]+[float(i) for i in input.readline().split()]\r\n X,Y=np.array([s[:-1]],dtype=np.float64),np.array([s[-1]],dtype=np.int64)\r\n Y=Y%10\r\n \r\n for line in input:\r\n s=[1]+[float(i) for i in line.split()]\r\n X,Y=np.append(X,[s[:-1]],axis=0),np.append(Y,[s[-1]],axis=0)\r\n Y=Y%10\r\n return (X,Y)\r\n\r\ndef hypothesis(X,theta):\r\n return 1/(1+np.exp(-X.dot(theta)))\r\n\r\ndef gradient_descent(X,Y,alpha,iter,function):\r\n O,m=np.ones(X[0].size),Y.size\r\n \r\n while iter>0:\r\n O-=X.T.dot(function(X,O)-Y)*alpha/m\r\n iter-=1\r\n \r\n return O\r\n\r\nX,Y=read_data('data.gz')\r\nX_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.2,random_state=12)\r\nn=X_train[0].size; theta=np.zeros((n,10))\r\n\r\n\r\nfor i in range(10):\r\n theta[:,i]=gradient_descent(X_train,Y_train==i,0.8,3200,hypothesis)\r\n\r\nprediction=np.argmax(X_test.dot(theta).T,axis=0)\r\n\r\nprint('Accuracy:\\n',np.mean(prediction == Y_test) * 100)\r\n","sub_path":"number_recognition.py","file_name":"number_recognition.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"352055424","text":"import logging\n\nfrom dbnd import ParameterScope, PipelineTask, data, dbnd_run_cmd, output, parameter\nfrom dbnd._core.context.databand_context import new_dbnd_context\nfrom dbnd.tasks.basics import SimplestTask\nfrom dbnd.testing.helpers_pytest import assert_run_task\nfrom dbnd_test_scenarios.test_common.task.factories import TTask, TTaskWithInput\nfrom test_dbnd.scenarios.pipelines.pipe_4tasks import (\n MainPipeline as Scenario4_MainPipeline,\n)\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass TestTaskRun(object):\n def test_ttask(self):\n task = TTask()\n assert_run_task(task)\n\n def test_task_require(self):\n class A(TTask):\n pass\n\n class B(A):\n x = parameter[str]\n tt = data\n\n def _requires(self):\n return A(\n task_name=\"required_by_B\"\n ) # This will end up referring to the same object\n\n task_A = A(task_name=\"A_wired_B\")\n task_B = B(task_name=\"B_task_B\", tt=task_A, x=\"d\")\n task_B.dbnd_run()\n assert task_B._complete()\n assert task_B.tt[\"t_output\"].task._complete()\n assert task_A._complete()\n\n def test_simple_pipeline(self):\n class A(TTask):\n pass\n\n class B(A):\n x = parameter[str]\n tt = data\n\n o_first = output.data\n o_second = output.data\n\n def run(self):\n super(B, self).run()\n self.o_first.as_object.touch()\n self.o_second.as_object.touch()\n\n class CPipeline(PipelineTask):\n x = parameter[str]\n\n a_output = output.data\n b_main = output.data\n b_output = output.data\n\n def band(self):\n self.a_output = A(task_name=\"A_simple\")\n b_main = B(task_name=\"B_simple\", tt=self.a_output, x=self.x)\n\n self.b_main = b_main\n self.b_output = b_main.o_second\n\n c_pipeline = CPipeline(x=\"some_x_values\")\n c_pipeline.dbnd_run()\n assert c_pipeline\n assert c_pipeline.a_output[\"t_output\"].source_task._complete()\n assert c_pipeline.b_main[\"o_second\"].source_task._complete()\n assert c_pipeline.b_output.source_task._complete()\n\n def test_nested_pipeline(self):\n class A(TTask):\n tt = data\n x = parameter[str]\n\n class BPipeline(PipelineTask):\n tt = data(scope=ParameterScope.children)\n x = parameter(scope=ParameterScope.children)[str]\n\n some_a = output\n\n def band(self):\n self.some_a = A(task_name=\"A_%s\" % self.x)\n\n class CPipeline(PipelineTask):\n tt = data(scope=ParameterScope.children)\n\n task_p1 = output\n some_a = output\n\n def band(self):\n self.task_p1 = BPipeline(task_name=\"B_x10\", x=10)\n self.some_a = BPipeline(task_name=\"B_x20\", x=20).some_a\n\n c_pipeline = CPipeline(tt=__file__)\n c_pipeline.dbnd_run()\n assert c_pipeline\n assert c_pipeline.task_p1[\"some_a\"][\"t_output\"].source_task._complete()\n assert c_pipeline.some_a[\"t_output\"].source_task._complete()\n assert isinstance(c_pipeline.some_a[\"t_output\"].source_task, A)\n\n def test_foreign_context_should_not_fail(self):\n with new_dbnd_context():\n t = SimplestTask()\n t.dbnd_run()\n\n TTaskWithInput(t_input=t).dbnd_run()\n\n def test_scenario_4_select_task(self, tmpdir_factory):\n dbnd_run_cmd([Scenario4_MainPipeline.get_task_family(), \"-c run.task=B_F4Task\"])\n","sub_path":"modules/dbnd/test_dbnd/task/test_task_run.py","file_name":"test_task_run.py","file_ext":"py","file_size_in_byte":3641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"350772666","text":"import csv , json\nimport pandas as pd\n# csvFilePath = \"./Courses.csv\"\n# tableJsonFilePath = \"./Courses.json\"\n# graphJsonFilePath = \"./graph.json\"\ncsvFilePath = \"Courses.csv\"\ntableJsonFilePath = \"./Courses.json\"\ngraphJsonFilePath = \"./graph.json\"\n\nTechTable_courses = []\ndef generate_tableJson():\n\twith open (csvFilePath) as csvFile:\n\t\tcsvReader = csv.DictReader(csvFile)\n\t\tfor csvRow in csvReader:\n\t\t\tcourse_code = list(csvRow[\"Course Code\"].split(\"/\"))[0]\n\t\t\tcsvRow[\"Prereq Link\"]=\"http://127.0.0.1:5000/viewDescription/filename?=\"+course_code\n\t\t\tTechTable_courses.append(csvRow)\n\tfor i in range(0,len(TechTable_courses)):\n\t\tTechTable_courses[i]['Course Name']+='#'\n\t\tTechTable_courses[i]['Course Name']+=TechTable_courses[i]['Link']\n\t\tTechTable_courses[i]['Prerequisites']=TechTable_courses[i]['Prerequisites'].replace('\"','')\n\t\tTechTable_courses[i]['Preferable Prerequisites']=TechTable_courses[i]['Preferable Prerequisites'].replace('\"','')\n\t\tTechTable_courses[i]['Antirequisites']=TechTable_courses[i]['Antirequisites'].replace('\"','')\n\twith open(tableJsonFilePath, \"w\") as jsonFile:\n\t\tjsonFile.write('{\"data\": ')\n\t\tjsonFile.write(json.dumps(TechTable_courses, indent = 4))\n\t\tjsonFile.write(\"}\")\n\t\tjsonFile.close()\ndef generate_graphJson():\n\tdata = pd.read_csv(csvFilePath)\n\tdata = data.to_dict()\n\tnodes = pd.DataFrame()\n\tname = []\n\tID = []\n\tcluster = []\n\tprereqs = []\n\tnames = data['Course Name']\n\tcodes = data['Course Code']\n\tids = data['Serial Number']\n\tclusters = data['cluster']\n\tprerequisites = data['Prerequisites']\n\tfor entry in range(0,len(prerequisites)):\n\t\tif(isinstance(prerequisites[entry], float)):\n\t\t\tprerequisites[entry] = 'None'\n\t\tprerequisites[entry] = prerequisites[entry].replace(\"'\",\"\")\n\t\tprerequisites[entry] = prerequisites[entry].replace('\"',\"\")\n\t\tprerequisites[entry] = prerequisites[entry].replace(\" \", \"\")\n\t\tprerequisites[entry] = list(prerequisites[entry].split(\",\"))\n\tfor i in range(0,len(names)):\n\t\tname.append(codes[i]+\":\"+names[i])\n\t\tID.append(ids[i])\n\t\tcluster.append(clusters[i])\n\t\tprereqs.append(prerequisites[i])\n\tnodes = '\"nodes\":['\n\tfor node in range(0,len(names)-1):\n\t\tnodes+='{\"id\":'+str(ID[node])+',\"name\":\"'+name[node]+'\",\"cluster\":'+str(cluster[node])+'},'\n\tnodes+='{\"id\":'+str(ID[node+1])+',\"name\":\"'+name[node+1]+'\",\"cluster\":'+str(cluster[node+1])+'}],'\n\tedges = '\"edges\":['\n\tfor course in range(0,len(names)):\n\t\tfor prereq in range(0, len(prerequisites[course])):\n\t\t\tif(prerequisites[course][prereq]!='None'):\n\t\t\t\tfor code in range(0,len(codes)):\n\t\t\t\t\tif(prerequisites[course][prereq]==codes[code]):\n\t\t\t\t\t\tedges+='{\"source\":'+str(code+1)+',\"target\":'+str(course+1)+'},'\n\tedges = edges[:-1]\n\tedges+=']'\n\tgraphJSON = '{'+nodes+edges+'}'\n\twith open(graphJsonFilePath, \"w\") as jsonFile:\n\t\tjsonFile.write(graphJSON)\n\t\tjsonFile.close()\n# generate_graphJson()\ngenerate_tableJson()","sub_path":"old/upload/jsongenerator.py","file_name":"jsongenerator.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"9460105","text":"import time\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport os\n\nimport keyboard\nimport control\nimport model as md\nimport environment\nimport autoencoder as ae\n\nimport gc\n\ndef train(i_train):\n global model, model_tar, encoder, encoder_tar, decoder, optimizer, gamma\n train_sel, train_ind, train_data = environment.sample()\n #print('sampling done')\n train_screens, train_key1s, train_key2s, train_action1, train_action2, train_rew1, train_rew2, train_terminal = train_data\n train_ima = torch.Tensor(train_screens)\n train_ima_ = decoder(encoder(train_ima))\n \n train_ae_loss = nn.L1Loss(reduction='mean')(train_ima, train_ima_)\n \n train_codes = encoder(train_ima).detach().numpy()\n train_codes_tar = encoder_tar(train_ima).detach().numpy()\n \n train_q_tar1 = 0\n train_q_tar2 = 0\n #print(codes.shape)\n #print(key1s.shape)\n #print(key1s.shape)\n #print(np.concatenate([codes[1:].flatten(), keys1[1:].flatten(), [0]])[np.newaxis, :].shape)\n \n if not train_terminal:\n train_state1b = torch.Tensor(np.concatenate([train_codes[1:].flatten(), train_key1s[1:].flatten(), [0]]))\n train_state2b = torch.Tensor(np.concatenate([train_codes[1:].flatten(), train_key2s[1:].flatten(), [1]]))\n train_argmax1 = torch.argmax(model(train_state1b)).item()\n train_argmax2 = torch.argmax(model(train_state2b)).item()\n train_state1b_tar = torch.Tensor(np.concatenate([train_codes_tar[1:].flatten(), train_key1s[1:].flatten(), [0]]))\n train_state2b_tar = torch.Tensor(np.concatenate([train_codes_tar[1:].flatten(), train_key2s[1:].flatten(), [1]]))\n train_tar_out1 = model_tar(train_state1b_tar).detach().numpy()\n train_tar_out2 = model_tar(train_state2b_tar).detach().numpy()\n train_q_tar1 = train_tar_out1[train_argmax1] * gamma\n train_q_tar2 = train_tar_out2[train_argmax2] * gamma\n #del state1b, state2b, argmax1, argmax2, state1b_tar, state2b_tar, tar_out1, tar_out2\n \n train_q_tar1 += train_rew1\n train_q_tar2 += train_rew2\n train_state1a = torch.Tensor(np.concatenate([train_codes[:-1].flatten(), train_key1s[:-1].flatten(), [0]]))\n train_state2a = torch.Tensor(np.concatenate([train_codes[:-1].flatten(), train_key2s[:-1].flatten(), [1]]))\n train_q_now1 = model(torch.Tensor(train_state1a))[train_action1]\n train_q_now2 = model(torch.Tensor(train_state2a))[train_action2]\n train_td_loss = ((train_q_tar1 - train_q_now1) ** 2 + (train_q_tar2 - train_q_now2) ** 2)\n environment.update_tdE(train_sel, train_ind, train_td_loss.item())\n \n train_loss = train_ae_loss + train_td_loss\n #print(i_train, train_ae_loss.item(), train_td_loss.item())\n optimizer.zero_grad()\n train_loss.backward()\n optimizer.step()\n #del q_tar1, q_tar2, state1a, state2a, q_now1, q_now2, td_loss, loss, ae_loss, ima, ima_, codes, codes_tar, screens, key1s, key2s, action1, action2, rew1, rew2, terminal, data, sel, ind\n \n\ngamma = 0.80\n\nmodel = md.Model()\nmodel_tar = md.Model()\nencoder = ae.Encoder()\nencoder_tar = ae.Encoder()\ndecoder = ae.Decoder()\noptimizer = optim.Adam(model.parameters(), lr = 0.01)\ntrained_episode = 0\n\nif os.path.isfile('checkpoint.pt'):\n checkpoint = torch.load('checkpoint.pt')\n model.load_state_dict(checkpoint['model'])\n encoder.load_state_dict(checkpoint['encoder'])\n decoder.load_state_dict(checkpoint['decoder'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n trained_episode = checkpoint['episode']\n\nenvironment.init()\n\nfor episode in range(trained_episode, trained_episode+1000):\n print('Episode {} start'.format(episode))\n step = 0\n \n model_tar.load_state_dict(model.state_dict())\n encoder_tar.load_state_dict(encoder.state_dict())\n \n environment.reset()\n \n last = time.time()\n \n codes = np.zeros([8, 20], dtype=np.float)\n keys1 = np.zeros([8, 6], dtype=np.float)\n keys2 = np.zeros([8, 6], dtype=np.float)\n while True:\n now = time.time()\n if now - last > 1/3:\n #print('FPS: {}'.format(1/(now - last)))\n last = now\n \n scr, winner, rew1, rew2 = environment.observe()\n \n scr = scr / 256\n code = encoder(torch.Tensor(scr[np.newaxis, :])).detach().numpy()\n state1 = np.concatenate([codes.flatten(), code.flatten(), keys1.flatten(), [0]])\n state2 = np.concatenate([codes.flatten(), code.flatten(), keys2.flatten(), [1]])\n q1 = model(torch.Tensor(state1))\n q2 = model(torch.Tensor(state2))\n #print('q1:', q1.detach().numpy())\n #print('q2:', q2.detach().numpy())\n if step != 0:\n q_tar1 = 0\n q_tar2 = 0\n if winner == 0:\n q_tar1 = model_tar(torch.Tensor(state1[np.newaxis, :]))[0, torch.argmax(q1)].item() * gamma\n q_tar2 = model_tar(torch.Tensor(state2[np.newaxis, :]))[0, torch.argmax(q2)].item() * gamma\n q_tar1 += rew1\n q_tar2 += rew2\n environment.save_tdE((q_tar1 - q_old1) ** 2, (q_tar2 - q_old2) ** 2)\n if winner != 0:\n keyboard.tap('Escape')\n environment.finish(episode, winner)\n keyboard.tap('Escape')\n environment.quit()\n break\n if np.random.rand() < 0.75:\n act1 = np.random.randint(36)\n else:\n act1 = torch.argmax(q1).item()\n if np.random.rand() < 0.75:\n act2 = np.random.randint(36)\n else:\n act2 = torch.argmax(q2).item()\n #print(act1, act2)\n environment.act(act1, act2)\n q_old1 = q1[act1]\n q_old2 = q2[act2]\n \n codes[:-1] = codes[1:]\n keys1[:-1] = keys1[1:]\n keys2[:-1] = keys2[1:]\n codes[-1] = code\n keys1[-1] = control.act_to_key(act1)\n keys2[-1] = control.act_to_key(act2)\n \n step += 1\n \n if step % 300 == 0: #100 sec 300\n tmp = time.time()\n keyboard.tap('Escape')\n \n environment.checkpoint(episode)\n \n print(\"before {}\".format(len(gc.get_objects())))\n \n print('Training')\n for i_train in range(30):\n train(i_train)\n \n print(\"after {}\".format(len(gc.get_objects())))\n \n if step == 300:\n stt = {}\n for obj in gc.get_objects():\n try:\n if type(obj).__name__ == 'builtin_function_or_method':\n if str(obj) in stt:\n stt[str(obj)] -= 1\n else:\n stt[str(obj)] = -1\n except:\n pass\n #print(stt)\n \n dd = stt.copy()\n for obj in gc.get_objects():\n try:\n if type(obj).__name__ == 'builtin_function_or_method':\n if str(obj) in dd:\n dd[str(obj)] += 1\n else:\n dd[str(obj)] = 1\n except:\n pass\n for key, val in dd.items():\n if val != 0:\n print(key, val)\n \n torch.save({'model': model.state_dict(), 'encoder': encoder.state_dict(), 'decoder': decoder.state_dict(),\n 'optimizer': optimizer.state_dict(), 'episode': episode}, 'checkpoint.pt')\n \n keyboard.tap('Escape')\n last += time.time() - tmp\n if step == 1800: #10 min\n environment.quit()\n break\n \n","sub_path":"selfplay.py","file_name":"selfplay.py","file_ext":"py","file_size_in_byte":8120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"458446247","text":"# -*- coding: utf-8 -*-\n\nimport smbus\nimport math\nimport socket\nfrom time import sleep\nfrom pythonosc import udp_client\nfrom pythonosc.osc_message_builder import OscMessageBuilder\n\nIP = '192.168.0.255'\nPORT = 4559\n\nDEV_ADDR = 0x68\n\nPWR_MGMT_1 = 0x6B\nSMPLRT_DIV = 0x19\nCONFIG = 0x1A\nGYRO_CONFIG = 0x1B\nINT_ENABLE = 0x38\nACCEL_XOUT = 0x3B\nACCEL_YOUT = 0x3D\nACCEL_ZOUT = 0x3F\nTEMP_OUT = 0x41\nGYRO_XOUT = 0x43\nGYRO_YOUT = 0x45\nGYRO_ZOUT = 0x47\n\nPWR_MGMT_1 = 0x6b\nPWR_MGMT_2 = 0x6c\n\nbus = smbus.SMBus(1)\nbus.write_byte_data(DEV_ADDR, PWR_MGMT_1, 0)\n\n\ndef MPU_Init():\n\t#write to sample rate register\n\tbus.write_byte_data(DEV_ADDR, SMPLRT_DIV, 7)\n\t\n\t#Write to power management register\n\tbus.write_byte_data(DEV_ADDR, PWR_MGMT_1, 1)\n\t\n\t#Write to Configuration register\n\tbus.write_byte_data(DEV_ADDR, CONFIG, 0)\n\t\n\t#Write to Gyro configuration register\n\tbus.write_byte_data(DEV_ADDR, GYRO_CONFIG, 24)\n\t\n\t#Write to interrupt enable register\n\tbus.write_byte_data(DEV_ADDR, INT_ENABLE, 1)\n\ndef read_word(adr):\n high = bus.read_byte_data(DEV_ADDR, adr)\n low = bus.read_byte_data(DEV_ADDR, adr+1)\n val = ((high << 8) | low)\n #print (val)\n return val\n\n# Sensor data read\ndef read_word_sensor(adr):\n val = read_word(adr)\n if (val > 32768): # minus\n val = val - 65536 # plus\n #print (val)\n return val\n\n\ndef get_temp():\n temp = read_word_sensor(TEMP_OUT)\n x = temp / 340 + 36.53 # data sheet(register map)記載の計算式.\n return x\n\n\ndef getGyro():\n x = read_word_sensor(GYRO_XOUT)/ 131.0\n y = read_word_sensor(GYRO_YOUT)/ 131.0\n z = read_word_sensor(GYRO_ZOUT)/ 131.0\n return [x, y, z]\n\n\ndef getAccel():\n x = read_word_sensor(ACCEL_XOUT)/ 16384.0\n y = read_word_sensor(ACCEL_YOUT)/ 16384.0\n z = read_word_sensor(ACCEL_ZOUT)/ 16384.0\n #print ({}{}{})\n return [x, y, z]\n\ndef getDeg(ax,ay,az):\n theta = math.atan(ax / math.sqrt(ay * ay + az * az))\n psi = math.atan(ay / math.sqrt(ax * ax + az * az))\n phi = math.atan(math.sqrt(ax * ax + ay * ay) / az)\n\n deg_theta = math.degrees(theta)\n deg_psi = math.degrees(psi)\n deg_phi = math.degrees(phi)\n\n return [deg_theta,deg_psi,deg_phi]\n\n#MPU_Init()\n\ncnt = 0\nBefore_a = 1.0\ninterval = 10\n\nclient = udp_client.UDPClient(IP, PORT)\nclient._sock.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)\nprint('start!')\nwhile 1:\n ax, ay, az = getAccel()\n #print ('x={0:4.3f}, y={1:4.3f}, z={2:4.3f},' .format(ax, ay, az))\n \n a = math.sqrt((ay * ay) + (az * az))\n j = a - Before_a\n if(j >= 0.5 and interval >= 10):\n print(cnt)\n interval = 0\n msg = OscMessageBuilder(address='/command')\n msg.add_arg(cnt)\n m = msg.build()\n client.send(m)\n cnt+=1\n Before_a = a\n interval += 1\n sleep(0.01)\n","sub_path":"command/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":2799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"404830930","text":"### Author: T.Brown 20/11/13\n\n# Calculates the RC for a given galaxy using the Polyex model (Catinella et al. 2006)\n\nimport numpy as np\n\n# define analytic function for RC fitting (Polyex Model - Giavanelli & Haynes 02)\ndef velocity(rpos, MI):\n \n# if statements selecting which parameters to use dependant on I-Band Mag\n\n # set variables for each magnitude bin: velocity amplitude, scale inner curve, scale outer curve.\n if MI >= -24.0 and MI < -23.6:\n V0 = 275\n rpe = 0.126\n alpha = 0.008\n\n if MI >= -23.6 and MI < -23.2:\n V0 = 255\n rpe = 0.132\n alpha = 0.002\n\n if MI >= -23.2 and MI < -22.8:\n V0 = 225\n rpe = 0.149\n alpha = 0.003\n\n if MI >= -22.8 and MI < -22.4:\n V0 = 200\n rpe = 0.164\n alpha = 0.002\n\n if MI >= -22.4 and MI < -22.0:\n V0 = 170\n rpe = 0.178\n alpha = 0.011\n\n if MI >= -22.0 and MI < -21.6:\n V0 = 148\n rpe = 0.201\n alpha = 0.022\n\n if MI >= -21.6 and MI < -21.2:\n V0 = 141\n rpe = 0.244\n alpha = 0.010\n\n if MI >= -21.2 and MI < -20.8:\n V0 = 122\n rpe = 0.261\n alpha = 0.020\n\n if MI >= -20.8 and MI < -20.0:\n V0 = 103\n rpe = 0.260\n alpha = 0.029\n\n if MI >= -20.0 and MI < -18.0:\n V0 = 85\n rpe = 0.301\n alpha = 0.019\n\n#else:\n# print 'Magnitude outside allowed range'\n \n return V0 * (1 - np.exp(-rpos / rpe)) * (1 + (alpha * np.abs(rpos) / rpe))\n\n\ndef rebin(x, bin_factor):\n\n indx = range(x.size)\n bounds = indx[0::bin_factor]\n\n y = zeros(size(bounds) -1)\n\n for i in range(size(y)):\n\n y[i] = x[bounds[i]:bounds[i+1]].mean()\n\n return y\n\n\n","sub_path":"velocity.py","file_name":"velocity.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"653346624","text":"\"\"\"More Control Flow Tools\"\"\"\n\ndef test_if_statements():\n \"\"\"测��� if 语句\"\"\"\n val_x = int(input(\"Please enter an integer: \"))\n if val_x < 0:\n val_x = 0\n print(\"Negative changed to zero\")\n elif val_x == 0:\n print(\"Zero\")\n elif val_x == 1:\n print(\"Single\")\n else:\n print(\"More\")\n\n# test_if_statements()\n\ndef test_for_statements():\n \"\"\"测试 for 语句\"\"\"\n words = [\"cat\", \"window\", \"defenestrate\"]\n for var_w in words:\n print(var_w, len(var_w))\n\n# test_for_statements()\n\ndef test_range_function():\n \"\"\"测试 range 函数\"\"\"\n for var_i in range(5):\n print(var_i)\n\n# test_range_function()\n\ndef test_loop_statements():\n \"\"\"测试循环语句\"\"\"\n for var_n in range(2, 10):\n for var_x in range(2, var_n):\n if var_n % var_x == 0:\n print(var_n, \"equals\", var_x, \"*\", var_n//var_x)\n else:\n break\n else:\n # loop fell through without finding a factor\n print(var_n, \"is a prime number\")\n\n# test_loop_statements()\n\n# def test_function_annotations(ham: str, eggs: str = \"eggs\") -> str:\n# \"\"\"测试函数\"\"\"\n# print(\"Annotations:\", test_function_annotations.__annotations__)\n# print(\"Arguments:\", ham, eggs)\n# return ham + \" and \" + eggs\n\n# test_function_annotations(\"spam\")\n\ndef test_function_annotations(ham, eggs):\n \"\"\"测试函数\"\"\"\n print(\"Annotations:\", test_function_annotations.__annotations__)\n print(\"Arguments:\", ham, eggs)\n return ham + \" and \" + eggs\n\ntest_function_annotations(\"spam\", \"eggs\")\n","sub_path":"the-python-tutorial/4.more_control_flow_tools.py","file_name":"4.more_control_flow_tools.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"564701844","text":"\"\"\"\nTask\n\nIn this simple Kata your task is to create a function that turns a string into a Mexican Wave. You will be passed a string and you must return that string in an array where an uppercase letter is a person standing up. \n\nRules\n\n 1. The input string will always be lower case but maybe empty.\n\n 2. If the character in the string is whitespace then pass over it as if it was an empty seat\n\nExample\n\nwave(\"hello\") => [\"Hello\", \"hEllo\", \"heLlo\", \"helLo\", \"hellO\"]\n\"\"\"\n\n\ndef wave(people):\n ans = []\n if len(people) == 0:\n return ans\n for i in range(len(people)-1):\n if people[i] != \" \":\n word = people[:i] + people[i].upper() + people[i+1:]\n ans.append(word)\n if people[-1] != \" \":\n word = people[:-1] + people[-1].upper()\n ans.append(word)\n return ans\n","sub_path":"6kyu_Mexican_Wave.py","file_name":"6kyu_Mexican_Wave.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"577508015","text":"import base64\nimport datetime\nimport json\nimport urllib.parse\nfrom typing import Mapping, Dict, List\n\nfrom grpclib.client import Channel\nfrom okapi.wrapper import LDProofs, DIDKey\nfrom okapi.okapi_utils import dictionary_to_struct, struct_to_dictionary\nfrom okapi.proto.okapi.keys.v1 import JsonWebKey, GenerateKeyRequest, KeyType\nfrom okapi.proto.okapi.proofs.v1 import CreateProofRequest, LdSuite\n\nfrom trinsic.proto.services.common.v1 import JsonPayload, RequestOptions, JsonFormat\nfrom trinsic.proto.services.provider.v1 import ProviderStub, InviteRequestDidCommInvitation, InviteResponse, \\\n ParticipantType, InvitationStatusResponse\nfrom trinsic.proto.services.trustregistry.v1 import TrustRegistryStub, GovernanceFramework, RegistrationStatus\nfrom trinsic.proto.services.universalwallet.v1 import WalletProfile, WalletStub, SearchResponse\nfrom trinsic.proto.services.verifiablecredentials.v1 import CredentialStub\n\n\ndef create_channel_if_needed(channel: Channel = None, service_address: str = '') -> Channel:\n if not channel:\n service_url = urllib.parse.urlsplit(service_address)\n is_https = service_url.scheme == \"https\"\n channel = Channel(host=f\"{service_url.hostname}\", port=service_url.port, ssl=is_https)\n return channel\n\n\nclass ServiceBase:\n def __init__(self):\n self.cap_invocation: str = \"\"\n\n @property\n def metadata(self) -> Mapping[str, str]:\n if not self.cap_invocation:\n raise Exception(\"Profile not set\")\n return {\"capability-invocation\": self.cap_invocation}\n\n def set_profile(self, profile: WalletProfile):\n capability_doc = {\"@context\": \"https://w3id.org/security/v2\",\n \"invocationTarget\": profile.wallet_id,\n \"proof\": {\n \"proofPurpose\": \"capabilityInvocation\",\n \"created\": datetime.datetime.now().isoformat(),\n \"capability\": profile.capability\n }}\n\n proof_response = LDProofs.create(CreateProofRequest(key=JsonWebKey().parse(profile.invoker_jwk),\n document=dictionary_to_struct(capability_doc),\n suite=LdSuite.LD_SUITE_JCSED25519SIGNATURE2020))\n\n proof_json = json.dumps(struct_to_dictionary(proof_response.signed_document), indent=2)\n self.cap_invocation = base64.standard_b64encode(proof_json.encode(\"utf-8\")).decode(\"utf-8\")\n\n\nclass WalletService(ServiceBase):\n def __init__(self, service_address: str = \"http://localhost:5000\", channel: Channel = None):\n super().__init__()\n self.channel = create_channel_if_needed(channel, service_address)\n self.client = WalletStub(self.channel)\n self.credential_client = CredentialStub(self.channel)\n\n def __del__(self):\n if self.channel:\n self.channel.close()\n\n async def register_or_connect(self, email: str):\n await self.client.connect_external_identity(email=email)\n\n async def create_wallet(self, security_code: str = None) -> WalletProfile:\n my_key = DIDKey.generate(GenerateKeyRequest(key_type=KeyType.KEY_TYPE_ED25519))\n my_did_document = struct_to_dictionary(my_key.did_document)\n\n create_wallet_response = await self.client.create_wallet(controller=str(my_did_document['id']),\n security_code=security_code or \"\")\n\n return WalletProfile(wallet_id=create_wallet_response.wallet_id,\n capability=create_wallet_response.capability,\n did_document=JsonPayload(json_string=json.dumps(my_did_document)),\n invoker=create_wallet_response.invoker,\n invoker_jwk=bytes(my_key.key[0]))\n\n async def issue_credential(self, document: dict) -> dict:\n self.credential_client.metadata = self.metadata\n response = await self.credential_client.issue(document=JsonPayload(json_string=json.dumps(document)))\n return json.loads(response.document.json_string)\n\n async def search(self, query: str = \"SELECT * from c\") -> SearchResponse:\n self.client.metadata = self.metadata\n return await self.client.search(query=query)\n\n async def insert_item(self, item: dict) -> str:\n self.client.metadata = self.metadata\n return (await self.client.insert_item(item=JsonPayload(json_string=json.dumps(item)))).item_id\n\n async def send(self, document: dict, email: str):\n self.client.metadata = self.metadata\n await self.credential_client.send(email=email, document=JsonPayload(json_string=json.dumps(document)))\n\n async def create_proof(self, document_id: str, reveal_document: dict) -> dict:\n self.credential_client.metadata = self.metadata\n return json.loads((await self.credential_client.create_proof(\n document_id=document_id, reveal_document=JsonPayload(\n json_string=json.dumps(reveal_document)))).proof_document.json_string)\n\n async def verify_proof(self, proof_document: dict) -> bool:\n self.credential_client.metadata = self.metadata\n return (await self.credential_client.verify_proof(\n proof_document=JsonPayload(json_string=json.dumps(proof_document)))).valid\n\n\nclass ProviderService(ServiceBase):\n def __init__(self, service_address: str = \"http://localhost:5000\", channel: Channel = None):\n super().__init__()\n self.channel = create_channel_if_needed(channel, service_address)\n self.provider_client = ProviderStub(self.channel)\n\n def __del__(self):\n if self.channel:\n self.channel.close()\n\n async def invite_participant(self,\n participant: ParticipantType = None,\n description: str = None,\n email: str = None,\n phone: str = None,\n didcomm_invitation: InviteRequestDidCommInvitation = None) -> InviteResponse:\n if not email and not phone:\n raise Exception(\"Contact method must be set\")\n\n return await self.provider_client.invite(participant=participant,\n description=description,\n phone=phone,\n email=email,\n didcomm_invitation=didcomm_invitation)\n\n async def invitation_status(self, invitation_id: str = '') -> InvitationStatusResponse:\n if not invitation_id or not invitation_id.strip():\n raise Exception(\"Onboarding reference ID must be set.\")\n\n return await self.provider_client.invitation_status(invitation_id=invitation_id)\n\n\nclass TrustRegistryService(ServiceBase):\n def __init__(self, service_address: str = \"http://localhost:5000\", channel: Channel = None):\n super().__init__()\n self.channel = create_channel_if_needed(channel, service_address)\n self.provider_client = TrustRegistryStub(self.channel)\n\n def __del__(self):\n if self.channel:\n self.channel.close()\n\n async def register_governance_framework(self, governance_framework: str, description: str):\n governance_url = urllib.parse.urlsplit(governance_framework, allow_fragments=False)\n # Verify complete url\n if governance_url.scheme and governance_url.netloc and governance_url.path:\n self.provider_client.metadata = self.metadata\n response = await self.provider_client.add_framework(governance_framework=GovernanceFramework(\n governance_framework_uri=governance_framework,\n description=description\n ))\n else:\n raise ValueError(f\"Invalid URI string={governance_framework}\")\n\n async def register_issuer(self, issuer_did: str, credential_type: str, governance_framework: str,\n valid_from: datetime.datetime, valid_until: datetime.datetime):\n # TODO - Handle nones for valid_from, valid_until\n self.provider_client.metadata = self.metadata\n await self.provider_client.register_issuer(did_uri=issuer_did,\n credential_type_uri=credential_type,\n governance_framework_uri=governance_framework,\n valid_from_utc=int(valid_from.timestamp()),\n valid_until_utc=int(valid_until.timestamp()))\n\n async def unregister_issuer(self, issuer_did: str, credential_type: str, governance_framework: str,\n valid_from: datetime.datetime, valid_until: datetime.datetime):\n raise NotImplementedError\n\n async def register_verifier(self, verifier_did: str, presentation_type: str, governance_framework: str,\n valid_from: datetime.datetime, valid_until: datetime.datetime):\n self.provider_client.metadata = self.metadata\n await self.provider_client.register_verifier(did_uri=verifier_did,\n presentation_type_uri=presentation_type,\n governance_framework_uri=governance_framework,\n valid_from_utc=int(valid_from.timestamp()),\n valid_until_utc=int(valid_until.timestamp()))\n\n async def unregister_verifier(self, verifier_did: str, presentation_type: str, governance_framework: str,\n valid_from: datetime.datetime, valid_until: datetime.datetime):\n raise NotImplementedError\n\n async def check_issuer_status(self, issuer_did: str, credential_type: str, governance_framework: str) -> RegistrationStatus:\n self.provider_client.metadata = self.metadata\n return (await self.provider_client.check_issuer_status(governance_framework_uri= governance_framework,\n did_uri=issuer_did,\n credential_type_uri=credential_type)).status\n\n async def check_verifier_status(self, issuer_did: str, presentation_type: str,\n governance_framework: str) -> RegistrationStatus:\n self.provider_client.metadata = self.metadata\n return (await self.provider_client.check_verifier_status(governance_framework_uri=governance_framework,\n did_uri=issuer_did,\n presentation_type_uri=presentation_type)).status\n\n async def search_registry(self, query:str=\"SELECT * FROM c\") -> List[Dict]:\n self.provider_client.metadata = self.metadata\n response = await self.provider_client.search_registry(query=query, options=RequestOptions(response_json_format=JsonFormat.Protobuf))\n\n return [item.json_struct.to_dict() for item in response.items]","sub_path":"python/trinsic/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":11307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"426530497","text":"import requests\nimport math\nimport time\nimport json\nfrom bs4 import BeautifulSoup\n\n# ----- Crawler Information ----- #\n# [東森房屋 - 租屋] http://www.etwarm.com.tw/rent/object_list\n\n# [流程]\n# 取得每個房屋物件的連結\n # 迭代進入每個連結,取得房屋物件的內容\n# ------------------------------- #\n\n\n# Get total pages\ndef getTotalPages(href):\n res = requests.get(href)\n soup = BeautifulSoup(res.text, \"lxml\")\n totalPieces = int(soup.select('div[class=\"object_mode\"]')[0].select('span')[0].text)\n res.close()\n # 10 house objects in each page\n totalPages = math.ceil(totalPieces / 10)\n return totalPieces, totalPages # return tuple\n\n\n# Get object information\ndef rent_info(href):\n try:\n time.sleep(3)\n res = requests.get(href)\n soup = BeautifulSoup(res.text, \"lxml\")\n\n data_basic = soup.select('ul[class=\"data_basic\"] > li')\n data_len = len(data_basic)\n\n print(\"租金 : \" + \"\".join(data_basic[0].text.split()))\n\n for data in range(1, data_len - 1):\n print(data_basic[data].text.split(\":\")[0] + \":\" +\n data_basic[data].text.split(\":\")[1])\n\n except IndexError as e:\n print(e, href)\n\n finally:\n pass\n\n\narea_list = [\"台北市\", \"新北市\"]\nkeyword_list = [\"套房\", \"雅房\"]\n\ntry:\n for area in area_list:\n for keyword in keyword_list:\n index = \"http://www.etwarm.com.tw/rent/object_list?area={x}&keyword={y}&page=1\"\\\n .format(x=area, y=keyword)\n\n print(\"--\" * 20)\n print(str(area) + str(keyword))\n totalPieces, totalPages = getTotalPages(index)\n print(\"Total Pages: \" + str(totalPages))\n print(\"--\" * 20 + \"\\n\")\n\n try:\n for page in range(1, int(totalPages) + 1):\n indexf = index[:-1] + \"{}\"\n href = indexf.format(page)\n res = requests.get(href)\n soup = BeautifulSoup(res.text, \"lxml\")\n\n # Dynamic get objects in each page\n obj_info = soup.select('div[class=\"obj_info\"]')\n totalObj = len(obj_info)\n\n count = 0\n\n for objName in range(0, totalObj):\n title = obj_info[objName].select('a')[0].text.split()\n title = str(title).lstrip('[\\'').rstrip('\\']')\n href = obj_info[objName].select('a')[0]['href']\n\n count += 1\n # Check Crawler\n print(\"Scraping: \" + str(count) + \" (\" + str(page) +\n \" / \" + str(totalPages) + \" Pages)\")\n print(title)\n print(href)\n\n rent_info(href)\n print()\n\n time.sleep(5)\n finally:\n pass\nfinally:\n pass\n\n\n# Write JSON\ndef saveJson(data, fileName):\n with open(fileName, \"w\", encoding=\"utf8\") as f:\n json.dump(data, f, ensure_ascii=False)\n\n# saveJson(job_lists_dict, \"Job_104_\" + str(jobcat) + \".json\")\n\n# Check Crawler\nprint(str(totalPieces) + \" Objects, \" + str(totalPages) + \" Pages Done.\")\n","sub_path":"test_code/etwarm.py","file_name":"etwarm.py","file_ext":"py","file_size_in_byte":3275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"500540007","text":"import re\n\n#\n#This program is used to calculate the time needed to save for a building/upgrade in Cookie Clicker.\n#\n\ndef promptUser():\n userInput = input (\"> \")\n processInput(userInput)\n print (\"\")\n promptUser()\n\ndef processInput(inputString):\n\n if ((inputString == \"help\") | (inputString == \"info\")):\n print (\"Currently supported values: \\n\")\n print (\"\\tk - Thousands\")\n print (\"\\tm - Millions\")\n print (\"\\tb - Billions\")\n print (\"\\tt - Trillions\")\n print (\"\\tqa - Quadrillions\")\n print (\"\\tqi - Quintillions\")\n print (\"\\tsx - Sextillions\")\n print (\"\\tsp - Septillions\")\n print (\"\\toc - Octillions\")\n print (\"\\tno - Nonillions\")\n print (\"\\tdc - Decillions\")\n elif (re.search(\"/\", inputString)):\n numeratorDenominatorList = re.split(\"/\", inputString)\n numerator = numeratorDenominatorList[0]\n denominator = numeratorDenominatorList[1]\n\n totalTime_Sec = castToFloat(numerator) / castToFloat(denominator)\n totalTime_Min = 0\n totalTime_Hours = 0\n totalTime_Days = 0\n totalTime_Years = 0\n \n #60sec per min\n #60min per hour\n #24 hour per day\n #86400sec per day\n #31536000 per year. Roughly, and not accounting for leap years.\n\n while (totalTime_Sec > 31536000):\n totalTime_Years += 1\n totalTime_Sec -= 31536000\n\n while (totalTime_Sec > 86400):\n totalTime_Days += 1\n totalTime_Sec -= 86400\n\n while (totalTime_Sec > 3600):\n totalTime_Hours += 1\n totalTime_Sec -= 3600\n\n while (totalTime_Sec > 60):\n totalTime_Min += 1\n totalTime_Sec -= 60\n\n print (\"\\t\" + inputString + \": \" + str(round(totalTime_Years, 2)) + \"yr, \" + str(round(totalTime_Days, 2)) + \"day, \" + str(round(totalTime_Hours, 2)) + \"hr, \" +\n str(round(totalTime_Min, 2)) + \"min, \" + str(round(totalTime_Sec, 2)) + \"sec\")\n\n else:\n print (\"Invalid input.\")\n\ndef castToFloat(inputString):\n #this method parses the string for k = thousand, m = million, etc.\n\n #thousands case\n if (re.search(\"k\", inputString)):\n return (float(re.sub(\"k\", \"\", inputString)) * 1000)\n #millions case\n elif (re.search(\"m\", inputString)):\n return (float(re.sub(\"m\", \"\", inputString)) * 1000000)\n #billions case\n elif (re.search(\"b\", inputString)):\n return (float(re.sub(\"b\", \"\", inputString)) * 1000000000)\n #trillions case\n elif (re.search(\"t\", inputString)):\n return (float(re.sub(\"t\", \"\", inputString)) * 1000000000000)\n #quadrillions case\n elif (re.search(\"qa\", inputString)):\n return (float(re.sub(\"qa\", \"\", inputString)) * 1000000000000000)\n #quintillions case\n elif (re.search(\"qi\", inputString)):\n return (float(re.sub(\"qi\", \"\", inputString)) * 1000000000000000000)\n #sextillions case\n elif (re.search(\"sx\", inputString)):\n return (float(re.sub(\"sx\", \"\", inputString)) * 1000000000000000000000)\n #septillions case\n elif (re.search(\"sp\", inputString)):\n return (float(re.sub(\"sp\", \"\", inputString)) * 1000000000000000000000000)\n #octillions case\n elif (re.search(\"oc\", inputString)):\n return (float(re.sub(\"oc\", \"\", inputString)) * 1000000000000000000000000000)\n #nonillions case\n elif (re.search(\"no\", inputString)):\n return (float(re.sub(\"no\", \"\", inputString)) * 1000000000000000000000000000000)\n #decillions case\n elif (re.search(\"dc\", inputString)):\n return (float(re.sub(\"dc\", \"\", inputString)) * 1000000000000000000000000000000000)\n\ndef displayHeader():\n print(\"=================================\")\n print(\"=== COOKIE CLICKER CALCULATOR ===\")\n print(\"=================================\")\n print(\"\\nEnter a division operation. Ex: 5m/2.5k, 12qa/8b...\\nOr type \\\"help\\\" to view the values list\")\n\n###\n\ndisplayHeader()\n\npromptUser()\n\n\n\n","sub_path":"CCCalculator.py","file_name":"CCCalculator.py","file_ext":"py","file_size_in_byte":3978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"211888141","text":"try:\n from egovScDoc.spiders.docSpider.base_spider import *\nexcept ImportError:\n from egovResearch.egovScDoc.spiders.docSpider.base_spider import *\n\n\nclass GuangzhouSpider(BaseSpider):\n __city_abbreviation__ = \"guangzhou\"\n\n # ---/---更新页码信息\n def _update_page_count(self):\n \"\"\"\n 更新页码信息\n :return:\n \"\"\"\n browser = self._get_browser()\n for config in self.config_list:\n base_url = \"http://www.gz.gov.cn\"\n\n if config.class_id == \"s2812\" or config.class_id == \"s2811\":\n url_page_index = 2\n else:\n url_page_index = 1\n request_url = \"{}/gzgov/{}/gk_fggw_list{}.shtml\".format(\n base_url, config.class_id, url_page_index)\n browser.get(request_url)\n soup = BeautifulSoup(browser.page_source, \"lxml\")\n span = soup.find(\"span\",class_=\"pagination_index_last\")\n text = \"\".join(span.text.replace(\" \",\"\").split(\" \"))\n pages = re.findall(\"共(\\d+)页\",text)\n page_count = int(pages[0]) + 1\n print(\" --page_num--:\", page_count)\n config.loop_stop = page_count\n config.update()\n browser.close()\n\n def resolve_detail_page(self, item, html):\n soup = BeautifulSoup(html, 'lxml')\n origin_content = soup.find(\"div\", id=\"zoomcon\")\n try:\n time_str = soup.find(\"span\", class_=\"time\").text\n except:\n return\n item.release_time = time_str[:11]\n org_str = soup.find(\"span\", class_=\"ly\").text\n item.organization = org_str.replace(\"来源:\", \"\")\n item.print()\n item.update_content(origin_content)\n item.update()\n pass\n\n def save_all_files(self):\n base_url = \"http://www.gz.gov.cn\"\n config_list = self.config_list\n for config in config_list:\n\n if config.class_id == \"s2812\" or config.class_id==\"s2811\":\n url_page_index = 2\n else:\n url_page_index = 1\n for i in range(config.loop_start, config.loop_stop):\n page_dir = \"{}{}\\{}\".format(self.base_dir, config.class_id, i + config.page_start)\n if i == 1:\n request_url = \"{}/gzgov/{}/gk_fggw_list{}.shtml\".format(\n base_url, config.class_id, url_page_index)\n else:\n request_url = \"{}/gzgov/{}/gk_fggw_list{}_{}.shtml\".format(\n base_url, config.class_id, url_page_index, i)\n res = requests.get(request_url, headers=requests_header)\n res.encoding = self.html_encoding\n soup = BeautifulSoup(res.text, \"lxml\")\n if url_page_index == 1:\n ul = soup.find(\"ul\", class_=\"list\")\n lis = ul.find_all(\"li\")\n else:\n div = soup.find(\"div\",class_=\"news_list_fggw\")\n lis = div.find_all(\"li\")\n\n time.sleep(3)\n if not os.path.exists(page_dir):\n os.makedirs(page_dir)\n for li in lis:\n item = EGOVSCPolicyPaper()\n a = li.find(\"a\")\n\n url = \"{}/{}\".format(base_url, a.get(\"href\").strip().replace(\"../../\", \"\"))\n title = a.get(\"title\").strip()\n\n item.title = title\n item.url = url\n item.origin_page_index = i\n item.remarks = config.remarks\n item.save(self)\n\n sub_res = requests.get(url, headers=requests_header)\n sub_res.encoding = self.html_encoding\n with open(\"{}\\{}.html\".format(page_dir, item.id), \"w\",\n encoding=self.html_encoding) as f:\n f.write(sub_res.text)\n self.resolve_detail_page(item, sub_res.text)\n time.sleep(3)\n\nif __name__ == '__main__':\n with app.app_context():\n GuangzhouSpider(True).update()\n","sub_path":"egovResearch/egovScDoc/spiders/docSpider/guangdong_spiders/guangzhou_spider.py","file_name":"guangzhou_spider.py","file_ext":"py","file_size_in_byte":4132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"556188441","text":"import os\nimport sys\nimport pdb\nimport code\nimport xml.etree.ElementTree as ET\nimport numpy as np\nimport math\nfrom PIL import Image\n\ndef cross(a, b):\n return np.cross(a, b)\n\ndef dot(a, b):\n return np.dot(a, b)\n\ndef normalize(val):\n return val / getLength(val)\n\ndef getLength(a):\n return np.sqrt(np.dot(a, a))\n\nclass Tracer:\n camera = {}\n image = {}\n shader = {}\n surface = {}\n light = {}\n surfaceNum = 0\n lightNum = 0\n\n def setDefault(self):\n self.camera['viewDir'] = np.array([0,0,-1]).astype(np.float)\n self.camera['viewUp'] = np.array([0,1,0]).astype(np.float)\n self.camera['viewProjNormal'] = -1 * self.camera['viewDir']\n self.camera['viewWidth'] = 1.0\n self.camera['viewHeight'] = 1.0\n self.camera['projDistance'] = 1.0\n\n def createEmptyCanvas(self):\n channels = 3\n img = np.zeros((self.image['height'], self.image['width'], channels), dtype=np.uint8)\n img[:,:] = 0\n\n return img\n\n def saveImg(self, name):\n img = Image.fromarray(self.img, 'RGB')\n img.save(name + '.png')\n\n def parseData(self, file):\n self.setDefault()\n\n tree = ET.parse(file)\n root = tree.getroot()\n\n for c in root.findall('camera'):\n self.camera['viewPoint'] = np.array(c.findtext('viewPoint').split()).astype(np.float)\n self.camera['viewDir'] = np.array(c.findtext('viewDir').split()).astype(np.float)\n self.camera['projNormal'] = np.array(c.findtext('projNormal').split()).astype(np.float)\n self.camera['viewUp'] = np.array(c.findtext('viewUp').split()).astype(np.float)\n self.camera['viewWidth'] = np.array(c.findtext('viewWidth').split()).astype(np.float)\n self.camera['viewHeight'] = np.array(c.findtext('viewHeight').split()).astype(np.float)\n\n if (c.findtext('projDistance')) != None:\n self.camera['projDistance'] = np.array(c.findtext('projDistance').split()).astype(np.float)\n else:\n self.camera['projDistance'] = 1.0\n\n for c in root.findall('shader'):\n name = c.attrib['name']\n self.shader[name] = {}\n self.shader[name]['type'] = c.attrib['type']\n self.shader[name]['diffuseColor'] = np.array(c.findtext('diffuseColor').split()).astype(np.float)\n\n if self.shader[name]['type'] == 'Phong':\n self.shader[name]['specularColor'] = np.array(c.findtext('specularColor').split()).astype(np.float)\n self.shader[name]['exponent'] = float(c.findtext('exponent'))\n\n for c in root.findall('surface'):\n cnt = self.surfaceNum\n self.surface[cnt] = {}\n self.surface[cnt]['type'] = c.attrib['type']\n self.surface[cnt]['name'] = c.find('shader').attrib['ref']\n\n if self.surface[cnt]['type'] == 'Box':\n self.surface[cnt]['minPt'] = np.array(c.findtext('minPt').split()).astype(np.float)\n self.surface[cnt]['maxPt'] = np.array(c.findtext('maxPt').split()).astype(np.float)\n else:\n self.surface[cnt]['center'] = np.array(c.findtext('center').split()).astype(np.float)\n self.surface[cnt]['radius'] = float(c.findtext('radius'))\n\n self.surfaceNum += 1\n\n for c in root.findall('light'):\n cnt = self.lightNum\n self.light[cnt] = {}\n self.light[cnt]['position'] = np.array(c.findtext('position').split()).astype(np.float)\n self.light[cnt]['intensity'] = np.array(c.findtext('intensity').split()).astype(np.float)\n\n self.lightNum += 1\n\n imgSize = np.array(root.findtext('image').split()).astype(np.int)\n self.image['width'] = imgSize[0]\n self.image['height'] = imgSize[1]\n\n def intersection_sphere(self, point, D, surface):\n P = point - surface['center']\n a = dot(D, D)\n b = dot(D, P)\n c = dot(P, P) - surface['radius'] ** 2\n\n temp = (b ** 2) - (a * c)\n\n if temp < 0:\n return None\n else:\n return min((-b + np.sqrt(temp)) / a, (-b - np.sqrt(temp)) / a)\n\n def intersection_box(self, P, D, surface):\n tnear = -math.inf\n tfar = math.inf\n\n for i in range(3):\n if D[i] == 0:\n if (P[i] < surface['minPt'][i] or P[i] > surface['maxPt'][i]):\n return None\n else:\n t1 = (surface['minPt'][i] - P[i]) / D[i]\n t2 = (surface['maxPt'][i] - P[i]) / D[i]\n\n if t1 > t2:\n t1, t2 = t2, t1\n if t1 > tnear:\n tnear = t1\n if t2 < tfar:\n tfar = t2\n if tnear > tfar:\n return None\n if tfar < 0:\n return None\n\n return tnear\n\n def findClosestObj(self, D):\n E = self.camera['viewPoint']\n tmin = math.inf\n closestObj = None\n\n for cnt in range(self.surfaceNum):\n surface = self.surface[cnt]\n t = None\n\n if surface['type'] == 'Sphere':\n t = self.intersection_sphere(E, D, surface)\n else:\n t = self.intersection_box(E, D, surface)\n\n if t == None:\n continue\n\n if t < tmin:\n closestObj = cnt\n tmin = t\n\n return tmin, closestObj\n\n def shadow(self, P, pixelColor, closestObj):\n shadowDir = normalize(self.light['position'] - P)\n color = pixelColor\n\n for o in range(self.surfaceNum):\n if closestObj == o:\n continue\n\n if self.surface[o]['type'] == 'Sphere':\n shadowT = self.intersection_sphere(P, shadowDir, self.surface[o])\n else:\n shadowT = self.intersection_box(P, shadowDir, self.surface[o])\n\n if shadowT == None:\n continue\n\n if dot(shadowT - P, shadowDir) < 0:\n continue\n\n color = [0, 0, 0]\n break\n\n return color\n\n\n def coloring(self, P, D, closestObj):\n surface = self.surface[closestObj]\n name = surface['name']\n E = self.camera['viewPoint']\n\n pixelColor = [0, 0, 0]\n addColor = [0, 0, 0]\n\n for cnt in self.light:\n light = self.light[cnt]\n L = normalize(light['position'] - P)\n\n if self.surface[closestObj]['type'] == 'Box':\n bias = 1.000001\n dp = (surface['minPt'] - surface['maxPt']) / 2\n N = np.array([\n int(P[0] / abs(dp[0]) * bias), \n int(P[1] / abs(dp[1]) * bias), \n int(P[2] / abs(dp[2]) * bias)]).astype(np.float)\n N = normalize(N)\n\n H = normalize((E - P) + L)\n else:\n H = normalize(-D + L)\n N = normalize(P - self.surface[closestObj]['center'])\n\n # intensity = light['intensity']\n diffuseColor = self.shader[name]['diffuseColor']\n pixelColor = diffuseColor\n\n # pixelColor += (diffuseColor * intensity * max(0, dot(N, L)))\n\n # # pixelColor = self.shadow(P, defaultColor, closestObj)\n # if self.shader[name]['type'] == 'Phong':\n # specularColor = self.shader[name]['specularColor']\n # exponent = self.shader[name]['exponent']\n # addColor += specularColor * intensity * np.power(max(0, np.dot(N, H)), exponent)\n\n # pixelColor += addColor\n pixelColor = Color(pixelColor[0], pixelColor[1], pixelColor[2])\n pixelColor.gammaCorrect(2.2)\n\n return pixelColor.toUINT8()\n\n def draw(self):\n self.img = self.createEmptyCanvas()\n\n E = self.camera['viewPoint']\n W = normalize(self.camera['projNormal'])\n U = normalize(cross(self.camera['viewUp'], W))\n V = -normalize(cross(W, U))\n\n x1 = -self.camera['viewWidth'] / 2\n y1 = -self.camera['viewHeight'] / 2\n x2 = self.camera['viewWidth'] / 2\n y2 = self.camera['viewHeight'] / 2\n imageW = self.image['width']\n imageH = self.image['height']\n\n for i in range(imageW):\n for j in range(imageH):\n x = x1 + (x2 - x1) * (i + 0.5) / imageW\n y = y1 + (y2 - y1) * (j + 0.5) / imageH\n S = E + (x * U) + (y * V) - (self.camera['projDistance'] * W)\n D = normalize(S - E)\n\n t, closestObj = self.findClosestObj(D)\n\n if t == math.inf:\n continue\n\n P = E + t * D\n\n self.img[j][i] = self.coloring(P, D, closestObj)\n\n def __init__(self, file):\n self.parseData(file)\n\nclass Color:\n def __init__(self, R, G, B):\n self.color=np.array([R,G,B]).astype(np.float)\n\n def gammaCorrect(self, gamma):\n inverseGamma = 1.0 / gamma;\n self.color=np.power(self.color, inverseGamma)\n\n def toUINT8(self):\n return (np.clip(self.color, 0,1)*255).astype(np.uint8)\n\ndef main():\n shape = Tracer(sys.argv[1])\n shape.draw()\n shape.saveImg(sys.argv[1])\n\nif __name__ == '__main__':\n main()","sub_path":"project01/rayTracer_0425.py","file_name":"rayTracer_0425.py","file_ext":"py","file_size_in_byte":9306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"21718218","text":"#!/usr/bin/env python3\n\nimport discord, sys, traceback, io\nfrom bot_utils import setup, send_msg, sc_precision\n\nfrom datetime import datetime, timedelta\nfrom subprocess import Popen, PIPE\n\n\"\"\"\nlog-checker checks journal logs for siad.\n\nArguments:\n 1. path to a .env file (default is none so env variables can already be\n preset)\n\n 2. systemd service name (default: \"siad\")\n\n 3. number of hours to look back in log (used as --since value in journalctl\n command) (default: 1 hour)\n\n\"\"\"\n\nDEFAULT_CHECK_INTERVAL = timedelta(hours=1)\n\nbot_token = setup()\nclient = discord.Client()\n\n@client.event\nasync def on_ready():\n await run_checks()\n await client.close()\n\n\nasync def run_checks():\n print(\"Running Skynet portal log checks\")\n try:\n await check_journal()\n\n except: # catch all exceptions\n trace = traceback.format_exc()\n await send_msg(client, \"```\\n{}\\n```\".format(trace), force_notify=False)\n\n\n# check_journal checks the journal\nasync def check_journal():\n print(\"\\nChecking journal...\")\n\n # Get the systemd service name as an argument, or use \"siad\" as default.\n service_name = \"siad\"\n if len(sys.argv) > 2:\n service_name = sys.argv[2]\n\n # Get the systemd service name as an argument, or use \"siad\" as default.\n check_interval = DEFAULT_CHECK_INTERVAL\n if len(sys.argv) > 3:\n check_interval = timedelta(hours=int(sys.argv[3]))\n\n now = datetime.now()\n time = now - check_interval\n time_string = \"{}-{}-{} {}:{}:{}\".format(time.year, time.month, time.day, time.hour, time.minute, time.second)\n\n # Open the journal.\n proc = Popen([\"journalctl\", \"--user-unit\", service_name, \"--since\", time_string], stdin=PIPE, stdout=PIPE, stderr=PIPE, text=True)\n std_out, std_err = proc.communicate()\n\n if len(std_err) > 0:\n await send_msg(client, \"Error reading journalctl output: {}\".format(std_err), force_notify=True)\n return\n\n # If there are any critical errors. upload the whole log file.\n if \"Critical\" in std_out or \"panic\" in std_out:\n upload_name = \"{}-{}-{}-{}-{}:{}:{}.log\".format(service_name, time.year, time.month, time.day, time.hour, time.minute, time.second)\n await send_msg(client, \"Critical error found in log!\", file=discord.File(io.BytesIO(std_out.encode()), filename=upload_name), force_notify=True)\n return\n\n # No critical errors, return a heartbeat type messagej\n pretty_before = time.strftime(\"%I:%M%p\")\n pretty_now = now.strftime(\"%I:%M%p\")\n await send_msg(client, \"No critical warnings in log from `{}` to `{}`\".format(pretty_before, pretty_now))\n\n\nclient.run(bot_token)\n","sub_path":"setup-scripts/log-checker.py","file_name":"log-checker.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"154444584","text":"\nimport os\nimport tensorflow as tf\n\n\n\n###caution it is a little complex\n\n### produce a ckpt file that training_flag in False mode\ncommand_for_make_it_eval=\"python tools/net_work_for_tf_lite.py\"\nos.system(command_for_make_it_eval)\n\nprint('done step 1')\n\n### freeze the deployed ckpt\ncommand_for_freeze=\"python tools/auto_freeze.py\"\nos.system(command_for_freeze)\nprint('done step 2')\n\n### convert to tf_lite\ncommand_for_freeze=\"python tools/tf_lite.py\"\nos.system(command_for_freeze)\nprint('done step 3')\nprint('over')","sub_path":"tools/auto_convert_tf_lite.py","file_name":"auto_convert_tf_lite.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"339434282","text":"# -*- coding: utf-8 -*-\n#\n# This file is part of Invenio.\n# Copyright (C) 2017-2019 CERN.\n#\n# Invenio 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\n\"\"\"Flask extension for Invenio-XRootD.\"\"\"\n\nfrom pkg_resources import DistributionNotFound, get_distribution\n\ntry:\n # Import XRootDPyFS if available so that its\n # opener gets registered on PyFilesystem.\n get_distribution(\"xrootdpyfs\")\n import xrootdpyfs\n\n XROOTD_ENABLED = True\nexcept DistributionNotFound:\n XROOTD_ENABLED = False\n xrootdpyfs = None\n\n\nclass InvenioXRootD(object):\n \"\"\"Invenio-XRootD extension.\"\"\"\n\n def __init__(self, app=None):\n \"\"\"Extension initialization.\"\"\"\n if app:\n self.init_app(app)\n\n def init_app(self, app):\n \"\"\"Extension registration and configuration.\"\"\"\n app.config[\"XROOTD_ENABLED\"] = XROOTD_ENABLED\n if XROOTD_ENABLED:\n app.config[\n \"FILES_REST_STORAGE_FACTORY\"\n ] = \"invenio_xrootd:eos_storage_factory\"\n app.extensions[\"invenio-xrootd\"] = self\n","sub_path":"invenio_xrootd/ext.py","file_name":"ext.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"212013889","text":"import logging\nfrom config import *\nfrom server_connections import *\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n\ndef receive_from_client_udp():\n udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n udp.bind(server_address)\n\n while True:\n data, address = udp.recvfrom(buffer_size)\n logger.debug(\"{} sent message: {}\".format(address, data.decode()))\n\n with lock:\n for client_address, client_socket in connected_clients.items():\n if client_address != address:\n udp.sendto(data, client_address)\n","sub_path":"server_udp.py","file_name":"server_udp.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"113954484","text":"import copy\nimport math\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import Module as Module\n\n\ndef gelu(x):\n \"\"\"Implementation of the gelu activation function.\n For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):\n 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))\n Also see https://arxiv.org/abs/1606.08415\n \"\"\"\n return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))\n\n\nclass PositionalEncoding(Module):\n\n def __init__(self, d_model, dropout=0.1, max_len=5000):\n super(PositionalEncoding, self).__init__()\n self.dropout = nn.Dropout(p=dropout)\n\n pe = torch.zeros(max_len, d_model)\n position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)\n div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))\n pe[:, 0::2] = torch.sin(position * div_term)\n pe[:, 1::2] = torch.cos(position * div_term)\n pe = pe.unsqueeze(0).transpose(0, 1)\n self.register_buffer('pe', pe)\n\n def forward(self, x):\n x = x + torch.transpose(self.pe, 1, 0)\n return self.dropout(x)\n\n\nclass BertLayerNorm(Module):\n def __init__(self, hidden_size, eps=1e-12):\n \"\"\"\n Construct a layernorm module in the TF style (epsilon inside the square root).\n \"\"\"\n super(BertLayerNorm, self).__init__()\n self.weight = nn.Parameter(torch.ones(hidden_size))\n self.bias = nn.Parameter(torch.zeros(hidden_size))\n self.variance_epsilon = eps\n\n def forward(self, x):\n u = x.mean(-1, keepdim=True)\n s = (x - u).pow(2).mean(-1, keepdim=True)\n x = (x - u) / torch.sqrt(s + self.variance_epsilon)\n return self.weight * x + self.bias\n\n\nclass BertSelfAttention(Module):\n def __init__(self, config):\n super(BertSelfAttention, self).__init__()\n if config['hidden_dim'] % config['num_attention_heads'] != 0:\n raise ValueError(\n \"The hidden size (%d) is not a multiple of the number of attention \"\n \"heads (%d)\" % (config['hidden_dim'], config['num_attention_heads']))\n self.num_attention_heads = config['num_attention_heads']\n self.attention_head_size = int(config['hidden_dim'] / config['num_attention_heads'])\n self.all_head_size = self.num_attention_heads * self.attention_head_size\n\n self.query = nn.Linear(config['hidden_dim'], self.all_head_size)\n self.key = nn.Linear(config['hidden_dim'], self.all_head_size)\n self.value = nn.Linear(config['hidden_dim'], self.all_head_size)\n if 'attention_temperature' in config:\n self.temp = config['attention_temperature']\n else:\n self.temp = 1\n self.dropout = nn.Dropout(0.1)\n\n def transpose_for_scores(self, x):\n new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)\n x = x.view(*new_x_shape)\n return x.permute(0, 2, 1, 3)\n\n def forward(self, hidden_states, attention_mask, output_attention_probs=False):\n mixed_query_layer = self.query(hidden_states)\n mixed_key_layer = self.key(hidden_states)\n mixed_value_layer = self.value(hidden_states)\n\n query_layer = self.transpose_for_scores(mixed_query_layer)\n key_layer = self.transpose_for_scores(mixed_key_layer)\n value_layer = self.transpose_for_scores(mixed_value_layer)\n\n # Take the dot product between \"query\" and \"key\" to get the raw attention scores.\n attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))\n attention_scores = attention_scores / math.sqrt(self.attention_head_size)\n # Apply the attention mask is (precomputed for all layers in BertModel forward() function)\n attention_scores = attention_scores + attention_mask\n\n # Normalize the attention scores to probabilities.\n attention_probs = nn.Softmax(dim=-1)(attention_scores / self.temp)\n\n # This is actually dropping out entire tokens to attend to, which might\n # seem a bit unusual, but is taken from the original Transformer paper.\n attention_probs = self.dropout(attention_probs)\n\n context_layer = torch.matmul(attention_probs, value_layer)\n context_layer = context_layer.permute(0, 2, 1, 3).contiguous()\n new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)\n context_layer = context_layer.view(*new_context_layer_shape)\n if output_attention_probs:\n return context_layer, attention_probs\n else:\n return context_layer\n\n\nclass BertSelfOutput(Module):\n def __init__(self, config):\n super(BertSelfOutput, self).__init__()\n self.dense = nn.Linear(config['hidden_dim'], config['hidden_dim'])\n self.LayerNorm = BertLayerNorm(config['hidden_dim'], eps=1e-12)\n self.dropout = nn.Dropout(0.1)\n\n def forward(self, hidden_states, input_tensor):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.dropout(hidden_states)\n hidden_states = self.LayerNorm(hidden_states + input_tensor)\n return hidden_states\n\n\nclass BertAttention(Module):\n def __init__(self, config):\n super(BertAttention, self).__init__()\n self.self = BertSelfAttention(config)\n self.output = BertSelfOutput(config)\n\n def forward(self, input_tensor, attention_mask, output_attention_probs=False):\n self_output = self.self(input_tensor, attention_mask, output_attention_probs=output_attention_probs)\n if output_attention_probs:\n self_output, attention_probs = self_output\n attention_output = self.output(self_output, input_tensor)\n if output_attention_probs:\n return attention_output, attention_probs\n return attention_output\n\n\nclass BertIntermediate(Module):\n def __init__(self, config):\n super(BertIntermediate, self).__init__()\n self.dense = nn.Linear(config['hidden_dim'], config['inter_dim'])\n self.intermediate_act_fn = gelu\n\n def forward(self, hidden_states):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.intermediate_act_fn(hidden_states)\n return hidden_states\n\n\nclass BertOutput(Module):\n def __init__(self, config):\n super(BertOutput, self).__init__()\n self.dense = nn.Linear(config['inter_dim'], config['hidden_dim'])\n self.LayerNorm = BertLayerNorm(config['hidden_dim'], eps=1e-12)\n self.dropout = nn.Dropout(0.1)\n\n def forward(self, hidden_states, input_tensor):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.dropout(hidden_states)\n hidden_states = self.LayerNorm(hidden_states + input_tensor)\n return hidden_states\n\n\nclass BertLayer(Module):\n def __init__(self, config):\n super(BertLayer, self).__init__()\n self.attention = BertAttention(config)\n self.intermediate = BertIntermediate(config)\n self.output = BertOutput(config)\n\n def forward(self, hidden_states, attention_mask, output_attention_probs=False):\n attention_output = self.attention(hidden_states, attention_mask, output_attention_probs=output_attention_probs)\n if output_attention_probs:\n attention_output, attention_probs = attention_output\n intermediate_output = self.intermediate(attention_output)\n layer_output = self.output(intermediate_output, attention_output)\n if output_attention_probs:\n return layer_output, attention_probs\n else:\n return layer_output\n\n\nclass BertEncoder(Module):\n def __init__(self, config):\n super(BertEncoder, self).__init__()\n layer = BertLayer(config)\n self.layer = nn.ModuleList([copy.deepcopy(layer) for _ in range(config['num_bert_layers'])])\n\n def forward(self, hidden_states, attention_mask, output_all_encoded_layers=False, output_attention_probs=True):\n all_encoder_layers = []\n all_attention_probs = []\n for layer_module in self.layer:\n hidden_states = layer_module(hidden_states, attention_mask, output_attention_probs=output_attention_probs)\n if output_attention_probs:\n hidden_states, attention_probs = hidden_states\n all_attention_probs.append(attention_probs)\n if output_all_encoded_layers:\n all_encoder_layers.append(hidden_states)\n if not output_all_encoded_layers:\n all_encoder_layers.append(hidden_states)\n if output_attention_probs:\n return all_encoder_layers, all_attention_probs\n else:\n return all_encoder_layers\n","sub_path":"generation/rn_testbed/bert_modules/bert_modules.py","file_name":"bert_modules.py","file_ext":"py","file_size_in_byte":8733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"622071292","text":"\nimport random\n\nimport numpy as np\n\nfrom . import SchedulerBase, StaticScheduler\nfrom .utils import compute_b_level_duration, compute_independent_tasks, get_duration_estimate, \\\n max_cpus_worker\nfrom ..simulator import TaskAssignment\n\n\nclass CampCore:\n\n def __init__(self, simulator):\n self.simulator = simulator\n\n independencies = compute_independent_tasks(simulator.task_graph)\n self.independecies = independencies\n\n workers = self.simulator.workers\n\n placement = np.empty(len(simulator.task_graph.tasks),\n dtype=np.int32)\n placement[:] = workers.index(max_cpus_worker(workers))\n self.placement = placement\n self.b_level = compute_b_level_duration(simulator.task_graph)\n\n def compute(self, iterations):\n\n placement = self.placement\n workers = self.simulator.workers\n independencies = self.independecies\n cpu_factor = sum([w.cpus for w in workers]) / len(workers)\n\n # Repulse score\n repulse_score = {}\n tasks = []\n self.tasks = tasks\n task_info = self.simulator.runtime_state.task_info\n\n for task, indeps in independencies.items():\n if not task_info(task).is_waiting:\n continue\n tasks.append(task)\n lst = []\n repulse_score[task] = lst\n if not indeps:\n continue\n task_value = get_duration_estimate(task) / len(indeps) * task.cpus / cpu_factor\n for t in indeps:\n score = task_value + get_duration_estimate(t) / len(independencies[t]) \\\n * t.cpus / cpu_factor\n lst.append((t.id, score))\n\n if not tasks:\n return\n\n for i in range(iterations):\n t = random.randint(0, len(tasks) - 1)\n task = tasks[t]\n old_w = placement[task.id]\n new_w = random.randint(0, len(workers) - 2)\n if new_w >= old_w:\n new_w += 1\n if workers[new_w].cpus < tasks[t].cpus:\n continue\n old_score = self.compute_task_score(repulse_score, placement, task)\n placement[task.id] = new_w\n new_score = self.compute_task_score(repulse_score, placement, task)\n # and np.random.random() > (i / limit) / 100:\n if new_score > old_score:\n placement[task.id] = old_w\n\n def compute_input_score(self, placement, task):\n old_worker = placement[task.id]\n score = 0\n for inp in task.inputs:\n size = inp.expected_size\n if size > score and placement[inp.parent.id] != old_worker:\n score = size\n return score\n\n def compute_task_score(self, repulse_score, placement, task):\n score = self.compute_input_score(placement, task)\n for t in task.consumers():\n score += self.compute_input_score(placement, t)\n score /= self.simulator.netmodel.bandwidth\n p = placement[task.id]\n for t_id, v in repulse_score[task]:\n if placement[t_id] == p:\n score += v\n return score\n\n def make_assignments(self):\n workers = self.simulator.workers\n placement = self.placement\n b_level = self.b_level\n\n return [TaskAssignment(workers[placement[task.id]], task, b_level[task])\n for task in self.tasks]\n\n\nclass Camp2Scheduler(StaticScheduler):\n\n def __init__(self, iterations=2000):\n super().__init__()\n self.iterations = iterations\n\n def init(self, simulator):\n super().init(simulator)\n\n def static_schedule(self):\n core = CampCore(self.simulator)\n core.compute(self.iterations)\n return core.make_assignments()\n\n\nclass TwoLayerScheduler(SchedulerBase):\n\n def compute_schedule(self):\n raise NotImplementedError()\n\n def schedule(self, new_ready, new_finished):\n assignments = self.compute_schedule()\n simulator = self.simulator\n result = []\n\n task_info = self.simulator.task_info\n\n free_cpus = {\n worker: worker.cpus - sum(t.cpus for t in worker.assigned_tasks)\n for worker in simulator.workers\n }\n\n assignments.sort(key=lambda a: a.priority, reverse=True)\n\n for assignment in assignments:\n # info = simulator.task_info(assignment.task)\n task = assignment.task\n # or any(task_info(o.parent).is_finished for o in task.inputs):\n if free_cpus[assignment.worker] > 0 and task_info(task).is_ready:\n result.append(assignment)\n free_cpus[assignment.worker] -= task.cpus\n\n \"\"\"\n result = []\n for worker in self.simulator.workers:\n #free_cpus = 2 * worker.cpus - sum(t.cpus for t in worker.assigned_tasks if t.is_ready)\n #tasks = [self._is_task_prepared(t) for t in worker.s_info]\n result += [assignment for assignment in worker.s_info\n if assignment.task.info.is_ready or (assignment.task.info.is_waiting and\n any(t.info.is_ready for t in assignment.task.inputs))]\n \"\"\"\n return result\n\n\nclass Camp3Scheduler(TwoLayerScheduler):\n\n def __init__(self, iterations=2000):\n super().__init__()\n self.iterations = iterations\n\n def init(self, simulator):\n super().init(simulator)\n self.core = CampCore(simulator)\n self.core.compute(4000)\n\n def compute_schedule(self):\n self.core.compute(self.iterations)\n return self.core.make_assignments()\n","sub_path":"schedsim/schedulers/camp.py","file_name":"camp.py","file_ext":"py","file_size_in_byte":5636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"56375785","text":"import tensorflow as tf\r\n\r\n\r\nclass ConvBNRelu(tf.keras.Model):\r\n\r\n def __init__(self, ch, kernelsz=3, strides=1, padding='same'):\r\n super(ConvBNRelu, self).__init__()\r\n\r\n self.model = tf.keras.models.Sequential([\r\n tf.keras.layers.Conv2D(ch, kernelsz, strides=strides, padding=padding),\r\n tf.keras.layers.BatchNormalization(),\r\n tf.keras.layers.ReLU()\r\n ])\r\n\r\n def call(self, x, training=None):\r\n x = self.model(x, training=training)\r\n\r\n return x\r\n\r\n\r\n\r\nclass mix_channels_block(tf.keras.Model):\r\n def __init__(self, mid_c, rec_c):\r\n super(mix_channels_block, self).__init__()\r\n self.rec_c = rec_c\r\n self.mid_c = mid_c\r\n self.initializer = tf.keras.initializers.random_normal(0, 0.02)\r\n self.repara = tf.keras.layers.Multiply()\r\n self.embedding = tf.keras.layers.Embedding(input_dim=6,\r\n output_dim=rec_c,\r\n embeddings_initializer=self.initializer,\r\n embeddings_regularizer=tf.keras.regularizers.l2(l=0.02)\r\n )\r\n self.conv1 = ConvBNRelu(ch=32, kernelsz=3)\r\n self.conv2 = ConvBNRelu(ch=mid_c, kernelsz=1)\r\n\r\n def call(self, x, idx_dir):\r\n \"\"\"\"fft_length\": 1023,\r\n \"frame_step\": 256,\r\n \"frame_length\": 1024,\r\n \"pad_end\": 1,\r\n \"name\": \"stft\"\"\"\r\n # idx = self.embedding(idx_dir)\r\n # idx = tf.expand_dims(tf.expand_dims(tf.squeeze(tf.transpose(idx, [0, 2, 1]), axis=-1), axis=1), axis=1)\r\n x = self.conv1(x)\r\n x = self.conv2(x)\r\n return x\r\n\r\n\r\nclass Downsample(tf.keras.Model):\r\n\r\n def __init__(self, filters, kernel_size, apply_batchnorm = True):\r\n super(Downsample, self).__init__()\r\n self.apply_batchnorm = apply_batchnorm\r\n self.initializer = tf.keras.initializers.random_normal(0, 0.02)\r\n self.conv1 = tf.keras.layers.Conv2D(filters,\r\n kernel_size,\r\n strides=2,\r\n padding=\"same\",\r\n kernel_initializer=self.initializer,\r\n use_bias=False)\r\n if self.apply_batchnorm:\r\n self.batchnorm = tf.keras.layers.BatchNormalization()\r\n\r\n def call(self, inputs, training=None, mask=None):\r\n inputs = self.conv1(inputs)\r\n if self.apply_batchnorm:\r\n inputs = self.batchnorm(inputs, training=training)\r\n outputs = tf.nn.leaky_relu(inputs)\r\n return outputs\r\n\r\nclass Upsample(tf.keras.Model):\r\n def __init__(self, filters, kernel_size, apply_dropout=False):\r\n super(Upsample, self).__init__()\r\n self.apply_dropout = apply_dropout\r\n self.initializer = tf.keras.initializers.random_normal(0, 0.02)\r\n self.up_conv = tf.keras.layers.Conv2DTranspose(filters=filters,\r\n kernel_size=kernel_size,\r\n strides=2,\r\n padding=\"same\",\r\n kernel_initializer=self.initializer,\r\n use_bias=False)\r\n self.batch_norm = tf.keras.layers.BatchNormalization()\r\n if self.apply_dropout:\r\n self.dropout = tf.keras.layers.Dropout(0.5)\r\n\r\n def call(self, x1, x2, training):\r\n x = self.up_conv(x1)\r\n x = self.batch_norm(x, training=training)\r\n if self.apply_dropout:\r\n x = self.dropout(x, training=training)\r\n x = tf.nn.relu6(x)\r\n x = tf.concat([x, x2], axis=-1)\r\n return x\r\n\r\nclass BidirGRU(tf.keras.Model):\r\n def __init__(self, units=256):\r\n super(BidirGRU, self).__init__()\r\n self.initializer = tf.keras.initializers.random_normal(0, 0.02)\r\n self.bigru = tf.keras.layers.Bidirectional(tf.keras.layers.GRU(units=units,\r\n return_sequences=True,\r\n ))\r\n def call(self, x):\r\n x_shape = x.shape\r\n x =tf.reshape(x, [x.shape[0], x.shape[1], -1])\r\n out = self.bigru(x)\r\n return tf.reshape(out, [x_shape[0], -1, x_shape[2], x_shape[3]])\r\n\r\n\r\nclass DiscDownsample(tf.keras.Model):\r\n def __init__(self, filters, kernel_size, apply_batchnorm=False):\r\n super(DiscDownsample, self).__init__()\r\n self.apply_batch_norm = apply_batchnorm\r\n self.initializer = tf.keras.initializers.random_normal(0, 0.02)\r\n self.conv1 = tf.keras.layers.Conv2D(filters=filters,\r\n kernel_size=kernel_size,\r\n strides=2,\r\n kernel_initializer=self.initializer,\r\n use_bias=False,\r\n padding=\"same\")\r\n if self.apply_batch_norm:\r\n self.batchnorm = tf.keras.layers.BatchNormalization()\r\n def call(self, x, training):\r\n x = self.conv1(x)\r\n if self.apply_batch_norm:\r\n x = self.batchnorm(x, training=training)\r\n x = tf.nn.leaky_relu(x)\r\n return x\r\n\r\nclass Generator(tf.keras.Model):\r\n\r\n\r\n def __init__(self, include_bigru = False,mid_c=3, rec_c=7):\r\n super(Generator, self).__init__()\r\n self.include_bigru = include_bigru\r\n self.initializer = tf.keras.initializers.random_normal(0, 0.02)\r\n # self.mix_channel = mix_channels_block(mid_c=mid_c, rec_c=rec_c)\r\n self.down1 = Downsample(32, 4, apply_batchnorm=False)\r\n self.down2 = Downsample(64, 4, apply_batchnorm=True)\r\n self.down3 = Downsample(128, 4, apply_batchnorm=True)\r\n self.down4 = Downsample(256, 4, apply_batchnorm=True)\r\n self.down5 = Downsample(512, 4, apply_batchnorm=True)\r\n self.down6 = Downsample(512, 4, apply_batchnorm=True)\r\n self.down7 = Downsample(512, 4, apply_batchnorm=True)\r\n if self.include_bigru:\r\n self.biGru = BidirGRU()\r\n self.up1 = Upsample(512, 4, True)\r\n self.up2 = Upsample(512, 4, True)\r\n self.up3 = Upsample(256, 4, True)\r\n self.up4 = Upsample(128, 4, True)\r\n self.up5 = Upsample(64, 4, True)\r\n self.up6 = Upsample(32, 4, True)\r\n self.last = tf.keras.layers.Conv2DTranspose(filters=1,\r\n kernel_size=(4, 4),\r\n strides=2,\r\n padding='same',\r\n kernel_initializer=self.initializer)\r\n\r\n def call(self, x, training):\r\n # x0 = self.mix_channel(x, tar_dir)\r\n x1 = self.down1(x, training)\r\n x2 = self.down2(x1, training)\r\n x3 = self.down3(x2, training)\r\n x4 = self.down4(x3, training)\r\n x5 = self.down5(x4, training)\r\n x6 = self.down6(x5, training)\r\n if self.include_bigru:\r\n x7 = self.biGru(x6)\r\n else:\r\n x7 = self.down7(x6, training=training)\r\n x8 = self.up1(x7, x6, training=training)\r\n x9 = self.up2(x8, x5, training=training)\r\n x10 = self.up3(x9, x4, training=training)\r\n x11 = self.up4(x10, x3, training=training)\r\n x12 = self.up5(x11, x2, training=training)\r\n x13 = self.up6(x12, x1, training=training)\r\n x14 = self.last(x13)\r\n x14 = tf.nn.relu6(x14)\r\n return x14\r\n\r\ndef conv3x3(channels, stride=1, kernel=(3, 3)):\r\n\r\n return tf.keras.layers.Conv2D(filters=channels,\r\n kernel_size=kernel,\r\n strides=stride,\r\n padding='same',\r\n use_bias=False,\r\n kernel_initializer=tf.random_normal_initializer())\r\n\r\nclass ResnetBlock(tf.keras.Model):\r\n\r\n def __init__(self, channels, strides, residual_path=False):\r\n super(ResnetBlock, self).__init__()\r\n\r\n self.channels = channels\r\n self.strides = strides\r\n self.residual_path = residual_path\r\n self.conv1 = conv3x3(channels, strides)\r\n self.bn1 = tf.keras.layers.BatchNormalization()\r\n self.conv2 = conv3x3(channels)\r\n self.bn2 = tf.keras.layers.BatchNormalization()\r\n\r\n if residual_path:\r\n self.down_conv = conv3x3(channels, stride=strides)\r\n self.down_bn = tf.keras.layers.BatchNormalization()\r\n\r\n def call(self, inputs, training=True, mask=None):\r\n residual = inputs\r\n x = self.bn1(inputs, training=training)\r\n x = tf.nn.relu(x)\r\n x = self.conv1(x)\r\n x = self.bn2(x, training=training)\r\n x = tf.nn.relu(x)\r\n x = self.conv2(x)\r\n if self.residual_path:\r\n residual = self.down_bn(inputs, training=training)\r\n residual = tf.nn.relu(residual)\r\n residual = self.down_conv(residual)\r\n x = x + residual\r\n return x\r\n\r\nclass Discriminator(tf.keras.Model):\r\n def __init__(self):\r\n super(Discriminator, self).__init__()\r\n \"\"\"\r\n filters, kernel_size, apply_batchnorm = True\"\"\"\r\n self.conv1 = DiscDownsample(16, kernel_size=(3, 3), apply_batchnorm=False)\r\n self.avg_pooling1 = tf.keras.layers.AveragePooling2D()\r\n self.conv2 = DiscDownsample(32, kernel_size=(3, 3), apply_batchnorm=True)\r\n self.avg_pooling2 = tf.keras.layers.AveragePooling2D()\r\n self.conv3 = DiscDownsample(64, kernel_size=(3, 3), apply_batchnorm=True)\r\n self.avg_pooling3 = tf.keras.layers.AveragePooling2D()\r\n self.conv4 = DiscDownsample(128, kernel_size=(3, 3), apply_batchnorm=True)\r\n self.conv5 = DiscDownsample(32, kernel_size=(3, 3), apply_batchnorm=True)\r\n self.Dense_out = tf.keras.layers.Dense(1)\r\n def call(self, inputs, training=True, mask=None):\r\n Gen_out, labels = inputs[0], inputs[1]\r\n bs = Gen_out.shape[0]\r\n Gen_out = self.conv1(Gen_out, training)\r\n Gen_out = self.avg_pooling1(Gen_out)\r\n Gen_out = self.conv2(Gen_out, training)\r\n Gen_out = self.avg_pooling2(Gen_out)\r\n Gen_out = self.conv3(Gen_out, training)\r\n Gen_out = self.avg_pooling3(Gen_out)\r\n Gen_out = self.conv4(Gen_out, training)\r\n Gen_out = self.conv5(Gen_out, training)\r\n labels = self.conv1(labels, training)\r\n labels = self.avg_pooling1(labels)\r\n labels = self.conv2(labels, training)\r\n labels = self.avg_pooling2(labels)\r\n labels = self.conv3(labels, training)\r\n labels = self.avg_pooling3(labels)\r\n labels = self.conv4(labels, training)\r\n labels = self.conv5(labels, training)\r\n # print(1) 32, 1, 1, 32\r\n Gen_out = tf.reshape(Gen_out, [bs, -1])\r\n labels = tf.reshape(labels, [bs, -1])\r\n diff = tf.nn.sigmoid(Gen_out - labels)\r\n logits = self.Dense_out(diff)\r\n return logits","sub_path":"ops.py","file_name":"ops.py","file_ext":"py","file_size_in_byte":11322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"579092304","text":"\"\"\"\r\nThe Moonstream subscriptions HTTP API\r\n\"\"\"\r\nimport logging\r\nfrom typing import Any, cast, Dict, List, Optional, Set, Union\r\nfrom pydantic.utils import to_camel\r\n\r\nfrom sqlalchemy.engine.base import Transaction\r\n\r\nfrom bugout.data import BugoutResource, BugoutResources\r\nfrom bugout.exceptions import BugoutResponseException\r\nfrom fastapi import Body, FastAPI, HTTPException, Request, Form, Query, Depends\r\nfrom fastapi.middleware.cors import CORSMiddleware\r\nfrom moonstreamdb.models import (\r\n EthereumBlock,\r\n EthereumTransaction,\r\n EthereumPendingTransaction,\r\n ESDFunctionSignature,\r\n ESDEventSignature,\r\n)\r\nfrom moonstreamdb import db\r\nfrom sqlalchemy.orm import Session\r\nfrom sqlalchemy import or_, and_\r\n\r\n\r\nfrom .. import data\r\nfrom ..middleware import BroodAuthMiddleware\r\nfrom ..settings import (\r\n MOONSTREAM_APPLICATION_ID,\r\n DOCS_TARGET_PATH,\r\n ORIGINS,\r\n DOCS_PATHS,\r\n bugout_client as bc,\r\n)\r\nfrom ..version import MOONSTREAM_VERSION\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\ntags_metadata = [\r\n {\"name\": \"streams\", \"description\": \"Operations with data stream and filters.\"},\r\n]\r\n\r\napp = FastAPI(\r\n title=f\"Moonstream streams API.\",\r\n description=\"Streams endpoints.\",\r\n version=MOONSTREAM_VERSION,\r\n openapi_tags=tags_metadata,\r\n openapi_url=\"/openapi.json\",\r\n docs_url=None,\r\n redoc_url=f\"/{DOCS_TARGET_PATH}\",\r\n)\r\n\r\napp.add_middleware(\r\n CORSMiddleware,\r\n allow_origins=ORIGINS,\r\n allow_credentials=True,\r\n allow_methods=[\"*\"],\r\n allow_headers=[\"*\"],\r\n)\r\n\r\nwhitelist_paths: Dict[str, str] = {}\r\nwhitelist_paths.update(DOCS_PATHS)\r\napp.add_middleware(BroodAuthMiddleware, whitelist=whitelist_paths)\r\n\r\n\r\n@app.get(\"/\", tags=[\"streams\"])\r\nasync def search_transactions(\r\n request: Request,\r\n q: str = Query(\"\"),\r\n filters: Optional[List[str]] = Query(None),\r\n limit: int = Query(10),\r\n offset: int = Query(0),\r\n db_session: Session = Depends(db.yield_db_session),\r\n):\r\n\r\n # get user subscriptions\r\n\r\n token = request.state.token\r\n params = {\"user_id\": str(request.state.user.id)}\r\n try:\r\n user_subscriptions_resources: BugoutResources = bc.list_resources(\r\n token=token, params=params\r\n )\r\n except BugoutResponseException as e:\r\n if e.detail == \"Resources not found\":\r\n return data.EthereumTransactionResponse(stream=[])\r\n raise HTTPException(status_code=e.status_code, detail=e.detail)\r\n except Exception as e:\r\n raise HTTPException(status_code=500)\r\n\r\n subscriptions_addresses = [\r\n resource.resource_data[\"address\"]\r\n for resource in user_subscriptions_resources.resources\r\n ]\r\n\r\n if q == \"\" or q == \" \":\r\n\r\n filters = [\r\n or_(\r\n EthereumTransaction.to_address == address,\r\n EthereumTransaction.from_address == address,\r\n )\r\n for address in subscriptions_addresses\r\n ]\r\n filters = or_(*filters)\r\n\r\n else:\r\n filters = database_search_query(q, allowed_addresses=subscriptions_addresses)\r\n if not filters:\r\n return data.EthereumTransactionResponse(stream=[])\r\n filters = and_(*filters)\r\n\r\n address_to_subscriptions = {\r\n resource.resource_data[\"address\"]: resource.resource_data\r\n for resource in user_subscriptions_resources.resources\r\n }\r\n\r\n ethereum_transactions = (\r\n db_session.query(\r\n EthereumTransaction.hash,\r\n EthereumTransaction.block_number,\r\n EthereumTransaction.from_address,\r\n EthereumTransaction.to_address,\r\n EthereumTransaction.gas,\r\n EthereumTransaction.gas_price,\r\n EthereumTransaction.input,\r\n EthereumTransaction.nonce,\r\n EthereumTransaction.value,\r\n EthereumBlock.timestamp,\r\n )\r\n .join(EthereumBlock)\r\n .filter(filters)\r\n .limit(25)\r\n )\r\n\r\n response = []\r\n for (\r\n hash,\r\n block_number,\r\n from_address,\r\n to_address,\r\n gas,\r\n gas_price,\r\n input,\r\n nonce,\r\n value,\r\n timestamp,\r\n ) in ethereum_transactions:\r\n\r\n subscription_type_id = None\r\n from_label = None\r\n to_label = None\r\n color = None\r\n\r\n if from_address in subscriptions_addresses:\r\n from_label = address_to_subscriptions[from_address][\"label\"]\r\n subscription_type_id = address_to_subscriptions[from_address][\r\n \"subscription_type_id\"\r\n ]\r\n color = address_to_subscriptions[from_address][\"color\"]\r\n\r\n if to_address in subscriptions_addresses:\r\n subscription_type_id = address_to_subscriptions[to_address][\r\n \"subscription_type_id\"\r\n ]\r\n to_label = address_to_subscriptions[to_address][\"label\"]\r\n color = address_to_subscriptions[to_address][\"color\"]\r\n\r\n response.append(\r\n data.EthereumTransactionItem(\r\n color=color,\r\n from_label=from_label,\r\n to_label=to_label,\r\n gas=gas,\r\n gasPrice=gas_price,\r\n value=value,\r\n from_address=from_address,\r\n to_address=to_address,\r\n hash=hash,\r\n input=input,\r\n nonce=nonce,\r\n timestamp=timestamp,\r\n subscription_type_id=\"1\",\r\n )\r\n )\r\n\r\n return data.EthereumTransactionResponse(stream=response)\r\n\r\n\r\ndef database_search_query(q: str, allowed_addresses: List[str]):\r\n\r\n filters = q.split(\"+\")\r\n constructed_filters = []\r\n for filter_item in filters:\r\n if filter_item == \"\":\r\n logger.warning(\"Skipping empty filter item\")\r\n continue\r\n\r\n # Try Google style search filters\r\n components = filter_item.split(\":\")\r\n if len(components) == 2:\r\n filter_type = components[0]\r\n filter_value = components[1]\r\n else:\r\n continue\r\n\r\n if filter_type == \"to\" and filter_value:\r\n constructed_filters.append(EthereumTransaction.to_address == filter_value)\r\n\r\n if filter_type == \"from\" and filter_value:\r\n if filter_value not in allowed_addresses:\r\n continue\r\n constructed_filters.append(EthereumTransaction.from_address == filter_value)\r\n\r\n if filter_type == \"address\" and filter_value:\r\n constructed_filters.append(\r\n or_(\r\n EthereumTransaction.to_address == filter_value,\r\n EthereumTransaction.from_address == filter_value,\r\n )\r\n )\r\n\r\n return constructed_filters\r\n","sub_path":"backend/moonstream/routes/streams.py","file_name":"streams.py","file_ext":"py","file_size_in_byte":6791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"353265521","text":"from flask import Flask, render_template, jsonify, request\nfrom pymongo import MongoClient\nimport re\nfrom config import *\n\napp = Flask(__name__)\napp.config['JSON_AS_ASCII'] = False\n\nclient = MongoClient(**MONGOSERVER)\ndb = client[DBNAME]\n\n\ndef check_num(s, v=None):\n if s is None:\n return v\n rc = re.compile(r'^\\d+$')\n ret = rc.match(s)\n return ret[0] if ret is not None else v\n\n\ndef handle_args(default_size=20):\n page = request.args.get('page')\n page_size = request.args.get('pagesize')\n page = check_num(page, 1)\n page_size = check_num(page_size, 10)\n page_size = int(page_size)\n if page_size > default_size:\n page_size = default_size\n skip = (int(page) - 1) * page_size\n return skip, page_size\n\n\ndef handle_query(query):\n dic = dict()\n for k,v in query.items():\n v = request.args.get(v)\n if v is not None:\n v = check_num(v)\n if v is None:\n return\n dic.update({k:v})\n return dic\n\n\ndef handle_sort():\n sort = request.args.get('sort')\n sort_type = {\n \"new\": [(\"pub_date\", -1)],\n \"popular\": [(\"_id\", 1)]\n }\n return sort_type.get(sort) if sort is not None else sort_type['new']\n\n\n@app.route('/api/dnn/actresses')\ndef actresses():\n co = db[CO_ACTRESS]\n skip, page_size = handle_args() \n actresses = co.find({},{\"_id\": 0}).skip(skip).limit(page_size)\n count = co.count()\n return jsonify({\"count\": count, \"actresses\": list(actresses)})\n\n\n@app.route('/api/dnn/actress/')\ndef actress(id):\n if check_num(id) is None:\n return jsonify(ERROR_NO_DATA)\n co = db[CO_ACTRESS]\n actress = co.find({\"act_id\":id},{\"_id\": 0})\n count = co.count({\"act_id\":id})\n return jsonify({\"count\": count, \"actress\": list(actress)})\n\n\n@app.route('/api/dnn/products')\ndef products():\n query = {\n \"actress.id\": \"actress\",\n \"series.id\": \"series\",\n \"genre.id\": \"genre\"\n }\n query = handle_query(query)\n if query is None:\n return jsonify(ERROR_NO_DATA)\n co = db[CO_PRODUCT]\n sort = handle_sort()\n skip, page_size = handle_args() \n products = co.find(query,{\"_id\":0}).sort(sort).skip(skip).limit(page_size)\n count = co.count(query)\n return jsonify({\"count\": count, \"products\": list(products),})\n\n\n@app.route('/api/dnn/product/')\ndef product(id):\n if check_num(id) is None:\n return jsonify(ERROR_NO_DATA)\n co = db[CO_PRODUCT]\n product = co.find({\"dvd_id\":id.upper()},{\"_id\": 0})\n count = co.count({\"dvd_id\":id.upper()})\n return jsonify({\"count\": count, \"product\": list(product)})\n\n\n@app.route('/api/dnn/genres')\ndef genres():\n co = db[CO_GENRE]\n skip, page_size = handle_args()\n query = {\n \"cate_l\": \"cate_l\",\n \"cate_m\": \"cate_m\",\n \"name\": \"name\"\n }\n query = handle_query(query)\n genres = co.find(query,{\"_id\": 0}).skip(skip).limit(page_size)\n count = co.count(query)\n return jsonify({\"count\": count, \"genres\": list(genres)})\n\n\n@app.route('/api/dnn/genre/')\ndef genre(id):\n if check_num(id) is None:\n return jsonify(ERROR_NO_DATA)\n co = db[CO_GENRE]\n genre = co.find({\"genre_id\": id},{\"_id\": 0})\n count = co.count({\"genre_id\": id})\n return jsonify({\"count\": count, \"actress\": list(genre)})\n\n\nif __name__ == '__main__':\n app.run(**WEBSERVER)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"380673008","text":"from sqlalchemy.exc import IntegrityError\n\nfrom unit_tests.base_test_cases import BaseTestCase\nfrom unit_tests.mock_data import (valid_category_data, create_mock_category, valid_product_data, create_mock_product)\n\nfrom app.catalogue.models import Category, Product\nfrom app import db\n\n\nclass TestCategoryModel(BaseTestCase):\n def test_category_saves_data(self):\n category = create_mock_category(**valid_category_data())\n\n self.assertEqual(Category.query.count(), 1)\n\n def test_category_name_is_unique(self):\n category_data = valid_category_data()\n category_data2 = valid_category_data()\n category_data2['name'] = category_data['name']\n\n category1 = create_mock_category(**category_data)\n\n with self.assertRaises(IntegrityError):\n category2 = create_mock_category(**category_data2)\n\n\nclass TestProductModel(BaseTestCase):\n def test_product_saves_data(self):\n product = create_mock_product()\n\n self.assertTrue(product.id is not None)\n self.assertFalse(product.disable_purchases)\n self.assertFalse(product.hide_from_display)\n self.assertTrue(product.track_stock)\n self.assertTrue(product.out_of_stock_purchase)\n\n self.assertEqual(product.categories.count(), 0)\n\n self.assertEqual(Product.query.count(), 1)\n\n def test_product_name_is_unique(self):\n product = create_mock_product()\n\n with self.assertRaises(IntegrityError):\n create_mock_product(name=product.name)\n\n def test_product_tag_is_unique(self):\n product = create_mock_product()\n\n with self.assertRaises(IntegrityError):\n create_mock_product(tag=product.tag)\n\n def test_name_is_not_nullable(self):\n product_data = valid_product_data()\n del product_data['name']\n\n product = Product(**product_data)\n db.session.add(product)\n with self.assertRaises(IntegrityError):\n db.session.commit()\n\n def test_tag_is_not_nullable(self):\n product_data = valid_product_data()\n del product_data['tag']\n\n product = Product(**product_data)\n db.session.add(product)\n with self.assertRaises(IntegrityError):\n db.session.commit()\n\n def test_associated_product_categories(self):\n category1 = create_mock_category()\n category2 = create_mock_category()\n\n product = create_mock_product(categories=[category1, category2])\n\n self.assertEqual(product.categories.count(), 2)\n self.assertEqual(category1.products.all(), [product])\n self.assertEqual(category2.products.all(), [product])\n","sub_path":"unit_tests/catalogue/test_catalogue_models.py","file_name":"test_catalogue_models.py","file_ext":"py","file_size_in_byte":2631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"313285522","text":"import os.path\n\nenv = Environment(CXXFLAGS='-std=c++11', CCFLAGS=['-g', '-Wall', '-Werror', '-Wextra'])\nabwehrkraft_sources = map(lambda x: 'src/' + x, ['abwehrkraft.cpp'])\nopencvlibs = [\n\t'opencv_calib3d', 'opencv_contrib', 'opencv_core', 'opencv_features2d',\n\t'opencv_flann', 'opencv_gpu', 'opencv_highgui', 'opencv_imgproc',\n\t'opencv_legacy', 'opencv_ml', 'opencv_nonfree', 'opencv_objdetect',\n\t'opencv_ocl', 'opencv_photo', 'opencv_stitching', 'opencv_superres',\n\t'opencv_ts', 'opencv_video', 'opencv_videostab', 'tbb',\n\t'pthread', 'm', 'dl',\n]\nimagedir = os.path.join(os.path.abspath('.'), \"images\")\nenv.Program('bin/abwehrkraft', abwehrkraft_sources, LIBS=['boost_system'] + opencvlibs, CPPDEFINES=[r'IMAGE_DIRECTORY=\\\"' + imagedir + r'\\\"'])\n","sub_path":"SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"494460357","text":"import PySimpleGUI as sg\nfrom PySimpleGUI import ThisRow\nfrom bot import KatiebBot\nfrom tools import get_instance_number, update_instance_number\nimport os\nfrom pathlib import Path\nimport sys\n\nif getattr(sys, \"frozen\", False):\n location = sys._MEIPASS\n ico = os.path.join(location, \"ScrapyBoyLogo.ico\") \nelse:\n location = os.path.abspath(\".\")\n ico = Path(os.path.join(os.path.dirname(__file__), \"assets\\\\ScrapyBoyLogo.ico\"))\n\nsg.ChangeLookAndFeel('Topanga')\nsg.SetOptions(icon=ico,\n button_color=('#FFFFFF','#00CA51'),\n margins=(30,30),\n border_width=5,\n element_padding=(10,5))\nlayout = [\n [sg.Text('Que queres que haga?', font=('Arial', 12))],\n [sg.Radio('Extraer y escribir', 'orden', pad=((10,10),(20,20))), sg.Radio('Dividir archivos pdf', 'orden')],\n [sg.Submit(button_text='Iniciar',button_color=('#FFFFFF','#00CA51'), font='Arial', key='bt1')] \n ] \n#, icon=ico\nwindow = sg.Window('Katieb', use_default_focus=False).Layout(layout)\n# get the instance number from registry\ninstance_num = get_instance_number()\nupdate_instance_number(instance_num)\n# instaciar bot\nkatieb = KatiebBot('log_test', instance_num)\n# event loop\nwhile True:\n event, values = window.Read()\n if event is None: #close\n break\n # unpacking option\n extract_write_opt = values[0] # boolean\n split_pdf_opt = values[1] # boolean \n # button press\n if event == 'bt1':\n # if the user dont choose option\n if (not extract_write_opt and not split_pdf_opt):\n sg.Popup('Elegi una tarea')\n # if choose the extract option\n if extract_write_opt:\n folder = sg.PopupGetFolder('En que carpeta escaneo por pdfs para extraer datos?')\n if folder == None:\n sg.PopupError('No me diste ninguna carpeta para escanear', auto_close=2)\n continue\n answer = sg.PopupYesNo('Usar tabla preexistente? sino, voy a crear una tabla por vos.')\n if answer == None:\n sg.PopupError('No respondiste mi pregunta', auto_close=2)\n continue\n elif answer == 'Yes':\n tabla = sg.PopupGetFile('Cual es la tabla en donde escribo?')\n if not tabla.endswith('.xlsx'):\n sg.PopupError('Ese archivo no es excel')\n continue\n # scan files first\n sg.PopupAutoClose('Comenzando Scaneo', auto_close_duration=2)\n folder = Path(folder)\n pdf_path_list, status_error_scan, happen = katieb.scan_dir_down(folder)\n if status_error_scan:\n sg.PopupError('Ocurrio el siguiente error scaneando ' + happen, auto_close_duration=3)\n continue\n # scan report\n pdf_file_list_print = [os.path.split(i)[1] for i in pdf_path_list]\n sg.PopupAutoClose(pdf_file_list_print, title='Mira los que encontre', auto_close_duration=2)\n # extract data second\n data, status_error_extraction, happen = katieb.extract_from_pdf(pdf_file_list=pdf_path_list)\n if status_error_extraction:\n sg.PopupError('Ocurrio un error extrayendo '+ happen, auto_close_duration=3)\n continue\n # rename files third\n status_error_rename, happen = katieb.rename_files(data, pathToFile_list=pdf_path_list)\n if status_error_rename:\n sg.PopupError('Ocurrio el siguiente error renombrando ' + happen, auto_close_duration=3)\n continue\n # write forth\n status_error_escritura, happen = katieb.write_to_table(data, file_name=tabla)\n if status_error_escritura:\n sg.PopupError('Ocurrio el siguiente error escribiendo '+ happen, auto_close_duration=3)\n continue\n sg.Popup('Trabajo hecho jefe!')\n \n elif answer == 'No':\n # elif answer is No\n sg.PopupAutoClose('Comenzando Scaneo', auto_close_duration=2)\n # scan folders search pdfs \n pdf_path_list, status_error_scan, happen = katieb.scan_dir_down(folder)\n if status_error_scan:\n sg.PopupError('Ocurrio un error scaneando: ' + happen, auto_close_duration=3)\n continue\n # scan report\n pdf_file_list_print = [os.path.split(i)[1] for i in pdf_path_list]\n sg.PopupAutoClose(pdf_file_list_print, title='Mira los que encontre', auto_close_duration=3)\n # extract data\n data, status_error_extraction, happen = katieb.extract_from_pdf(pdf_file_list=pdf_path_list)\n if status_error_extraction:\n sg.PopupError('Ocurrio un error extrayendo: '+ happen, auto_close_duration=3)\n continue\n # rename files\n status_error_rename, happen = katieb.rename_files(data, pathToFile_list=pdf_path_list)\n if status_error_rename:\n sg.PopupError('Ocurrio un error renombrando: ' + happen, auto_close_duration=3)\n continue\n # writing files \n status_error_escritura, happen = katieb.write_to_table(data)\n if status_error_escritura:\n sg.PopupError('Ocurrio el siguiente error escribiendo: '+ happen, auto_close_duration=3)\n continue\n sg.Popup('Trabajo hecbo jefe!') \n \n elif split_pdf_opt:\n custom_layout = [[sg.Text('Queres escanear una carpeta por pdfs? o queres dividir un unico archivo?')],\n [sg.Text(' ')],\n [sg.Button('Escanear carpeta'), sg.Button('Dividir un unico archivo')]]\n custom_popup = sg.Window('Que hago?').Layout(custom_layout)\n while True: \n event2, val2 = custom_popup.read()\n # print(event2, val2)\n if event2 == None:\n break\n if event2 == 'Escanear carpeta':\n custom_popup.Close()\n folder = sg.PopupGetFolder('En que carpeta escaneo por pdfs para dividir?')\n if folder == None:\n sg.PopupError('No me diste ninguna carpeta para escanear')\n break\n sg.PopupAutoClose('Comenzando Scaneo', auto_close_duration=2)\n pdf_path_list, status_error_scan, happen = katieb.scan_dir_down(folder)\n if status_error_scan:\n sg.PopupError('Ocurrio el siguiente error escaneando '+ happen, auto_close_duration=3)\n break\n if len(pdf_path_list) == 0:\n sg.Popup('No encontre ningun pdf jefe')\n break\n # scan report\n pdf_file_list_print = [os.path.split(i)[1] for i in pdf_path_list]\n sg.PopupAutoClose(pdf_file_list_print, title='Mira los que encontre', auto_close_duration=2)\n folder_destino = sg.PopupGetFolder('En que carpeta dejo los pdfs divididos?')\n if folder_destino == None:\n sg.Popup('No me diste ninguna carpeta para dejar los archivos, voy a dejarlos en la ubicacion en la que estoy.')\n status_error_split, happen = katieb.split_pdf(pdf_file_list=pdf_path_list, folder_destino=folder_destino) \n if status_error_split:\n sg.PopupError('Ocurrio el siguiente error diviendo ' + happen, auto_close_duration=3)\n break\n sg.Popup('Trabajo hecho jefe!')\n elif event2 == 'Dividir un unico archivo':\n custom_popup.Close()\n archivo_pdf = sg.PopupGetFile('Cual es el archivo pdf que tengo que dividir?')\n if archivo_pdf == None:\n sg.PopupError('No me diste ningun archivo')\n break\n if not archivo_pdf.endswith('.pdf'):\n sg.PopupError('Ese archivo no es pdf')\n break \n folder_destino = sg.PopupGetFolder('En que carpeta dejo los pdfs divididos?')\n if folder_destino == None:\n sg.Popup('No me diste ninguna carpeta para dejar los archivos, voy a dejarlos en la ubicacion en la que estoy.') \n status_error_split, happen = katieb.split_pdf(pdf_file=archivo_pdf, folder_destino=folder_destino) \n if status_error_split:\n sg.PopupError('Ocurrio el siguiente error dividiendo ' + happen, auto_close_duration=3)\n break\n sg.Popup('Trabajo hecho jefe!')\n custom_popup.close() \nwindow.close()\n","sub_path":"Katieb.py","file_name":"Katieb.py","file_ext":"py","file_size_in_byte":9136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"102290200","text":"from urllib.request import urlopen\nfrom urllib.parse import urlparse\nfrom bs4 import BeautifulSoup\nimport random\nimport ssl\nimport re\n\n\ndef getInternalLinks(bsObj, includeUrl):\n internalLinks = []\n print(\"1 getInternalLinks=\" + includeUrl)\n include = urlparse(includeUrl).scheme + \"://\" + urlparse(includeUrl).netloc\n for link in bsObj.findAll('a', {'href': re.compile(\"^(/|\" + include + \").*\")}):\n # print(link)\n if link.attrs['href'] is not None:\n if link.attrs['href'] not in internalLinks:\n if link.attrs['href'].startswith('/'):\n internalLinks.append(include + link.attrs['href'])\n else:\n internalLinks.append(link['href'])\n\n return internalLinks\n\n\ndef getExternalLinks(bsObj, excludeUrl):\n externalLinks = []\n print(\"getExternalLinks,excude=\" + excludeUrl)\n for link in bsObj.findAll('a', {'href': re.compile(\"^(http|www|https)((?!\" + excludeUrl + \").)*$\")}):\n print(\"getExternalLinks=%s\" % link)\n if link.attrs['href'] is not None:\n if link.attrs['href'] not in externalLinks:\n externalLinks.append(link.attrs['href'])\n return externalLinks\n\n\ndef getRandomExternalLink(url):\n if url is None:\n return None\n context = ssl._create_unverified_context()\n html = urlopen(url, context=context)\n obj = BeautifulSoup(html)\n\n externalLinks = getExternalLinks(obj, urlparse(url).netloc)\n print(\"外链数量: %d\" % len(externalLinks))\n if len(externalLinks) == 0:\n internalLinks = getInternalLinks(obj, url)\n print(\"内链数量: %d\" % len(internalLinks))\n if len(internalLinks) == 0:\n return None\n else:\n return getRandomExternalLink(internalLinks[random.randint(0, len(internalLinks) - 1)])\n else:\n return externalLinks[random.randint(0, len(externalLinks) - 1)]\n\n\ndef start(url):\n newUrl = getRandomExternalLink(url)\n print('随机外链= %s' % newUrl)\n if newUrl is not None:\n start(newUrl)\n else:\n print(\"结束流程\")\n\n\nstart(\"https://oreilly.com\")\n","sub_path":"projects/LearningEveryDay/2018.5.18/WebCrawler.py","file_name":"WebCrawler.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"498171821","text":"import pyglet, pymunk\nfrom pyglet.window import key\n\n__GAME_WINDOW_X_SIZE__ = 1280\n__GAME_WINDOW_Y_SIZE__ = 720\n\n\nclass Player(pyglet.sprite.Sprite):\n def __init__(self, user_id, player_id, name, npc, label, space, *args, **kwargs):\n super(Player, self).__init__(*args, **kwargs)\n\n self.user_id = user_id\n self.player_id = player_id\n self.name = name\n self.npc = npc\n self.label = label\n\n self.jumping = False\n self.velocity_x, self.velocity_y = 400.0, -30.0\n \n self.mass = 0.01\n self.body = pymunk.Body(self.mass, 10)\n self.body.position = (50, 50)\n self.body.player = self\n shape = [(-15, -15), (15, -15), (15, 15), (-15, 15), (-15, -15)]\n self.shape = pymunk.Poly(self.body, shape)\n self.body.elasticity = 0\n self.shape.elasticity = 0\n self.shape.friction = 100000\n print(\"Constraints\", self.body.constraints)\n\n space.add(self.body, self.shape)\n\n self.key_handler = key.KeyStateHandler()\n\n def jump(self, dt):\n if self.velocity_y > 0:\n self.y += (0.5 * self.mass * (self.velocity_y ** 2)) * dt\n else:\n self.y += -(0.5 * self.mass * (self.velocity_y ** 2)) * dt\n\n self.velocity_y -= 1.95\n\n def update(self, x=15, y=15):\n if self.npc:\n self.x = x\n self.y = y\n\n self.body.position = [self.x-15, self.y-15]\n return\n else:\n move_vect = [0, 0]\n if self.key_handler[key.A]:\n move_vect[0] -= 1\n if self.key_handler[key.D]:\n move_vect[0] += 1\n if self.key_handler[key.SPACE] and not self.jumping and -400 < self.body.velocity[1] < 400: # jump\n self.body.apply_impulse_at_world_point((0, 12), self.body.position)\n self.jumping = True\n\n if __GAME_WINDOW_X_SIZE__ + 100 < self.x < -100 or self.y < 0:\n self.x = 15\n self.y = 15\n self.body.position = [self.x-15, self.y-15]\n \n if -300 < self.body.velocity[0] < 300:\n self.body.apply_impulse_at_world_point(move_vect, self.body.position)\n\n def render_simulation_fields(self):\n self.x = self.body.position[0]\n self.y = self.body.position[1]\n\n def check_bounds(self):\n min_x = self.image.width // 2\n min_y = self.image.height // 2\n max_x = __GAME_WINDOW_X_SIZE__ - self.image.width // 2\n max_y = __GAME_WINDOW_Y_SIZE__ - self.image.height // 2\n\n if self.x <= min_x:\n self.x = min_x\n if self.x >= max_x:\n self.x = max_x\n if self.y <= min_y:\n self.y = min_y\n self.jumping = False\n self.velocity_y = -30.0\n if self.y >= max_y:\n self.y = max_y\n\n def is_colliding_with(self, obj):\n return (-15 < self.x - obj.x < obj.width + 15 and\n -15 < self.y - obj.y < obj.height + 15)\n\n def detect_collision_with(self, obj):\n if self.is_colliding_with(obj):\n if self.velocity_y > 0:\n self.y = obj.y - 15\n self.velocity_y = -10.0\n if self.velocity_y < 0 and self.y-25 > obj.y:\n self.y = obj.y + obj.height + 15\n self.jumping = False\n self.velocity_y = -30.0\n if self.is_colliding_with(obj):\n if self.velocity_x > 0:\n self.x = obj.x - 15\n if self.velocity_x < 0:\n self.x = obj.x + obj.width + 15\n\n def reset(self):\n self.x = 15\n self.y = 15\n self.velocity_x = 400.0\n self.velocity_y = -30.0\n self.jumping = False\n \n def __repr__(self):\n return str(self)\n \n def __str__(self):\n return \"player_id: \" + str(self.player_id) + \" user_id: \" + str(self.user_id) + \\\n \" name: \" + str(self.name) + \" x: \" + str(self.x) + \" y: \" + str(self.y)\n","sub_path":"snider_glider/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":4020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"326503912","text":"# -*- coding:utf-8 -*-\nimport os\n\nbase = os.path.abspath(os.path.dirname(__name__))\n\n\n# 为了批量创建文件\ndef mk_py(pre, n):\n for i in range(1, int(n)+1):\n file_name = base + os.sep + pre + str(i) + \".py\"\n f = open(file_name, 'a')\n f.write('# -*- coding:utf-8 -*-')\n f.close()\n\n\nif __name__ == \"__main__\":\n pre = raw_input(\"请输入要生成的文件前缀: \")\n n = raw_input(\"请输入要生成的文件数量: \")\n mk_py(pre, n)\n","sub_path":"Practice0.py","file_name":"Practice0.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"397156885","text":"## Soru - 1\nfrom typing import List\n\nl = [[1,'a',['cat'],2],[[[3]],'dog'],4,5]\nflat_list2 = []\n\ndef lookInside(l): # Takes the list type element\n for x in l: # For each sub-element of it\n if type(x) is not list: # If the sub-element is not list, \n flat_list2.append(x) # Then add it to flat_list\n else: \n lookInside(x) # Else, look inside of it again\n\ndef makeFlat(l): # Getting the list \n for e in l: # Checking the elements of the list\n if type(e) is list: # If element's type is list then\n lookInside(e) # send that element to lookInside function \n else:\n flat_list2.append(e) # Else, (if it is not list) append it to our new flat_list\n\nmakeFlat(l) # Function call, the complex list has been given to function\nprint(flat_list2) # Printing the flatten list\n\n## Soru - 2\n\nlist2 = [[1, 2], [3, 4], [5, 6, 7]]\nlist1 = list2[::-1]\n\nprint(list1)\n","sub_path":"patika_proje.py","file_name":"patika_proje.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"297554126","text":"import urllib.request\r\nimport logging\r\nimport logging.handlers\r\n\r\n\r\n# Define Variables\r\nRW_IPBL_url = \"https://ransomwaretracker.abuse.ch/downloads/RW_IPBL.txt\"\r\nRW_DOMBL_url = \"https://ransomwaretracker.abuse.ch/downloads/RW_DOMBL.txt\"\r\nRW_URLBL_url = \"https://ransomwaretracker.abuse.ch/downloads/RW_URLBL.txt\"\r\n\r\n\r\n# Set Syslog information\r\nshooter = logging.getLogger('SysLogShooter')\r\nshooter.setLevel(logging.INFO)\r\nsyslogserver = logging.handlers.SysLogHandler(address=('127.0.0.1', 515))\r\nshooter.addHandler(syslogserver)\r\n\r\n\r\n# Download the file from `url` and save it locally under `file_name`:\r\nurllib.request.urlretrieve(RW_IPBL_url, \"RW_IPBL.txt\")\r\n\r\n\r\n# Example: We will pass values from a List\r\n\r\nf = open('RW_IPBL.txt','r',encoding=\"utf8\")\r\nfor line in f.readlines():\r\n print(line)\r\n shooter.info('Threat Intelligence - Abuse.ch - Ransomeware Tracker,IPv4,'+line)\r\nf.close()\r\n","sub_path":"ThreatIntel_Abuse_ch.py","file_name":"ThreatIntel_Abuse_ch.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"228065243","text":"from lino.utils.pythontest import TestCase\n\n\nclass DocTest(TestCase):\n\n def test_files(self):\n\n self.check_doctest('index.rst')\n from django import VERSION\n self.assertEqual(VERSION[0], 1)\n if VERSION[1] == 6:\n self.check_doctest('django16.rst')\n elif VERSION[1] > 6:\n self.check_doctest('django17.rst')\n else:\n self.fail(\"Unsupported Django version {0}\".format(VERSION))\n\n","sub_path":"docs/tested/diamond2/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"236261180","text":"import pwn\nimport sys\nif '--remote' in sys.argv:\n p = pwn.remote(\"chall.pwnable.tw\", 10001)\nelse:\n p = pwn.process(\"./orw\")\noutput = p.recv(len(\"Give my your shellcode:\"))\n\nshellcode = open(\"shellcode.bin\", 'rb').read()\nassert len(shellcode) < 200\np.send(shellcode)\noutput = p.recvall()\nprint(output)\n","sub_path":"pwnable/orw/exploit.py","file_name":"exploit.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"620100323","text":"import os\nfrom collections import Iterable\nfrom typing import Union, List\n\nimport numpy as np\nimport pandas as pd\n\nfrom tde.tde import calc_tri_displacements\nfrom matplotlib import pyplot as plt\nfrom pyproj import Transformer\nimport meshio\nfrom shapely.ops import linemerge, unary_union\nfrom shapely.geometry import LineString, MultiPolygon\n\nfrom rsqsim_api.io.read_utils import read_dxf, read_stl\nfrom rsqsim_api.io.tsurf import tsurf\nfrom rsqsim_api.fault.patch import RsqSimTriangularPatch, RsqSimGenericPatch\n\n\ntransformer_utm2nztm = Transformer.from_crs(32759, 2193, always_xy=True)\n\n\nclass DisplacementArray:\n def __init__(self, x_array: np.ndarray, y_array: np.ndarray, z_array: np.ndarray = None,\n e_array: np.ndarray = None, n_array: np.ndarray = None, v_array: np.ndarray = None):\n assert x_array.shape == y_array.shape, \"X and Y arrays should be the same size\"\n assert x_array.ndim == 1, \"Expecting 1D arrays\"\n assert not all([a is None for a in [e_array, n_array, v_array]]), \"Read in at least one set of displacements\"\n\n self.x, self.y = x_array, y_array\n if z_array is None:\n self.z = np.zeros(self.x.shape)\n else:\n assert isinstance(z_array, np.ndarray)\n assert z_array.shape == self.x.shape\n self.z = z_array\n\n if e_array is not None:\n assert isinstance(e_array, np.ndarray)\n assert e_array.shape == self.x.shape\n self.e = e_array\n\n if n_array is not None:\n assert isinstance(n_array, np.ndarray)\n assert n_array.shape == self.x.shape\n self.n = n_array\n\n if v_array is not None:\n assert isinstance(v_array, np.ndarray)\n assert v_array.shape == self.x.shape\n self.v = v_array\n\n\nclass RsqSimSegment:\n def __init__(self, segment_number: int, patch_type: str = \"triangle\", fault_name: str = None):\n \"\"\"\n\n :param segment_number:\n :param patch_type:\n :param fault_name:\n \"\"\"\n self._name = None\n self._patch_numbers = None\n self._patch_outlines = None\n self._patch_vertices = None\n self._vertices = None\n self._triangles = None\n self._edge_lines = None\n self._segment_number = segment_number\n self._patch_type = None\n self._adjacency_map = None\n self._laplacian = None\n self._boundary = None\n\n self.patch_type = patch_type\n self.name = fault_name\n self.ss_gf, self.ds_gf = (None,) * 2\n\n @property\n def name(self):\n return self._name\n\n @name.setter\n def name(self, fault_name: str):\n if fault_name is None:\n self._name = None\n else:\n assert isinstance(fault_name, str)\n assert \" \" not in fault_name, \"No spaces in fault name, please...\"\n self._name = fault_name.lower()\n\n @property\n def patch_numbers(self):\n return self._patch_numbers\n\n @patch_numbers.setter\n def patch_numbers(self, numbers: Union[list, tuple, np.ndarray]):\n number_array = np.array(numbers)\n assert number_array.dtype == \"int\"\n if self.patch_outlines is not None:\n assert len(number_array) == len(self.patch_outlines)\n self._patch_numbers = number_array\n\n @property\n def segment_number(self):\n return self._segment_number\n\n @property\n def patch_type(self):\n return self._patch_type\n\n @patch_type.setter\n def patch_type(self, patch_type: str):\n assert isinstance(patch_type, str)\n patch_lower = patch_type.lower()\n assert patch_lower in (\"triangle\", \"rectangle\", \"tri\", \"rect\"), \"Expecting 'triangle' or 'rectangle'\"\n if patch_lower in (\"triangle\", \"tri\"):\n self._patch_type = \"triangle\"\n else:\n self._patch_type = \"rectangle\"\n\n @property\n def patch_outlines(self):\n return self._patch_outlines\n\n @property\n def patch_vertices(self):\n return self._patch_vertices\n\n @patch_outlines.setter\n def patch_outlines(self, patches: List):\n if self.patch_type == \"triangle\":\n assert all([isinstance(patch, RsqSimTriangularPatch) for patch in patches])\n elif self.patch_type == \"rectangle\":\n assert all([isinstance(patch, RsqSimGenericPatch) for patch in patches])\n else:\n raise ValueError(\"Set patch type (triangle or rectangle) for fault!\")\n\n self._patch_outlines = patches\n self._patch_vertices = [patch.vertices for patch in patches]\n\n @property\n def vertices(self):\n if self._vertices is None:\n self.get_unique_vertices()\n return self._vertices\n\n @property\n def bounds(self):\n \"\"\"\n Square box in XY plane containing all vertices\n \"\"\"\n x0 = min(self.vertices[:, 0])\n y0 = min(self.vertices[:, 1])\n x1 = max(self.vertices[:, 0])\n y1 = max(self.vertices[:, 1])\n bounds = np.array([x0, y0, x1, y1])\n return bounds\n\n @property\n def boundary(self):\n return self._boundary\n\n @boundary.setter\n def boundary(self, boundary_array: np.ndarray):\n if boundary_array is not None:\n assert isinstance(boundary_array, np.ndarray)\n assert boundary_array.ndim == 2 # 2D array\n assert boundary_array.shape[1] == 3 # Three columns\n\n self._boundary = boundary_array\n\n @property\n def quaternion(self):\n return None\n\n\n def get_unique_vertices(self):\n if self.patch_vertices is None:\n raise ValueError(\"Read in triangles first!\")\n all_vertices = np.reshape(self.patch_vertices, (3 * len(self.patch_vertices), 3))\n unique_vertices = np.unique(all_vertices, axis=0)\n self._vertices = unique_vertices\n\n @property\n def triangles(self):\n if self._triangles is None:\n self.generate_triangles()\n return self._triangles\n\n @property\n def edge_lines(self):\n if self._edge_lines is None:\n self.generate_triangles()\n return self._edge_lines\n\n def generate_triangles(self):\n assert self.patch_outlines is not None, \"Load patches first!\"\n all_vertices = [patch.vertices for patch in self.patch_outlines]\n unique_vertices = np.unique(np.vstack(all_vertices), axis=0)\n self._vertices = unique_vertices\n\n triangle_ls = []\n line_ls = []\n for triangle in all_vertices:\n vertex_numbers = []\n for vertex in triangle:\n index = np.where((unique_vertices == vertex).all(axis=1))[0][0]\n vertex_numbers.append(index)\n triangle_ls.append(vertex_numbers)\n line_ls += [[vertex_numbers[0], vertex_numbers[1]],\n [vertex_numbers[0], vertex_numbers[2]],\n [vertex_numbers[1], vertex_numbers[2]]]\n self._triangles = np.array(triangle_ls)\n self._edge_lines = np.array(line_ls)\n\n def find_triangles_from_vertex_index(self, vertex_index: int):\n assert isinstance(vertex_index, int)\n assert 0 <= vertex_index < len(self.vertices)\n triangle_index_list = []\n for i, triangle in enumerate(self.triangles):\n if vertex_index in triangle:\n triangle_index_list.append(i)\n\n print(triangle_index_list)\n return triangle_index_list\n\n @classmethod\n def from_triangles(cls, triangles: Union[np.ndarray, list, tuple], segment_number: int = 0,\n patch_numbers: Union[list, tuple, set, np.ndarray] = None, fault_name: str = None,\n strike_slip: Union[int, float] = None, dip_slip: Union[int, float] = None,\n rake: Union[int, float] = None):\n \"\"\"\n Create a segment from triangle vertices and (if appropriate) populate it with strike-slip/dip-slip values\n :param segment_number:\n :param triangles:\n :param patch_numbers:\n :param fault_name:\n :param strike_slip:\n :param dip_slip:\n :return:\n \"\"\"\n # Test shape of input array is appropriate\n triangle_array = np.array(triangles)\n assert triangle_array.shape[1] == 9, \"Expecting 3d coordinates of 3 vertices each\"\n if patch_numbers is None:\n patch_numbers = np.arange(len(triangle_array))\n else:\n assert len(patch_numbers) == triangle_array.shape[0], \"Need one patch for each triangle\"\n\n # Create empty segment object\n fault = cls(patch_type=\"triangle\", segment_number=segment_number, fault_name=fault_name)\n\n triangle_ls = []\n\n # Populate segment object\n for patch_num, triangle in zip(patch_numbers, triangle_array):\n triangle3 = triangle.reshape(3, 3)\n patch = RsqSimTriangularPatch(fault, vertices=triangle3, patch_number=patch_num, strike_slip=strike_slip,\n dip_slip=dip_slip, rake=rake)\n triangle_ls.append(patch)\n\n fault.patch_outlines = triangle_ls\n fault.patch_numbers = np.array([patch.patch_number for patch in triangle_ls])\n fault.patch_dic = {p_num: patch for p_num, patch in zip(fault.patch_numbers, fault.patch_outlines)}\n\n return fault\n\n @classmethod\n def from_tsurface(cls, tsurface_file: str, segment_number: int = 0,\n patch_numbers: Union[list, tuple, set, np.ndarray] = None, fault_name: str = None,\n strike_slip: Union[int, float] = None, dip_slip: Union[int, float] = None):\n assert os.path.exists(tsurface_file)\n tsurface_mesh = tsurf(tsurface_file)\n\n fault = cls.from_triangles(tsurface_mesh.triangles, segment_number=segment_number, patch_numbers=patch_numbers,\n fault_name=fault_name, strike_slip=strike_slip, dip_slip=dip_slip)\n return fault\n\n @classmethod\n def from_dxf(cls, dxf_file: str, segment_number: int = 0,\n patch_numbers: Union[list, tuple, set, np.ndarray] = None, fault_name: str = None,\n strike_slip: Union[int, float] = None, dip_slip: Union[int, float] = None):\n triangles, boundary = read_dxf(dxf_file)\n segment = cls.from_triangles(triangles, segment_number=segment_number, patch_numbers=patch_numbers,\n fault_name=fault_name, strike_slip=strike_slip, dip_slip=dip_slip)\n segment.boundary = boundary\n\n return segment\n\n @classmethod\n def from_pandas(cls, dataframe: pd.DataFrame, segment_number: int,\n patch_numbers: Union[list, tuple, set, np.ndarray], fault_name: str = None,\n strike_slip: Union[int, float] = None, dip_slip: Union[int, float] = None, read_rake: bool = True,\n normalize_slip: Union[float, int] = 1, transform_from_utm: bool = False):\n\n triangles = dataframe.iloc[:, :9].to_numpy()\n if transform_from_utm:\n reshaped_array = triangles.reshape((len(triangles) * 3), 3)\n transformed_array = transformer_utm2nztm.transform(reshaped_array[:, 0], reshaped_array[:, 1],\n reshaped_array[:, 2])\n reordered_array = np.vstack(transformed_array).T\n triangles_nztm = reordered_array.reshape((len(triangles), 9))\n\n else:\n triangles_nztm = triangles\n\n # Create empty segment object\n fault = cls(patch_type=\"triangle\", segment_number=segment_number, fault_name=fault_name)\n\n triangle_ls = []\n\n if read_rake:\n assert \"rake\" in dataframe.columns, \"Cannot read rake\"\n assert all([a is None for a in (dip_slip, strike_slip)]), \"Either read_rake or specify ds and ss, not both!\"\n rake = dataframe.rake.to_numpy()\n rake_dic = {r: (np.cos(np.radians(r)) * normalize_slip, np.sin(np.radians(r)) * normalize_slip) for r in np.unique(rake)}\n assert len(rake) == len(triangles_nztm)\n else:\n rake = np.zeros((len(triangles_nztm),))\n\n # Populate segment object\n for i, (patch_num, triangle) in enumerate(zip(patch_numbers, triangles_nztm)):\n triangle3 = triangle.reshape(3, 3)\n if read_rake:\n strike_slip = rake_dic[rake[i]][0]\n dip_slip = rake_dic[rake[i]][1]\n patch = RsqSimTriangularPatch(fault, vertices=triangle3, patch_number=patch_num,\n strike_slip=strike_slip,\n dip_slip=dip_slip, rake=rake[i])\n triangle_ls.append(patch)\n\n fault.patch_outlines = triangle_ls\n fault.patch_numbers = patch_numbers\n fault.patch_dic = {p_num: patch for p_num, patch in zip(fault.patch_numbers, fault.patch_outlines)}\n\n return fault\n\n @classmethod\n def from_pickle(cls, dataframe: pd.DataFrame, segment_number: int,\n patch_numbers: Union[list, tuple, set, np.ndarray], fault_name: str = None):\n patches = dataframe.to_numpy()\n\n # Create empty segment object\n fault = cls(patch_type=\"triangle\", segment_number=segment_number, fault_name=fault_name)\n\n triangle_ls = []\n # Populate segment object\n for i, patch_num in enumerate(patch_numbers):\n patch_data = patches[i]\n patch = RsqSimTriangularPatch(fault, vertices=patch_data[0], patch_number=patch_num,\n strike_slip=patch_data[8],\n dip_slip=patch_data[7],\n patch_data=patch_data[1:7])\n triangle_ls.append(patch)\n\n fault.patch_outlines = triangle_ls\n fault.patch_numbers = patch_numbers\n fault.patch_dic = {p_num: patch for p_num, patch in zip(fault.patch_numbers, fault.patch_outlines)}\n\n return fault\n\n @classmethod\n def from_stl(cls, stl_file: str, segment_number: int = 0,\n patch_numbers: Union[list, tuple, set, np.ndarray] = None, fault_name: str = None,\n strike_slip: Union[int, float] = None, dip_slip: Union[int, float] = None):\n\n triangles = read_stl(stl_file)\n return cls.from_triangles(triangles, segment_number=segment_number, patch_numbers=patch_numbers,\n fault_name=fault_name, strike_slip=strike_slip, dip_slip=dip_slip)\n\n\n\n def collect_greens_function(self, sites_x: Union[list, tuple, np.ndarray], sites_y: Union[list, tuple, np.ndarray],\n sites_z: Union[list, tuple, np.ndarray] = None, strike_slip: Union[int, float] = 1,\n dip_slip: Union[int, float] = 1, poisson_ratio: Union[int, float] = 0.25,\n tensional_slip: Union[int, float] = 0):\n \"\"\"\n\n :param sites_x:\n :param sites_y:\n :param sites_z:\n :param strike_slip:\n :param dip_slip:\n :param poisson_ratio:\n :param tensional_slip:\n :return:\n \"\"\"\n x_array = np.array(sites_x)\n y_array = np.array(sites_y)\n if sites_z is None:\n z_array = np.zeros(x_array.shape)\n else:\n z_array = np.array(sites_z)\n\n x_vertices, y_vertices, z_vertices = [[vertices.T[i] for vertices in self.patch_vertices] for i in range(3)]\n\n ds_gf_dic = {}\n ss_gf_dic = {}\n for patch_number, xv, yv, zv in zip(self.patch_numbers, x_vertices, y_vertices, z_vertices):\n ds_gf_dic[patch_number] = calc_tri_displacements(x_array, y_array, z_array, xv, yv, -1. * zv,\n poisson_ratio, 0., tensional_slip, dip_slip)\n ss_gf_dic[patch_number] = calc_tri_displacements(x_array, y_array, z_array, xv, yv, -1. * zv,\n poisson_ratio, strike_slip, tensional_slip, 0.)\n\n self.ds_gf = ds_gf_dic\n self.ss_gf = ss_gf_dic\n\n def gf_design_matrix(self, displacements: DisplacementArray):\n \"\"\"\n Maybe this should be stored on the DisplacementArray object?\n :param displacements:\n :return:\n \"\"\"\n assert isinstance(displacements, DisplacementArray), \"Expecting DisplacementArray object\"\n if any([a is None for a in (self.ds_gf, self.ss_gf)]):\n self.collect_greens_function(displacements.x, displacements.y, displacements.z)\n design_matrix_ls = []\n d_list = []\n w_list = []\n for component, key in zip([displacements.e, displacements.n, displacements.v], [\"x\", \"y\", \"z\"]):\n if component is not None:\n for site in range(len(component)):\n component_ds = [self.ds_gf[i][key][site] for i in self.patch_numbers]\n component_ss = [self.ss_gf[i][key][site] for i in self.patch_numbers]\n component_combined = component_ds + component_ss\n design_matrix_ls.append(component_combined)\n d_list.append(component)\n\n design_matrix_array = np.array(design_matrix_ls)\n d_array = np.hstack([a for a in d_list])\n\n return design_matrix_array, d_array\n\n @property\n def adjacency_map(self):\n if self._adjacency_map is None:\n self.build_adjacency_map()\n return self._adjacency_map\n\n def build_adjacency_map(self):\n \"\"\"\n For each triangle vertex, find the indices of the adjacent triangles.\n This function overwrites that from the parent class TriangularPatches.\n\n :Kwargs:\n * verbose : Speak to me\n\n :Returns:\n * None\n \"\"\"\n\n self._adjacency_map = []\n\n # Cache the vertices and faces arrays\n\n # First find adjacent triangles for all triangles\n # Currently any triangle with a edge, could be a common vertex instead.\n for vertex_numbers in self.triangles:\n adjacent_triangles = []\n for j, triangle in enumerate(self.triangles):\n common_vertices = [a for a in vertex_numbers if a in triangle]\n if len(common_vertices) == 2:\n adjacent_triangles.append(j)\n self._adjacency_map.append(adjacent_triangles)\n\n def build_laplacian_matrix(self):\n\n \"\"\"\n Build a discrete Laplacian smoothing matrix.\n\n :Args:\n * verbose : if True, displays stuff.\n * method : Method to estimate the Laplacian operator\n\n - 'count' : The diagonal is 2-times the number of surrounding nodes. Off diagonals are -2/(number of surrounding nodes) for the surrounding nodes, 0 otherwise.\n - 'distance': Computes the scale-dependent operator based on Desbrun et al 1999. (Mathieu Desbrun, Mark Meyer, Peter Schr\\\"oder, and Alan Barr, 1999. Implicit Fairing of Irregular Meshes using Diffusion and Curvature Flow, Proceedings of SIGGRAPH).\n\n * irregular : Not used, here for consistency purposes\n\n :Returns:\n * Laplacian : 2D array\n \"\"\"\n\n # Build the tent adjacency map\n if self.adjacency_map is None:\n self.build_adjacency_map()\n\n # Get the vertices\n\n # Allocate an array\n laplacian_matrix = np.zeros((len(self.patch_numbers), len(self.patch_numbers)))\n\n # Normalize the distances\n all_distances = []\n for i, (patch, adjacents) in enumerate(zip(self.patch_outlines, self.adjacency_map)):\n patch_centre = patch.centre\n distances = np.array([np.linalg.norm(self.patch_outlines[a].centre - patch_centre) for a in adjacents])\n all_distances.append(distances)\n normalizer = np.max([np.max(d) for d in all_distances])\n\n # Iterate over the vertices\n for i, (adjacents, distances) in enumerate(zip(self.adjacency_map, all_distances)):\n # Distance-based\n distances_normalized = distances / normalizer\n e = np.sum(distances_normalized)\n laplacian_matrix[i, i] = float(len(adjacents)) * 2. / e * np.sum(1. / distances_normalized)\n laplacian_matrix[i, adjacents] = -2. / e * 1. / distances_normalized\n\n self._laplacian = np.hstack((laplacian_matrix, laplacian_matrix))\n\n @property\n def laplacian(self):\n if self._laplacian is None:\n self.build_laplacian_matrix()\n return self._laplacian\n\n def find_top_vertex_indices(self, depth_tolerance: Union[float, int] = 100):\n top_vertex_depth = max(self.vertices[:, -1])\n shallow_indices = np.where(self.vertices[:, -1] >= top_vertex_depth - depth_tolerance)[0]\n return shallow_indices\n\n def find_top_vertices(self, depth_tolerance: Union[float, int] = 100):\n shallow_indices = self.find_top_vertex_indices(depth_tolerance)\n return self.vertices[shallow_indices]\n\n def find_top_edges(self, depth_tolerance: Union[float, int] = 100):\n shallow_indices = self.find_top_vertex_indices(depth_tolerance)\n top_edges = self.edge_lines[np.all(np.isin(self.edge_lines, shallow_indices), axis=1)]\n return top_edges\n\n @property\n def trace(self):\n top_edges = self.find_top_edges()\n line_list = []\n for edge in top_edges:\n v1 = self.vertices[edge[0]]\n v2 = self.vertices[edge[1]]\n line = LineString([v1[:-1], v2[:-1]])\n line_list.append(line)\n return linemerge(line_list)\n\n @property\n def fault_outline(self):\n multip = MultiPolygon(patch.as_polygon() for patch in self.patch_outlines)\n return unary_union(list(multip))\n\n def plot_2d(self, ax: plt.Axes):\n ax.triplot(self.vertices[:, 0], self.vertices[:, 1], self.triangles)\n\n def to_mesh(self):\n return meshio.Mesh(points=self.vertices, cells=[(\"triangle\", self.triangles)])\n\n def to_stl(self, stl_name: str):\n mesh = self.to_mesh()\n mesh.write(stl_name, file_format=\"stl\")\n\n def to_vtk(self, vtk_name: str):\n mesh = self.to_mesh()\n mesh.write(vtk_name, file_format=\"vtk\")\n\n\nclass RsqSimFault:\n \"\"\"\n The idea is to allow a fault to have one or more segments\n \"\"\"\n\n def __init__(self, segments: Union[RsqSimSegment, List[RsqSimSegment]]):\n self._segments = None\n self._vertices = None\n\n if segments is not None:\n self.segments = segments\n\n @property\n def segments(self):\n return self._segments\n\n @segments.setter\n def segments(self, segments: Union[RsqSimSegment, List[RsqSimSegment]]):\n\n if isinstance(segments, RsqSimSegment):\n self._segments = [segments]\n else:\n assert isinstance(segments, Iterable), \"Expected either one segment or a list of segments\"\n assert all([isinstance(segment, RsqSimSegment) for segment in segments]), \"Expected a list of segments\"\n self._segments = list(segments)\n\n\n","sub_path":"src/rsqsim_api/rsqsim_api/fault/segment.py","file_name":"segment.py","file_ext":"py","file_size_in_byte":23153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"370127929","text":"#! python\n# this script will archive everything except format you give in the argument\n# X 2020 Arnold Cytrowski\n\nimport os, zipfile\n\ndef archiveIt():\n abs_directory_path = os.path.abspath('.')\n format = input('Give here format which you want to archive from this folder:\\n')\n zip_new_file = zipfile.ZipFile(f'zipOf{format}.zip', 'w')\n if len(format) <= 3:\n for folder, subfolders, filenames in os.walk('.'):\n for filename in filenames:\n if filename.endswith(f'.{format}'):\n print(f'{filename} has beed added to archive')\n zip_new_file.write(os.path.join(abs_directory_path, filename), filename)\n print('muchas gracias amigo, have a great day')\n\narchiveIt()\n\n","sub_path":"selectiveArchiver.py","file_name":"selectiveArchiver.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"379104754","text":"from flask import Flask, render_template, request,jsonify\nfrom pymongo import MongoClient\n\nfrom scrap import my_scrap\n\nclient = MongoClient('localhost', 27107)\ndb = client.spartadb\n\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef home():\n\n return render_template('index.html')\n\n@app.route('/news')\ndef my_news():\n my_data = my_scrap()\n print(my_data)\n return jsonify(my_data)\n\nif __name__ == \"__main__\":\n app.run('0.0.0.0', 5000,debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"517601442","text":"class Solution:\n # @param version1, a string\n # @param version2, a string\n # @return an integer\n def compareVersion(self, version1, version2):\n v1 = version1.split('.')\n v2 = version2.split('.')\n length = max(len(v1), len(v2))\n for i in range(abs(len(v1)-len(v2))):\n v1.append('0')\n v2.append('0')\n for i in range(length):\n if int(v1[i]) > int(v2[i]):\n return 1\n if int(v1[i]) < int(v2[i]):\n return -1\n return 0\n","sub_path":"compareversionnumbers.py","file_name":"compareversionnumbers.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"298241417","text":"from datetime import datetime\nfrom time import time\nfrom mongoConn import makeDBConn\nfrom log import Log\nimport pymongo\nimport math\n\ndef getSingleDateLogs(day=-1,month=-1,year=-1):\n if year == -1:\n year = datetime.fromtimestamp(time()).year\n if month == -1:\n month = datetime.fromtimestamp(time()).month\n if day == -1:\n day = datetime.fromtimestamp(time()).day\n t1 = datetime(year,month,day).timestamp()\n t2 = datetime(year,month,day,23,59).timestamp()\n query = {\"timestamp\" : {\"$gt\" : t1} , \"timestamp\" : {\"$lt\" : t2}}\n db = makeDBConn()\n return db.st_aquinas.find(query)\n\ndef getAllLogs():\n logs = makeDBConn().st_aquinas.find().sort([(\"timestamp\",pymongo.ASCENDING)])\n response = []\n for l in logs:\n response.append(Log(l['content'],\n l['timestamp'],\n l['tags'],\n l['fixedData']))\n return response\n","sub_path":"src/jsonRetriever.py","file_name":"jsonRetriever.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"108026820","text":"import os\nimport sys\nimport sqlite3\nimport pandas as pd\nsys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))\nfrom utility.static import now\nfrom utility.setting import db_tick\n\n\ncon = sqlite3.connect(db_tick)\ndf_name = pd.read_sql(\"SELECT name FROM sqlite_master WHERE TYPE = 'table'\", con)\ntable_list = list(df_name['name'].values)\nif 'moneytop' in table_list:\n table_list.remove('moneytop')\nif 'codename' in table_list:\n table_list.remove('codename')\n\ncount = len(table_list)\nfor i, code in enumerate(table_list):\n df = pd.read_sql(f\"SELECT * FROM '{code}'\", con)\n df = df.set_index('index')\n if '매도2호가' in df.columns:\n df.rename(columns={\n '매도2호가': '매도호가2', '매도1호가': '매도호가1', '매수1호가': '매수호가1', '매수2호가': '매수호가2',\n '매도2잔량': '매도잔량2', '매도1잔량': '매도잔량1', '매수1잔량': '매수잔량1', '매수2잔량': '매수잔량2'\n }, inplace=True)\n df.to_sql(code, con, if_exists='replace', chunksize=1000)\n print(f'[{now()}] 틱데이터 칼럼명 확인 및 변경 중 ... {i+1}/{count}')\ncon.close()\n","sub_path":"database/updater_20210924.py","file_name":"updater_20210924.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"590253332","text":"\n###### do not change anything in this file! ######\n\nimport random, time, pickle\nfrom sys import argv\n\nsize = 25\ninput_size = 12\nchance_of_obstacles = 0.2\ncanvas = [[0]*size,[0]*size]\nball_position = 2\nball_in_air = -1\nlose = False\nball_in_air_time = 2\nJUMP = 1 # ball operation\nRUN = 0 # ball operation\nNOTHING = 0\nBALL = 1\nOBASTACLE = 2\nFAIL = 3\nMAGIC_NUM = 0.233\n\ndef initialize():\n global canvas, ball_in_air, lose\n canvas = [[0]*size,[0]*size]\n canvas[1][ball_position] = BALL\n ball_in_air = -1\n lose = False\n\ndef save_dna(file_name, dna):\n with open(file_name, \"wb\") as fp: # Pickling\n pickle.dump(dna, fp)\n fp.close()\n\ndef load_dna(file_name):\n with open(file_name, \"rb\") as fp: # Unpickling\n return pickle.load(fp)\n\ndef preprocess(canvas):\n p = 0\n for i in range(size):\n if canvas[1][size - i - 1] == OBASTACLE:\n p += 2**i\n return p\n\ndef draw(canvas):\n # draw the first line\n line = \"\"\n for i in range(size):\n c=canvas[0][i]\n if(c == BALL):\n line = line + \"o\"\n else:\n line = line + \" \"\n print(line)\n # draw the second line\n line = \"\"\n for i in range(size):\n c=canvas[1][i]\n if(c == BALL):\n line = line + \"o\"\n elif(c == OBASTACLE):\n line = line + \"L\"\n elif(c == FAIL):\n line = line + \"X\"\n else:\n line = line + \" \"\n print(line)\n line = \"\"\n for i in range(size):\n line += \"-\"\n print(line)\n print(\" \")\n \n\ndef ball_change(canvas, action):\n global lose\n if(action == JUMP):\n canvas[0][ball_position] = BALL\n canvas[1][ball_position] = NOTHING\n else:\n canvas[0][ball_position] = NOTHING\n if(canvas[1][ball_position] == OBASTACLE):\n lose = True\n canvas[1][ball_position] = FAIL\n else:\n canvas[1][ball_position] = BALL\n\ndef ball_AI(canvas, dna):\n y = 0\n for i in range(input_size):\n y += dna[i]*canvas[1][i]\n if(y > MAGIC_NUM):\n return JUMP\n else:\n return RUN\n\ndef move_on(canvas):\n global lose\n global ball_in_air\n global chance_of_obstacles\n canvas[0] = canvas[0][1:size] + [NOTHING]\n canvas[1] = canvas[1][1:size] + [NOTHING]\n if(ball_in_air >= 0): \n canvas[0][ball_position] = BALL\n canvas[0][ball_position - 1] = NOTHING\n else:\n if(canvas[1][ball_position] == OBASTACLE):\n lose = True\n canvas[1][ball_position] = FAIL\n else:\n canvas[1][ball_position] = BALL\n canvas[1][ball_position - 1] = NOTHING\n i = random.randint(0,100)\n if(i/100 < chance_of_obstacles):\n chance_of_obstacles = 0\n canvas[1][size - 1] = OBASTACLE\n else:\n chance_of_obstacles += 0.05\n\n\n\n# T is the maximum iteration, \n# in_training is a bool value that says whether you don't want to print animation\ndef game_start(T, in_training, dna): \n global ball_in_air\n global lose\n t=0\n while(t 0):\n ball_in_air -= 1\n elif(ball_in_air == 0):\n ball_in_air -= 1\n ball_change(canvas, RUN)\n else:\n action = ball_AI(canvas, dna)\n if(action == JUMP):\n ball_in_air = ball_in_air_time\n ball_change(canvas, JUMP)\n if(not in_training):\n draw(canvas)\n time.sleep(0.25)\n if(not in_training):\n if(lose):\n print(\" YOU LOSE!!!\")\n else:\n print(\" ARRIVED!!!\")\n return t\n \n\nif __name__ == \"__main__\":\n initialize()\n dna_path = argv[1]\n dna = load_dna(dna_path)\n game_start(300, False, dna)\n\n \n \n\n","sub_path":"Project_1/codes/hurdling.py","file_name":"hurdling.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"374276182","text":"# -*- coding: utf8 -*-\n\ndef cleanup( text ):\n paragraphs = text.split( \"\\n\" )\n result = \"\"\n for p in paragraphs:\n p = p.strip()\n if len( p ) > 0:\n if p[-1] != \".\":\n p += \".\"\n result += u\"%s\\n\" % p\n return result\n\n\n","sub_path":"python/news_snack/algorithms/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"236084295","text":"class Solution:\n def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:\n graph = collections.defaultdict(list)\n for i in range(n):\n graph[i] = []\n for node1, node2 in edges:\n graph[node1].append(node2)\n graph[node2].append(node1)\n def bfs(graph, src):\n visited = set()\n cur = collections.deque([src])\n res = 0\n while cur:\n n = len(cur)\n for i in range(n):\n node = cur.popleft()\n visited.add(node)\n for neighbor in graph[node]:\n if neighbor in visited:\n continue\n cur.append(neighbor)\n if cur: res+=1\n return res\n minHeight = sys.maxsize\n res = []\n for i in range(n):\n h = bfs(graph, i)\n if h > minHeight:\n continue\n if h==minHeight:\n res.append(i)\n else:\n minHeight = h\n res.clear()\n res.append(i)\n return res\n\n","sub_path":"Leetcode/tree/310_Minimum Height Trees/brute_force/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"643309419","text":"from flask import Flask, render_template, jsonify\nfrom flask_socketio import SocketIO, emit\n# from camera import VideoCamera\nfrom subprocess import check_output\nimport json\nimport psutil\nimport requests\nimport time\nimport platform\nimport os\n\n\napp = Flask(__name__)\napp.config[\"SECRET_KEY\"] = \"secret!\"\nsocketio = SocketIO(app)\nthread = None\n\nisStreaming = True\nisRecognition = False\nHOST = os.getenv('IP', '0.0.0.0')\nPORT = int(os.getenv('PORT', 5000))\n\n\ndef background_thread():\n socketio.emit(\"my_response\", namespace=\"/test\")\n\n\ndef get_procs():\n allProcs = []\n for proc in psutil.process_iter():\n try:\n pinfo = proc.as_dict(attrs=[\"pid\", \"name\"])\n allProcs.append(pinfo)\n except psutil.NoSuchProcess:\n pass\n return allProcs\n\n\ndef gen(camera):\n while True:\n frame = camera.get_frame()\n yield (b\"--frame\\r\\n\"\n b\"Content-Type: image/jpeg\\r\\n\\r\\n\" + frame + b\"\\r\\n\\r\\n\")\n\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n\n\n@socketio.on(\"connect\", namespace=\"/test\")\ndef test_connect():\n global thread\n if thread is None:\n thread = socketio.start_background_task(target=background_thread)\n emit(\"my_response\", {\"data\": \"Connected\", \"count\": 0})\n\n\n# @app.route(\"/video\")\n# def video_feed():\n # return Response(gen(VideoCamera()),\n # mimetype=\"multipart/x-mixed-replace; boundary=frame\")\n\n\n@app.route(\"/processes\", methods=[\"GET\"])\ndef get_process():\n return jsonify({\"processes\": get_procs()})\n\n\ndef get_sys_stats():\n\n # squareLen = 4\n # xLeft = random.randint(1, 10)\n # yLeft = random.randint(1, 10)\n # yLeft += 1\n # topLeft = (xLeft, yLeft)\n # botRight = (xLeft + squareLen - 1, yLeft - squareLen - 1)\n\n data = [{\"cpu\": {\"times\": {\"user\": psutil.cpu_times()[0],\"nice\": psutil.cpu_times()[1],\"system\": psutil.cpu_times()[2],\"idle\": psutil.cpu_times()[3]},\"load\": psutil.cpu_percent(interval=1, percpu=True),\"cores\": psutil.cpu_count()},\"net\": {\"bytes_sent\": psutil.net_io_counters()[0], \"bytes_recieved\": psutil.net_io_counters()[1], \"packets_sent\": psutil.net_io_counters()[2], \"packets_recv\": psutil.net_io_counters()[3], \"errin\": psutil.net_io_counters()[4], \"errout\": psutil.net_io_counters()[5], \"dropin\": psutil.net_io_counters()[6], \"dropout\": psutil.net_io_counters()[7]},\"disk\": {\"total\": psutil.disk_usage(\"/\")[0],\"used\": psutil.disk_usage(\"/\")[1],\"free\": psutil.disk_usage(\"/\")[2],\"percent\": psutil.disk_usage(\"/\")[3]},\"memory\": {\"total\": psutil.virtual_memory()[0],\"available\": psutil.virtual_memory()[1],\"percent\": psutil.virtual_memory()[2],\"used\": psutil.virtual_memory()[3],\"free\": psutil.virtual_memory()[4]}}]\n return data\n\n\n@app.route(\"/device_stats\", methods=[\"GET\", \"POST\"])\ndef get_stats():\n return jsonify({\"stats\": get_sys_stats()})\n\n\ndef getOS():\n platform_data = platform.uname()\n system = platform_data[0]\n\n if (system == \"Windows\"):\n return False\n elif (system == \"Linux\"):\n system_dist = platform.dist()\n if (system_dist[0] == \"Ubuntu\"):\n return True\n elif (system_dist[0] == \"debian\"):\n return False\n else:\n return False\n\n\ndef hasAppURL():\n if (getOS()):\n return True\n\n\ndef getAppURL():\n '''\n Get URL address for C9 servers\n '''\n output = check_output([\"cat\", \"/etc/hosts\"])\n alias_parts = output.splitlines()[0].decode(\"utf8\").split(\" \")\n alias_parts = [i for i in alias_parts if i != ''] # Remove all whitespaces elements\n alias_parts = alias_parts[1].split(\"-\")\n alias_parts = alias_parts[0:-1] # Remove last number element\n login = alias_parts.pop(0) # Add first element to the end\n alias_parts.append(login) # Add first element to the end\n\n domain_name_len = len(alias_parts)\n domain_name = \"\"\n i = 0\n while (i != domain_name_len):\n if (i == domain_name_len - 1):\n domain_name += alias_parts[i]\n else:\n domain_name += alias_parts[i] + \"-\"\n i += 1\n\n url = \"https://\" + domain_name + \".c9users.io\"\n return url\n\n\ndef register_device():\n url = \"https://device-manager-stable-jonsnow123kappa.c9users.io/register\"\n get_ip = requests.get(\"http://httpbin.org/ip\")\n ip = get_ip.json()\n\n task = \"\"\n if (isStreaming):\n task = \"Streaming\"\n if (isRecognition):\n task = \"Recognition\"\n\n if hasAppURL():\n data = {\"address\": getAppURL(), \"task_group\": task}\n else:\n data = {\"address\": \"{}:{}\".format(ip[\"origin\"], PORT),\n \"task_group\": task}\n\n headers = {\"Content-type\": \"application/json\"}\n\n while True:\n r = requests.post(url, data=json.dumps(data), headers=headers)\n if (r.status_code == 200):\n print(\"Device has been successfully registered!\")\n break\n else:\n print(\"Device manager is unavailable. Attempting to connect...\")\n time.sleep(5)\n continue\n\n\nif __name__ == \"__main__\":\n try:\n register_device()\n socketio.run(app, host=HOST, port=PORT, debug=False)\n except Exception as e:\n print(e)\n except KeyboardInterrupt:\n print(\"Keyboard interrupt has been invoked. Exitting...\")\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"402491966","text":"from keras.callbacks import ModelCheckpoint\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation, Flatten\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.metrics import mean_absolute_error \nfrom matplotlib import pyplot as plt\nimport seaborn as sb\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport warnings \nwarnings.filterwarnings('ignore')\nwarnings.filterwarnings('ignore', category=DeprecationWarning)\nfrom xgboost import XGBRegressor\n\n\ndef get_data():\n #get train data\n train_data_path ='train.csv'\n train = pd.read_csv(train_data_path)\n uniques = train[0:1]\n\n #get test data\n test_data_path ='test.csv'\n test = pd.read_csv(test_data_path)\n #uniques = pd.factorize(['b', 'b', 'a', 'c', 'b'])\n \n return train , test\n\n\ndef get_combined_data():\n #reading train data\n train , test = get_data()\n\n target = train.Producao\n train.drop(['Producao'],axis = 1 , inplace = True)\n\n combined = train.append(test)\n combined.reset_index(inplace=True)\n #combined.drop(['index', 'Id'], inplace=True, axis=1)\n return combined, target\n\n\n#Load train and test data into pandas DataFrames\ntrain_data, test_data = get_data()\n\n#Combine train and test data to process them together\ncombined, target = get_combined_data()\n\n#print(combined.describe())\n\n\n\ndef get_cols_with_no_nans(df,col_type):\n '''\n Arguments :\n df : The dataframe to process\n col_type : \n num : to only get numerical columns with no nans\n no_num : to only get nun-numerical columns with no nans\n all : to get any columns with no nans \n '''\n if (col_type == 'num'):\n predictors = df.select_dtypes(exclude=['object'])\n elif (col_type == 'no_num'):\n predictors = df.select_dtypes(include=['object'])\n elif (col_type == 'all'):\n predictors = df\n else :\n print('Error : choose a type (num, no_num, all)')\n return 0\n cols_with_no_nans = []\n for col in predictors.columns:\n if not df[col].isnull().any():\n cols_with_no_nans.append(col)\n return cols_with_no_nans\n\n\nnum_cols = get_cols_with_no_nans(combined , 'num')\ncat_cols = get_cols_with_no_nans(combined , 'no_num')\n\nprint ('Number of numerical columns with no nan values :',len(num_cols))\nprint ('Number of nun-numerical columns with no nan values :',len(cat_cols))\n\n'''combined = combined[num_cols + cat_cols]\ncombined.hist(figsize = (12,10))\nplt.show()'''\n#----------- \"Esse\"\n'''\ntrain_data = train_data[num_cols + cat_cols]\ntrain_data['Target'] = target\n\nC_mat = train_data.corr()\nfig = plt.figure(figsize = (15,15))\n\nsb.heatmap(C_mat, vmax = .8, square = True)\nplt.show()'''\n\n#Now, split back combined dataFrame to training data and test data\n\ndef split_combined():\n global combined\n train = combined[:88]\n test = combined[88:]\n\n return train , test \n \ntrain, test = split_combined()\n'''-----> Make the Deep Neural Network\nDefine a sequential model\nAdd some dense layers\nUse ‘relu’ as the activation function for the hidden layers\nUse a ‘normal’ initializer as the kernal_intializer '''\n\n'''Initializers define the way to set the initial random weights of Keras layers.\nWe will use mean_absolute_error as a loss function\nDefine the output layer with only one node\nUse ‘linear ’as the activation function for the output layer'''\n\nNN_model = Sequential()\n\n# The Input Layer :\nNN_model.add(Dense(6, kernel_initializer='normal',input_dim = train.shape[1], activation='sigmoid'))\n\n# The Hidden Layers :\nNN_model.add(Dense(12, kernel_initializer='normal',activation='sigmoid'))\nNN_model.add(Dense(12, kernel_initializer='normal',activation='sigmoid'))\nNN_model.add(Dense(12, kernel_initializer='normal',activation='sigmoid'))\n\n# The Output Layer :\nNN_model.add(Dense(1, kernel_initializer='normal',activation='linear'))\n\n# Compile the network :\nNN_model.compile(loss='mean_absolute_error', optimizer='adam', metrics=['mean_absolute_error'])\nNN_model.summary()\n\n\n#Define a checkpoint callback\ncheckpoint_name = 'Weights-{epoch:03d}--{val_loss:.5f}.hdf5' \ncheckpoint = ModelCheckpoint(checkpoint_name, monitor='val_loss', verbose = 1, save_best_only = True, mode ='auto')\ncallbacks_list = [checkpoint]\n\n#Train the model\nNN_model.fit(train, target, epochs=1500, batch_size=3, validation_split = 0.2, callbacks=callbacks_list)\n\n# Load wights file of the best model :\nwights_file = 'Weights-1353--739.24282.hdf5' # choose the best checkpoint \nNN_model.load_weights(wights_file) # load it\nNN_model.compile(loss='mean_absolute_error', optimizer='adam', metrics=['mean_absolute_error'])\n\ndef make_submission(prediction, sub_name):\n my_submission = pd.DataFrame({'Id':pd.read_csv('test.csv').Id,'Producao':prediction})\n my_submission.to_csv('{}.csv'.format(sub_name),index=False)\n print('A submission file has been made')\n\npredictions = NN_model.predict(test)\nmake_submission(predictions[:,0],'Prediction result')\n","sub_path":"TCC/Conjuntos de testes/1tmp1chv_New/rede01.py","file_name":"rede01.py","file_ext":"py","file_size_in_byte":5004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"454529323","text":"import math\nimport os\nimport struct\nimport sklearn.metrics as metrics\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport multiprocessing\nfrom multiprocessing import Manager\nfrom sklearn.decomposition import PCA\n\n\ndef load_dataset(path): # 读取数据集\n train_image_path = os.path.join(path, 'train-images.idx3-ubyte')\n train_label_path = os.path.join(path, 'train-labels.idx1-ubyte')\n test_image_path = os.path.join(path, 't10k-images.idx3-ubyte')\n test_label_path = os.path.join(path, 't10k-labels.idx1-ubyte')\n\n with open(train_image_path, 'rb') as image_path:\n magic_train_number, num_train_images, num_train_rows, num_train_columns = struct.unpack('>IIII',\n image_path.read(16))\n # print(magic_train_number,num_train_images,num_train_rows,num_train_columns)\n train_images = np.fromfile(image_path, dtype=np.uint8).reshape(60000, 784)\n\n with open(train_label_path, 'rb') as label_path:\n magic_train_number2, num_train_items = struct.unpack('>II', label_path.read(8))\n # print(magic_train_number2,num_train_items)\n train_labels = np.fromfile(label_path, dtype=np.uint8)\n\n with open(test_image_path, 'rb') as image_path2:\n magic_test_number, num_test_images, num_test_rows, num_test_columns = struct.unpack('>IIII',\n image_path2.read(16))\n # print(magic_test_number, num_test_images, num_test_rows, num_test_columns)\n test_images = np.fromfile(image_path2, dtype=np.uint8).reshape(10000, 784)\n\n with open(test_label_path, 'rb') as label_path2:\n magic_test_number2, num_test_items = struct.unpack('>II', label_path2.read(8))\n # print(magic_test_number2, num_test_items)\n test_labels = np.fromfile(label_path2, dtype=np.uint8)\n\n train_images = train_images / 127.0\n test_images = test_images / 127.0\n return train_images, train_labels, test_images, test_labels\n\n\ndef one_hot(y):\n ans = np.zeros((y.shape[0], 10))\n for i in range(y.shape[0]):\n ans[i][y[i]] = 1\n return ans\n\ndef sigmoid(z):\n return 1 / (1 + np.exp(-z))\n\ndef propagate(X, Y, w, b):\n # print(X.shape,Y.shape,w.shape)\n num = X.shape[1]\n A = sigmoid(np.dot(w.T, X) + b)\n # print(A.shape)\n cost = (-1 / num) * np.sum(Y * np.log(A) + (1 - Y) * (np.log(1 - A)))\n dw = (1 / num) * np.dot(X, (A - Y).T)\n # print(dw.shape)\n db = (1 / num) * np.sum(A - Y)\n return cost, dw, db\n\ndef train(X, y, iterations, learningRate):\n X = np.array(X)\n y = np.array(y)\n X = X.T\n y = y.T\n w = np.zeros((X.shape[0], 1))\n b = 0\n for i in range(iterations):\n cost, dw, db = propagate(X, y, w, b)\n w -= learningRate * dw\n b -= learningRate * db\n return w, b\n\n\nif __name__ == '__main__':\n train_images, train_labels, test_images, test_labels = load_dataset('Mnist')\n y_train = one_hot(train_labels)\n error_rates=[]\n iterations=[10,100,500,1000]\n learningRates=[0.01,0.1,1,10]\n for iteration in iterations:\n for learningRate in learningRates:\n W = []\n B = []\n for i in range(10):\n X = train_images\n y = []\n for j in range(train_images.shape[0]):\n if (train_labels[j] == i):\n y.append(1)\n else:\n y.append(0)\n w, b = train(X, y, iterations=iteration, learningRate=learningRate)\n # print(w.shape)\n W.append(w)\n B.append(b)\n print('第{}轮已训练完成'.format(i))\n W = np.array(W)\n B = np.array(B)\n # print(W.shape, B.shape)\n cnt=0\n for i in range(test_images.shape[0]):\n res = []\n for j in range(10):\n res.append(sigmoid(np.dot(test_images[i], W[j]) + B[j]))\n y_predict = np.argmax(res)\n # print(res)\n # print('预测值:{},实际值:{}'.format(y_predict, test_labels[i]))\n if(y_predict!=test_labels[i]):\n cnt+=1\n print('错误率为:',cnt/100.0)\n error_rates.append(cnt/100.0)\n print(error_rates)\n#24.95 16.7 36.22 31.22\n#16.73 11.26 17.23 16.06\n#12.64 9.23 11.85 24.23\n#11.29 8.74 11.37 22.29\n\n","sub_path":"Perceptron/logic_regression.py","file_name":"logic_regression.py","file_ext":"py","file_size_in_byte":4509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"558723221","text":"import math\nimport tensorflow as tf\nimport numpy as np\n\nfrom .pressure_model_fn import pressure_model_fn\nfrom .fast_predict import FastPredict\n\nclass Pressure():\n def __init__(self):\n params = {}\n\n # ----- Input -----\n # Grid parameters\n params[\"p_ll\"] = (0, 0)\n params[\"p_ur\"] = (15, 15)\n params[\"xRes\"] = 0.25\n params[\"yRes\"] = 0.25\n params[\"h\"] = 0.5\n params[\"N_x\"] = round((params[\"p_ur\"][0]-params[\"p_ll\"][0] + params[\"xRes\"]) / params[\"xRes\"])\n params[\"N_y\"] = round((params[\"p_ur\"][1]-params[\"p_ll\"][1] + params[\"yRes\"]) / params[\"yRes\"])\n\n # Attributes that the model uses\n params[\"body_channels\"] = [\"mass\", \"vx\", \"vy\", \"omega\"]\n params[\"contact_channels\"] = [\"nx\", \"ny\"]\n params[\"feature_channels\"] = params[\"body_channels\"] + params[\"contact_channels\"]\n params[\"N_c\"] = len(params[\"body_channels\"]) + len(params[\"contact_channels\"])\n\n\n # ----- Model Parameters -----\n # Training parameters\n params[\"eta\"] = 0.001\n params[\"initializer_stddev\"] = 0.1\n\n # A weight multiplied with the loss from nodes where the label is zero\n params[\"use_zero_weight\"] = True\n params[\"zero_weight\"] = 0.25\n\n # A weight multiplied with the l2-regularization loss\n params[\"lmbda\"] = 0.01\n\n\n # ----- Layer Parameters -----\n f = 16\n k = 4\n\n # Input layer\n\n # Initial convolution\n params[\"input_conv_filters\"] = f\n params[\"input_conv_kernel\"] = k\n\n # Pooling layer\n params[\"n_poolings\"] = 2\n params[\"pool_size\"] = [2 for _ in range(params[\"n_poolings\"])]\n params[\"pool_stride\"] = [2 for _ in range(params[\"n_poolings\"])]\n\n # First round of convolution layers\n params[\"n_convolutions_1\"] = 2\n params[\"conv_1_filters\"] = [f for _ in range(params[\"n_convolutions_1\"])]\n params[\"conv_1_kernel\"] = [k for _ in range(params[\"n_convolutions_1\"])]\n\n # Second round of convolution layers\n params[\"n_convolutions_2\"] = 2\n params[\"conv_2_filters\"] = [f/2, f/4]\n params[\"conv_2_kernel\"] = [1 for _ in range(params[\"n_convolutions_2\"])]\n\n\n # ----- Model config -----\n # Path to model storage\n params[\"model_path\"] = \"./src/tensorflow/models/pressure/\"\n\n # Tells the model whether or not to use GPUs, and only keep 1 checkpoint\n gpu_options = tf.GPUOptions(allow_growth=True)\n config = tf.ConfigProto(\n device_count = {\"GPU\": 0}, # Switch from GPU to CPU\n gpu_options = gpu_options,\n )\n runconfig = tf.estimator.RunConfig(\n keep_checkpoint_max = 1,\n session_config = config\n )\n\n self.params = params\n self.estimator = tf.estimator.Estimator(\n model_fn = pressure_model_fn,\n model_dir = params[\"model_path\"],\n params = params,\n config = runconfig\n )\n\n # We create a FastPredict object, which is used for making predictions\n # without having to reload the model each time\n # First we create an input fn taking a generator as input\n def pred_input_fn(generator):\n\n def _inner_input_fn():\n dataset = tf.data.Dataset().from_generator(\n generator,\n output_types=(tf.float32),\n ).batch(1)\n iterator = dataset.make_one_shot_iterator()\n features = iterator.get_next()\n return {'x': features}\n\n return _inner_input_fn\n\n self.FastPredict = FastPredict(self.estimator, pred_input_fn)\n\n\n def train(self, features, labels, train_params):\n # We create the input function\n train_input_fn = tf.estimator.inputs.numpy_input_fn(\n x = {\"x\": features},\n y = labels,\n batch_size = train_params[\"batch_size\"],\n num_epochs = train_params[\"num_epochs\"],\n shuffle = True\n )\n\n # We train\n self.estimator.train(\n input_fn=train_input_fn\n )\n\n\n def evaluate(self, features, labels):\n # We create the input function\n eval_input_fn = tf.estimator.inputs.numpy_input_fn(\n x = {\"x\": features},\n y = labels,\n num_epochs = 1,\n shuffle = False\n )\n\n # We do the evaluation\n eval_results = self.estimator.evaluate(input_fn=eval_input_fn)\n\n return eval_results\n\n\n def predict(self, features):\n # We do the predictions\n pred_results = self.FastPredict.predict(features)\n\n # For some reason the result is some unsubscriptable iterator object\n # There should only be a single pred_dict\n for pred_dict in pred_results:\n ni = pred_dict[\"ni\"]\n ti = pred_dict[\"ti\"]\n\n return (ni, ti)\n","sub_path":"src/tensorflow/pressure.py","file_name":"pressure.py","file_ext":"py","file_size_in_byte":4937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"464882387","text":"\"\"\"REST_IA_Server URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import include, path\nfrom rest_framework import routers\nfrom server import views\nfrom django.conf import settings, urls\n\n\nrouter = routers.DefaultRouter()\nrouter.register(r'typeelements', views.TypeElementViewSet, basename='typeelement')\nrouter.register(r'elements', views.ElementViewSet, basename='element')\nrouter.register(r'users', views.UserViewSet, basename='user')\nrouter.register(r'owners', views.OwnerViewSet, basename='owner')\nrouter.register(r'applications', views.ApplicationViewSet, basename='application')\nrouter.register(r'visites', views.VisiteViewSet, basename='visite')\nrouter.register(r'typepages', views.TypePageViewSet, basename='typepage')\nrouter.register(r'pages', views.PageViewSet, basename='page')\nrouter.register(r'actions', views.ActionViewSet, basename='action')\nrouter.register(r'typeactions', views.TypeActionViewSet, basename='typeaction')\nrouter.register(r'pertinences', views.PertinenceViewSet, basename='pertinence')\n\n\nurlpatterns = [\n path('', include(router.urls)),\n path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n path('admin/', admin.site.urls)\n # urls.url('^pertinent/(?P.+)$', views.RefuseDemandeAPIView.as_view()),\n]\n","sub_path":"REST_IA_Server/REST_IA_Server/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"341549689","text":"import numpy as np\nimport os\nimport sys\nfrom collections import defaultdict\nskip_list = open(\"skip_list\").read().split()\nprint(\"skip\",skip_list)\nfilename, compression_mode, nb_reads, nb_ambiguous, size, nb_skipped_bytes, barcode_length, repetitions = \"\",\"\",0,0,0,-1,0,0\ntable = defaultdict(list)\ndef record():\n global nb_skipped_bytes\n if os.path.basename(filename) in skip_list: \n return\n if not os.path.exists(\"/home/gzip/fastq/hdd_files/\"+os.path.basename(filename)):\n print(\"not recording stats for file\",os.path.basename(filename),\"might be multipart/blocked\")\n return\n #success = 1 if (nb_reads > 0 and nb_ambiguous == 0) else 0 \n success = ((1.0*nb_reads)/(nb_reads+nb_ambiguous)) if nb_reads > 0 else 0\n nb_skipped_bytes /= repetitions\n table[compression_mode]+=[(filename,size,barcode_length,nb_skipped_bytes,success)]\n print(filename,compression_mode,size,barcode_length,nb_reads,nb_ambiguous,success,nb_skipped_bytes)\n\nfor line in open(sys.argv[1]):\n if \".gz\" in line:\n new_filename = line.split(\":\")[0]\n if new_filename == filename:\n repetitions += 1\n continue # just a different execution of same file, we'll record everything when at the next different file\n if filename != \"\": record()\n filename = new_filename\n if \"max speed\" in line:\n compression_mode = \"lowest\"\n elif \"max compression\" in line:\n compression_mode = \"best\"\n else:\n compression_mode = \"normal\"\n if filename.endswith(\"ERA987833-CNC_CasAF3_CRI1strepeat_rep1_R1.fastq.gz\"):\n compression_mode = \"best\" # clearly not a gzip -1, it compresses even better than gzip -9, so maybe zopfli\n if filename.endswith(\"ERA972101-1503_TGACCA_L005_R1_001.fastq.gz\"):\n compression_mode = \"best\" #same\n\n size = int(line.split()[line.split().index(\"seek\")-1])\n nb_reads, nb_ambiguous, nb_skipped_bytes, barcode_length, repetitions = 0,0,-1, 0, 0\n if \"done, printed\" in line:\n nb_reads += int(line.split()[2])\n if \"and also didn't print\" in line:\n nb_ambiguous += int(line.split()[4])\n if \"at decoded block\" in line and len(line.split()) > 13:\n nb_blocks = int(line.split()[9].strip(','))\n mean_block_length = float(line.split()[13])\n nb_skipped_bytes += nb_blocks * mean_block_length\n if \"barcode\" in line:\n barcode_length = len(line.split()[-1])\n\nrecord()\n\ndef avg_sd(l,norm=0,perc=0):\n assert(type(l) == list and len(l)>1)\n return (\"%5.1f\" % ((100.0**perc)*np.average(l)/(1024**norm))) + \" +- \" + (\"%2.3f\" % ((100.0**perc)*np.std(l)/(1024**norm)))\n\nprint(\"----\")\nprint(\"%10s\" % \"comp\", \"%5s\" % \"files\",\"%5s\" % \"size\", \"%12s\" % \"skipped\", \"%12s\" % \"success\")\nall_sizes, all_successes, all_skipped_bytes = [],[],[]\nfor compression_mode in table:\n sizes, successes, skipped_bytes = [], [], []\n for (filename, size, barcode_length, skipped, success) in table[compression_mode]:\n sizes.append(size)\n successes.append(success)\n if skipped != -1:\n skipped_bytes.append(skipped)\n\n if len(skipped_bytes) > 0 :\n avg_skipped_bytes = avg_sd(skipped_bytes,2)\n else:\n avg_skipped_bytes = \"NA\"\n all_sizes.extend(sizes)\n all_successes.extend(successes)\n all_skipped_bytes.extend(skipped_bytes)\n print(\"%10s\" % compression_mode, \"%5d\" % len(table[compression_mode]),\"%5.1f\" % (sum(sizes)/(1024*1024*1024.0)), avg_skipped_bytes, avg_sd(successes,perc=1))\n\nprint(\"%10s\" % \"Total\", \"%5d\" % len(all_sizes), \"%5.1f\" % (sum(all_sizes)/(1024*1024*1024.0)),avg_sd(all_skipped_bytes,norm=2), avg_sd(all_successes,perc=1))\n\n# save to tinydb\nfrom tinydb import TinyDB, Query\ndb = TinyDB('db.json')\nquery = Query()\nfor compression_mode in table:\n for (filename, size, barcode_length, nb_skipped_bytes, success) in table[compression_mode]:\n if len(db.search(query.filename == filename)) == 0:\n db.insert({'filename': filename})\n db.update({'compression_level': compression_mode, 'size' : size, 'nb_skipped_bytes': nb_skipped_bytes }, query.filename == filename)\n if barcode_length > 0:\n db.update({'barcode': barcode_length}, query.filename == filename)\n","sub_path":"scripts/parse_random_access.py","file_name":"parse_random_access.py","file_ext":"py","file_size_in_byte":4253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"621064737","text":"import pdb\r\nclass Solution:\r\n def longestPalindrome(self, s: str) -> str:\r\n def expand(c):\r\n i, j = c,c\r\n while i>=0 and jlen(ans):\r\n ans = curr\r\n curr = expand(c,c+1)\r\n if len(curr)>len(ans):\r\n ans = curr\r\n return ans\r\nprint(Solution().longestPalindrome(\"baba\"))\r\n\r\n\r\n#### Booty solution I came up with during a test...\r\n# class Solution:\r\n# def longestPalindrome(self, s: str) -> str:\r\n# def newMax(i,j,k):\r\n# nonlocal longest, start, end\r\n# if k-j-2+1>longest[i]:\r\n# longest[i] = k-j-2+1 #overcounted by 2\r\n# start[i] = j+1\r\n# end[i] = k-1\r\n# if s==\"\":\r\n# return \"\"\r\n# longest = [1]*len(s) #min length = 1\r\n# start = [0]*len(s)\r\n# end = [0]*len(s)\r\n# for i in range(len(s)):\r\n# # Odd length palindrome\r\n# j = k = i\r\n# while j>=0 and k=0 and k= 10:\n articles = str(int(articles) - 20)\n break\n continue\n\n html = request.json()\n title = html['data']['productTitle']\n price = html['data']['productPrice']\n description = html['data']['productDescription']\n day = datetime.today().replace(microsecond=0)\n\n URL = 'https://m.joongna.com/product-detail/' + articles\n if price < 10000:\n articles = str(int(articles) + 2)\n continue\n\n # print(title, price, day, URL, description)\n\n \"\"\"\n 데이터 분석 및 몽고디비 연결\n \"\"\"\n try:\n DataCheck.DataCheck(title, str(price), URL, day, description, 1)\n except Exception:\n with open(os.path.join(BASE_DIR, \"Error.txt\"), \"a+\") as f:\n f.write(\"Error URL : \" + URL + \"\\n\")\n\n articles = str(int(articles) + 2)\n count = 0\n\nrequest.close()\n\nwith open(os.path.join(BASE_DIR, \"startJoongo2.txt\"), \"w\") as f:\n f.write(articles)\n\n\ncrawlbotlogging.endLog(\"Joongo2.py\", articles, startTime)","sub_path":"Joongo2.py","file_name":"Joongo2.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"296134959","text":"import sys\n\nimport requests\n\n\nname = input(\"your name?\")\nprint(\"hello\", name)\n\n\ndef greeting(who):\n greeting = \"hey {}\".format(who)\n return greeting\n\n\n# print (sys.version)\nprint(sys.executable)\n\nr = requests.get(\"https://macblaze.ca\")\n\nprint(r.status_code)\n\n# shft opt f = autoformat\n","sub_path":"list_python_source.py","file_name":"list_python_source.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"492865840","text":"# Copyright 2020 The TensorFlow Probability 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\"\"\"System for dynamically rewriting modules to support multiple backends.\n\nThe theory of operation is as follows. In general, when requesting a module to\nbe imported Python first accesses finders in `sys.meta_path`, which assign a\nloader to a module.\n\nWe hook into this system by providing a custom finder which trigers when a\ncertain module name is loaded, and then specifies a custom loader which\nmanipulates the source of the module before executing it. The source is\nmanipulated primarily to alter the import lines to point to a new backend\nmodule.\n\nBy modifiying the loader, we make this process resilent to reloads via IPython's\n`autoreload` magic, as well as `importlib.reload` function.\n\nConcretely, modules of the name `inference_gym.dynamic..` are\nspecially handled to:\n\n1. Load the source from the `inference_gym.` module instead.\n2. Rewrite external imports, like TensorFlow and TensorFlow Probability.\n3. Rewrite imports of the form `inference_gym.` inside the modules to be\n `inference_gym.dynamic..`, which repeats this process\n for .\n4. Rewrite `BACKEND = None` to `BACKEND = ''.\n\nThe various name/filename manipulations are done relative to a 'root module'\nwhich is `inference_gym` in this case.\n\nAs a special note, `inference_gym.dynamic.backend_` modules already\nexist on the filesystem to simplify logic in this module, and are not rewritten.\nThis works fine because the custom finder we install is only queried if the\nregular Python finders fail to find anything.\n\"\"\"\n\nimport importlib\nimport importlib.abc\nimport importlib.machinery\nimport importlib.util\nimport re\nimport sys\n\n# For debugging, you can turn this on which prints a large number of messages to\n# stdout. We don't use regular absl.logging because most of this happens before\n# it is set up in `main`.\nDEBUG = False\n\n\ndef _external_rewrites(backend, data):\n \"\"\"Rewrite external imports.\"\"\"\n # TFP\n if backend == 'backend_tensorflow':\n sub = 'import tensorflow_probability as tfp'\n elif backend == 'backend_jax':\n sub = 'import tensorflow_probability.substrates.jax as tfp'\n elif backend == 'backend_numpy':\n sub = 'import tensorflow_probability.substrates.numpy as tfp'\n else:\n raise ValueError(f'Unknown backend {backend}')\n data = re.sub('import tensorflow_probability as tfp', sub, data)\n\n # TensorFlow\n if backend == 'backend_tensorflow':\n sub = 'import tensorflow.compat.v2 as tf'\n elif backend == 'backend_jax':\n sub = ('from tensorflow_probability.substrates import jax as _tfp_jax; tf ='\n ' _tfp_jax.tf2jax; del _tfp_jax')\n elif backend == 'backend_numpy':\n sub = ('from tensorflow_probability.substrates import numpy as _tfp_numpy; '\n 'tf = _tfp_numpy.tf2numpy; del _tfp_numpy')\n else:\n raise ValueError(f'Unknown backend {backend}')\n data = re.sub('import tensorflow.compat.v2 as tf', sub, data)\n\n # TFP's direct imports\n if backend == 'backend_tensorflow':\n sub = 'from tensorflow_probability.python'\n elif backend == 'backend_jax':\n sub = 'from tensorflow_probability.substrates.jax'\n elif backend == 'backend_numpy':\n sub = 'from tensorflow_probability.substrates.numpy'\n else:\n raise ValueError(f'Unknown backend {backend}')\n data = re.sub('from tensorflow_probability.python',\n sub, data)\n\n # TF's internal nest module\n if backend == 'backend_tensorflow':\n sub = 'from tensorflow.python.util import nest'\n elif backend == 'backend_jax':\n sub = 'from tensorflow_probability.python.internal.backend.jax import nest'\n elif backend == 'backend_numpy':\n sub = (\n 'from tensorflow_probability.python.internal.backend.numpy import nest')\n else:\n raise ValueError(f'Unknown backend {backend}')\n data = re.sub('from tensorflow.python.util import nest',\n sub, data)\n\n return data\n\n\ndef _root_name_comps():\n \"\"\"Return the name components of the root module.\"\"\"\n # This assumes `rewrite` is a 2 levels deep inside of `inference_gym`. If we\n # move it, we'd change the `-2` to equal the (negative) nesting level.\n return __name__.split('.')[:-2]\n\n\ndef _root_name():\n \"\"\"Return the name of the root module.\"\"\"\n return '.'.join(_root_name_comps())\n\n\nclass Loader(importlib.abc.SourceLoader):\n \"\"\"Custom loader which rewrites the source before loading it.\"\"\"\n\n def __init__(self, orig_module_name, orig_loader, orig_filename,\n backend_name):\n self._backend_name = backend_name\n self._orig_module_name = orig_module_name\n self._orig_loader = orig_loader\n self._orig_filename = orig_filename\n\n def get_filename(self, fullname):\n del fullname\n return self._orig_filename\n\n def get_data(self, path):\n if DEBUG:\n print('Rewriting ', path)\n\n data = self._orig_loader.get_data(path).decode('utf-8')\n\n root_name = _root_name()\n\n if DEBUG:\n print('root_name ', root_name)\n\n data = re.sub(\n 'import {}'.format(root_name),\n 'import {}.dynamic.{}'.format(root_name, self._backend_name),\n data,\n )\n data = re.sub(\n 'from {}'.format(root_name),\n 'from {}.dynamic.{}'.format(root_name, self._backend_name),\n data,\n )\n data = re.sub(\n 'BACKEND = None',\n 'BACKEND = \\'{}\\''.format(self._backend_name),\n data,\n )\n data = _external_rewrites(self._backend_name, data)\n\n if DEBUG:\n print(data)\n print()\n return data.encode('utf-8')\n\n\nclass Finder(importlib.abc.MetaPathFinder):\n \"\"\"Custom finder for the dynamic rewrite system.\n\n It handles modules like `inference_gym.dynamic.`.\n \"\"\"\n # This is here so we can detect stale references to this class in\n # sys.meta_path.\n _INFERENCE_GYM_FINDER = True\n\n def find_spec(self, fullname, path, target=None):\n \"\"\"See base class.\"\"\"\n del target # We don't use this hint.\n root_name_comps = _root_name_comps()\n root_name = _root_name() + '.dynamic'\n\n if DEBUG:\n print('candidate: ', fullname, path)\n # Only handle things starting with .dynamic.\n if not fullname.startswith(root_name):\n return\n\n if DEBUG:\n print('fullname: ', fullname)\n print('path: ', path)\n\n # We cut out the leading components (including 'dynamic', hence the + 1),\n # leaving us with [, ...].\n module_name_comps = fullname.split('.')[len(root_name_comps) + 1:]\n\n if DEBUG:\n print('module_name_comps: ', module_name_comps)\n\n # This shouldn't really happen, but to be safe we don't handle this case\n # either. This would correspond to doing `import\n # inference_gym.dynamic.`, which doesn't need rewriting.\n if len(module_name_comps) < 2:\n return\n\n backend_name = module_name_comps[0]\n orig_module_name = '.'.join(root_name_comps + module_name_comps[1:])\n if DEBUG:\n print('backend: ', backend_name)\n print('orig_module_name: ', orig_module_name)\n # N.B. this will actually execute package __init__.py files. If those import\n # backend-specific modules, those imports will fail. That's why the\n # __init__.py files in question disable import errors using the\n # backends.util.silence_nonrewritten_import_errors utility.\n orig_spec = importlib.util.find_spec(orig_module_name)\n if orig_spec is None:\n raise ImportError('Cannot import ' + orig_module_name)\n is_package = bool(orig_spec.submodule_search_locations)\n orig_loader = orig_spec.loader\n # We use duck-typing here because we don't necesarily need this to be a\n # SourceFileLoader, just that it has this method.\n if not hasattr(orig_loader, 'get_data'):\n raise TypeError('{} has an unsupported loader: {}'.format(\n orig_module_name, orig_loader))\n\n spec = importlib.machinery.ModuleSpec(\n fullname,\n Loader(orig_module_name, orig_loader, orig_spec.origin, backend_name), # pylint: disable=abstract-class-instantiated\n origin=orig_spec.origin,\n is_package=is_package,\n )\n\n # We need to modify the spec after construction to set a few attributes.\n # This is allowed as per ModuleSpec docstring.\n if is_package:\n # Otherwise importing from packages fails to work.\n spec.submodule_search_locations = [\n '.'.join([path[0], module_name_comps[-1]])\n ]\n # Helps with pdb integration.\n spec.has_location = True\n # We don't cache these rewritten modules.\n spec.cached = False\n if DEBUG:\n print()\n return spec\n\n\ndef enable_backends():\n \"\"\"Enables the backends.\"\"\"\n if DEBUG:\n print('sys.meta_path: ', sys.meta_path)\n\n # We try to be robust to reloading this module, and remove the old instance of\n # the Finder from sys.meta_path.\n found = False\n i = 0\n for (i, finder) in enumerate(sys.meta_path):\n if hasattr(finder, '_INFERENCE_GYM_FINDER'):\n found = True\n break\n\n if found:\n sys.meta_path[i] = Finder()\n else:\n # We insert it at the beginning. This enables us to intercept the dynamic\n # modules before any other finder tries and (mistakenly) succeeds in somehow\n # handling them. This does force us to be careful about letting all the\n # regular modules to be handled by the regular finders via the early\n # returns.\n sys.meta_path.insert(0, Finder())\n\n\nenable_backends()\n","sub_path":"spinoffs/inference_gym/inference_gym/backends/rewrite.py","file_name":"rewrite.py","file_ext":"py","file_size_in_byte":9955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"396680584","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 8 16:19:36 2021\n\n@author: Admin\n\nTest if we need a 3channel mask for color --> yes we do\n\"\"\"\n\nimport numpy as np\nimport cv2\n\n\nimg_c = cv2.imread(\"colorimg_small.png\")\nimg_g = cv2.cvtColor(img_c,cv2.COLOR_BGR2GRAY)\n\nprint(\"shape \",img_c.shape)\ncv2.imshow(\"w\",img_c)\n\nscale = 10\n\ndim=(int(img_c.shape[1]*scale),int(img_c.shape[0]*scale))\n\nimg_2 = cv2.resize(img_c, dim, interpolation = cv2.INTER_AREA )\ncv2.imshow(\"w\",img_2)","sub_path":"simple_test_codes/cv2_bitwise_mask_colorVSgray.py","file_name":"cv2_bitwise_mask_colorVSgray.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"456332877","text":"import sys\nimport os\nimport math\n\n# MEM Base\nMEM_BASE = os.environ['CMSSW_BASE']+ \"/src/ttH_Htautau_MEM_Analysis/MEM\"\n\n# Math constants\nPI = math.pi\n\n# LHC beam energy (Gev)\nsqrtS = 13000\n\n\n\n# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n# Input files\n# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n\nInputType = \"PyRun2\"\n\nInputFileList = [\"ttH_Htautau_MEM_Analysis/MEM/EventDump_ttH.py\"]\n\n\n\n#treeName = \"HTauTauTree_2lSS\"\n\n\n# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n# Events\n# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\nmaxNbrOfEventsToRead = 2\nskipEvents = 0\n\n\n# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n# Random Number Generator\n# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\nflagSameRNG = True\n\n# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n# Computation / Run\n# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n\nflagTFLepTau = True \nflagTFHadTau = True\nflagTFFake = True\nflagTFMET = True\nflagTFJet1 = True\nflagTFJet2 = True\nflagTFBJet_leptop = True\nflagTFBJet_hadtop = True\nflagTF_fakelep = True\nflagTF_fakeleptau = True\nflagTFTop = True\nflagJac = True\nflagWME = True\n# Verbose Modes\nNoVerbose = 0\nResultLevel = 1 \nIntegrationLevel = 2 \nIntegrandLevel = 3 \n# Seclect verbose mode\nverbose = NoVerbose\n#logFileName = MEM_BASE + \"/python/small.log\"\n\n\n\n# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n# MC Integration\n# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\nnbrOfDimttH = 5\nnbrOfDimttZ = 5\nnbrOfDimttbar_DL = 5\nnbrOfDimttZ_Zll = 3\n\n\nnbrOfDimttH_miss = 7\nnbrOfDimttZ_miss = 7\nnbrOfDimttZ_Zll_miss = 5\n\n\nrunttZ_integration = True\nrunttZ_Zll_integration = True\nrunttbar_DL_fakelep_integration = True\n\nrun_missing_jet_integration = True\nforce_missing_jet_integration = False\nforce_missing_jet_integration_ifnoperm = True\n\n\n\nnbrOfPoints_ttH = 2500\n#nbrOfPoints_ttH = 10\nnbrOfPoints_ttZ = 2500\n#nbrOfPoints_ttZ = 10\nnbrOfPoints_ttbar_DL = 10000\n#nbrOfPoints_ttbar_DL = 10\nnbrOfPoints_ttZ_Zll = 500\n#nbrOfPoints_ttZ_Zll = 5\n\n\nnbrOfPoints_ttH_miss = 20000\n#nbrOfPoints_ttH_miss = 20\nnbrOfPoints_ttZ_miss = 20000\n#nbrOfPoints_ttZ_miss = 20\nnbrOfPoints_ttZ_Zll_miss = 5000\n#nbrOfPoints_ttZ_Zll_miss = 10\n\nnbrOfPermut_per_jet = 4\n\n# Integration boundaries \nphiNu_tlep = [ 0, 2*PI ]\ncosThetaNu_tlep = [-1.,1.]\nphiNu_ttau = [ 0, 2*PI ]\ncosThetaNu_ttau = [-1.,1.]\n \nuse_pT_TFJet = True\nCI_TFJet = 0.95 #Use 95% CI from the jet TF\nuse_top_compatibility_check = True\n\ninclude_hadrecoil = True\n\n#Missing jet parameters\neta_acceptance = 2.4\njet_radius = 0.4\ndR_veto_jet_lep = 0.4\nrel_iso_lep = 0.4\npT_cut = 25.\n\nphi_missing_jet = [ 0, 2*PI ]\ncosTheta_missing_jet = [-1.,1.]\n\n\n\n# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n# MadGraph 5\n# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\nMGParamCardFile = MEM_BASE+\"/bin/param_card.dat\"\n\n\n# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n# LHAPDF\n# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\nLHAPDFFile = \"cteq66\"\n","sub_path":"MEM/python/small_nomin_122016.py","file_name":"small_nomin_122016.py","file_ext":"py","file_size_in_byte":3374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"1142623","text":"import os\nimport random\nimport string\n\nimport requests\n\nBOT_TOKEN = os.environ['TELEGRAM_BOT_TOKEN']\nTELEGRAM_API_HOSTNAME = os.environ['TELEGRAM_API_HOSTNAME']\nTELEGRAM_BOT_API_URL = f'{TELEGRAM_API_HOSTNAME}bot{BOT_TOKEN}/'\n\nTELEGRAM_WEBHOOK_SECRET = os.environ['TELEGRAM_WEBHOOK_SECRET']\nTELEGRAM_WEBHOOK_URL = os.environ['TELEGRAM_WEBHOOK_HOSTNAME'] + TELEGRAM_WEBHOOK_SECRET\n\nCONSOLE_TITLE_DIVIDER = '\\n'\nCONSOLE_LINE_INDENT = '* '\n\n\ndef set_webhook():\n r = requests.post(TELEGRAM_BOT_API_URL + 'setWebhook', json={'url': TELEGRAM_WEBHOOK_URL})\n result = r.json()\n return str(result)\n\n\ndef delete_webhook():\n r = requests.get(TELEGRAM_BOT_API_URL + 'deleteWebhook')\n result = r.json()\n return str(result)\n\n\ndef get_webhook_info():\n r = requests.get(TELEGRAM_BOT_API_URL + 'getWebhookInfo')\n result = r.json()\n return str(result)\n\n\ndef generate_secret_key():\n candidate_characters = string.ascii_uppercase + string.ascii_lowercase + string.digits\n chosen_characters = random.sample(candidate_characters, 32)\n new_key = ''.join(chosen_characters)\n return new_key\n\n\nif __name__ == '__main__':\n print(CONSOLE_TITLE_DIVIDER + 'TELEGRAM BOT ADMIN')\n print(CONSOLE_LINE_INDENT + 'Telegram bot token:\\t' + BOT_TOKEN)\n print(CONSOLE_LINE_INDENT + 'Telegram API URL:\\t\\t' + TELEGRAM_BOT_API_URL)\n\n print(CONSOLE_TITLE_DIVIDER + 'WEBHOOK ADMIN')\n print(CONSOLE_LINE_INDENT + 'Webhook secret key:\\t\\t' + TELEGRAM_WEBHOOK_URL)\n print(CONSOLE_LINE_INDENT + 'Webhook URL:\\t\\t\\t\\t' + TELEGRAM_WEBHOOK_URL)\n # print(CONSOLE_LINE_INDENT + 'Set Webhook response:\\t\\t' + set_webhook())\n # print(CONSOLE_LINE_INDENT + 'Delete Debhook response:\\t' + delete_webhook())\n print(CONSOLE_LINE_INDENT + 'Webhook Info response:\\t' + get_webhook_info())\n # print(CONSOLE_LINE_INDENT + 'New key generated:\\t\\t' + generate_secret_key())\n","sub_path":"admin_functions.py","file_name":"admin_functions.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"292046257","text":"from api.db import stat_db, crawl_db, CrawlCollections, StatCollections, relation_db, RelationCollections\nimport time\nimport re\nfrom datetime import datetime\nimport pandas as pd\nimport numpy as np\n\n\ndef quote_graph(link_id):\n \"\"\"\n 单个btt帖子的用户关系图\n :param link_id:\n :return:\n \"\"\"\n start = time.time()\n\n # 加载单条帖子的所有评论\n cursor = crawl_db[CrawlCollections.BTT_COMMENT].find({'data.link_id': link_id})\n comment_df = pd.DataFrame([item['data'] for item in cursor], columns=['author', 'grade', 'quote_id', 'user_id', 'message_id'])\n comment_df['num'] = 1\n\n # 按照用户名分组,计算每个人评论的数量\n grouped_df = comment_df.groupby(['author', 'user_id', 'grade'], as_index=False).agg(np.sum)\n\n # 取评论数量前100位的用户\n filtered_df = grouped_df.sort_values(by='num', ascending=False)[:100]\n describe = grouped_df.describe()\n\n # 将评论数量按比例转换为size,其中评论最多的人size为100\n filtered_df['num'] = filtered_df['num'] * 100 / describe['num']['max']\n\n # 将过滤后的data frame和原来的数据进行连接操作,目的是找出各个用户之间的引用关系\n merged_df = pd.merge(comment_df, filtered_df, on=['user_id', 'author', 'grade'], how='inner')\n temp_relation_df = merged_df.dropna().groupby(['quote_id', 'user_id'], as_index=False).agg(np.sum)\n\n # 将temp_relation_df中的quote_id与原数据的message_id做连接,找出user_id和quote_user_id\n relation_df = pd.merge(temp_relation_df, comment_df, left_on='quote_id', right_on='message_id', how='inner')[['user_id_x', 'user_id_y', 'num_x']]\n relation_df.columns = ['target', 'source', 'size']\n filter_user_json = filtered_df.sort_values(by='grade').to_json(orient='records')\n relation_json = relation_df.to_json(orient='records')\n category_json = filtered_df.grade.value_counts().to_json()\n stat_db[StatCollections.BTT_USER_RELATION_STAT].find_one_and_update({'_id': link_id},\n {'$set': {'user': filter_user_json,\n 'relation': relation_json,\n 'categories': category_json}},\n upsert=True)\n end = time.time()\n print('analyze bitcointalk user completed used {0}, link_id= {1}'.format(end - start, link_id))\n\n\ndef comment_time_distribute(link_id):\n \"\"\"\n 单个btt帖子时间的日回复数量\n :param link_id:\n :return:\n \"\"\"\n start = time.time()\n\n comments = pd.DataFrame([item['data'] for item in crawl_db[CrawlCollections.BTT_COMMENT].find({'data.link_id': link_id})],\n columns=['time'])\n comments = comments.dropna()\n comments.time = comments['time'].apply(lambda x: datetime.fromtimestamp(x))\n comments.set_index(comments.time, inplace=True)\n comments['num'] = 1\n comments.drop('time', axis=1)\n df = comments.resample('D').sum().fillna(0)\n data = df.reset_index().to_json(orient='values')\n stat_db[StatCollections.BTT_LINK_TIME_DISTRIBUTE].find_one_and_update({'_id': link_id},\n {'$set': {\n 'data': data\n }},\n upsert=True)\n end = time.time()\n print('analyze comment time distribute used {0}, link_id= {1}'.format(end - start, link_id))\n\n\ndef search_and_stat_keyword(keywords):\n comments = crawl_db[CrawlCollections.BTT_COMMENT].find()\n keyword_collections = []\n for keyword in keywords:\n params = {}\n params['keyword'] = keyword\n params['data'] = []\n keyword_collections.append(params)\n print('获取评论...')\n\n # 从已有的comments中找出包含关键词的评论\n for comment in comments:\n try:\n text = comment['data']['content']\n for params in keyword_collections:\n if re.search(r'\\b{0}\\b'.format(params['keyword']), text, re.I) is not None:\n params['data'].append(comment)\n except Exception:\n pass\n\n for index, params in enumerate(keyword_collections):\n print('分析第{0}个keyword'.format(index))\n keyword_stat(params['data'], params['keyword'])\n print('第{0}个keyword分析结束'.format(index))\n\n\ndef keyword_stat(select_comments, keyword):\n \"\"\"\n 在已经获取的所有评论中找到包含了keyword的评论,按照用户的姓名分组。找出这个人最早提到这个关键词的时间。形成时间和用户activity的分布图\n :param keyword: 查找的关键词\n :param select_comments: 搜索出来的评论\n :return:\n \"\"\"\n\n # 将挑选出的评论加载到dataFrame中\n df = pd.DataFrame([item['data'] for item in select_comments],\n columns=['time', 'activity', 'author', 'link_id', 'user_id', 'grade'])\n df['num'] = 1\n\n # 将选出的评论按照用户名和等级分组,并对time这一列取最小值,num这一列取总和,activity这一列取最大值\n group = df.groupby(['author', 'grade', 'user_id'], as_index=False)\n grouped_df = group.agg({'time': np.min, 'num': np.sum, 'activity': np.max})\n\n # 提及人数\n user_count = grouped_df.index.size\n\n # 将grade这一列作为category类型\n d = grouped_df['grade'].astype('category')\n\n # 将time这一列转换为时间戳\n grouped_df['time'] = grouped_df['time'] * 1000\n\n # 按照num的比例算每个点的大小值,最大50,最小2\n max = grouped_df['num'].max()\n min = grouped_df['num'].min()\n if max != min:\n grouped_df['num'] = grouped_df['num'].map(lambda x: np.floor((x - min) / (max - min) * 48 + 2))\n else:\n grouped_df['num'] = 50\n\n # 调整dataFrame中列顺序,将time放在第一列,activity放在第二列,因为在画分布图的时候,第一列的书作为横坐标,第二列的值作为纵坐标\n activity = grouped_df['activity']\n time = grouped_df['time']\n grouped_df.drop(labels=['activity'], axis=1, inplace=True)\n grouped_df.drop(labels=['time'], axis=1, inplace=True)\n grouped_df.insert(0, 'activity', activity)\n grouped_df.insert(0, 'time', time)\n\n # 计算top30的排名\n top30 = grouped_df.sort_values(by='time')[:30]\n top30_json = top30.to_json(orient='values')\n\n # 将大的dataFrame按照等级拆分为小的dataFrame,作为多个series\n json_arr = []\n for grade in d.cat.categories:\n df = grouped_df[grouped_df['grade'] == grade]\n json = df.to_json(orient='values')\n json_arr.append({'data': json, 'grade': grade})\n stat_db[StatCollections.BTT_COMMENT_KEYWORD_STAT].find_one_and_update({'keyword': keyword},\n {'$set': {'data': json_arr,\n 'user_count': user_count,\n 'keyword': keyword,\n 'top30_data': top30_json}},\n upsert=True)\n\n\ndef link_stat_batch(func):\n \"\"\"\n 批量分析用户关系图和评论时间分布图的入口\n :return:\n \"\"\"\n aly_link = crawl_db[CrawlCollections.BTT_COMMENT].aggregate([{'$group': {'_id': '$data.link_id'}}])\n for item in aly_link:\n link_id = item['_id']\n if func == 'quote_graph':\n stat = stat_db[StatCollections.BTT_USER_RELATION_STAT].find_one({'_id': link_id})\n if stat is None:\n quote_graph(link_id)\n if func == 'comment_time_distribute':\n stat = stat_db[StatCollections.BTT_LINK_TIME_DISTRIBUTE].find_one({'_id': link_id})\n if stat is None:\n comment_time_distribute(link_id)\n\n\ndef user_history_stat():\n \"\"\"\n 用户历史足迹分析,找出用户在那些项目中回复的数量以及时间分布\n :return:\n \"\"\"\n count = 0\n now = datetime.now()\n # 将货币和ANN link的关联关系加载到data frame\n relation_btt = relation_db[RelationCollections.RELATION_CURRENCY_BTT].find({'ann': True})\n relation_df = pd.DataFrame([item for item in relation_btt], columns=['topic_id', 'currency_name'])\n\n # 获取数据库中所有的用户\n user_list = crawl_db[CrawlCollections.BTT_COMMENT].aggregate([{'$group': {'_id': '$data.user_id'}}])\n for user in user_list:\n count += 1\n if count % 100 == 0:\n print('success analyse count {0}'.format(count))\n user_id = user['_id']\n\n # 从数据库中查找用户分析过的数据,如果不为空则跳出循环\n stat_data = stat_db[StatCollections.BTT_USER_HISTORY_STAT].find_one({'_id': user_id})\n if stat_data is not None:\n if (now - stat_data['update_time']).seconds < 3600 * 24 * 7:\n if 'data' in stat_data['arr_data']:\n continue\n\n # 从数据库中加载该用户的所有评论\n df = pd.DataFrame(\n [item['data'] for item in crawl_db[CrawlCollections.BTT_COMMENT].find({'data.user_id': user_id})],\n columns=['time', 'author', 'user_id', 'link_id'])\n\n # 将关系data frame和\n merged_df = pd.merge(df, relation_df, left_on='link_id', right_on='topic_id', how='left')\n clean_merged_df = merged_df.dropna().drop('topic_id', axis=1)\n\n # 将数据按照currency name分组,获取每个currency的评论数量\n clean_merged_df['num'] = 1\n grouped_df = clean_merged_df.groupby(['link_id', 'currency_name'], as_index=False).agg({'num': np.sum})\n general_data = grouped_df.sort_values(by='num', ascending=False).to_json(orient='values')\n\n # 将用户的足迹按照currency name 分类, 获取评论分布图\n arr_data = []\n clean_merged_df['time'] = clean_merged_df['time'].apply(lambda x: datetime.fromtimestamp(x))\n clean_merged_df.set_index(clean_merged_df.time, inplace=True)\n clean_merged_df.drop('time', axis=1)\n d = clean_merged_df['currency_name'].astype('category')\n for currency_name in d.cat.categories:\n temp_df = clean_merged_df[clean_merged_df['currency_name'] == currency_name]\n resampled_df = temp_df.resample('D').sum().fillna(0)\n json_data = resampled_df.reset_index().to_json(orient='values')\n arr_data.append({'currency_name': currency_name, 'data': json_data})\n\n # 保存数据\n stat_db[StatCollections.BTT_USER_HISTORY_STAT].find_one_and_update({'_id': user_id},\n {'$set': {\n 'general_data': general_data,\n 'arr_data': arr_data,\n 'update_time': datetime.now()\n }}, upsert=True)\n\n\ndef set_ann_flag():\n \"\"\"\n 在relation_currency_btt中的关系添加一个标志位创世帖。数据来源于relation_currency_ann表中\n :return:\n \"\"\"\n ann_links = relation_db[RelationCollections.RELATION_CURRENCY_ANN].find()\n for item in ann_links:\n query = {'topic_id': item['topic_id'], 'currency_name': item['currency_name']}\n r = relation_db[RelationCollections.RELATION_CURRENCY_BTT].find_one(query)\n if r is None:\n relation_db[RelationCollections.RELATION_CURRENCY_BTT].insert_one({'topic_id': item['topic_id'], 'currency_name': item['currency_name'], 'ann': True})\n else:\n relation_db[RelationCollections.RELATION_CURRENCY_BTT].update_one(query, {'$set': {'ann': True}})\n\n\nif __name__ == '__main__':\n # link_stat_batch('quote_graph')\n # link_stat_batch('comment_time_distribute')\n # user_history_stat()\n # charleshoskinson / Jeremy Wood / founder / IOHK\n # search_and_stat_keyword(['Jeremy Wood', 'DFINITY', 'word2vec'])\n # comment_time_distribute('1365894')\n quote_graph('1365894')\n","sub_path":"api/common/analyzes/bitcointalk_analyzation.py","file_name":"bitcointalk_analyzation.py","file_ext":"py","file_size_in_byte":12554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"351007581","text":"import math\nfrom fractions import Fraction, gcd\n\nl, r, sol = Fraction(1, 3), Fraction(1, 2), 0\n\nfor d in range(4, 12001):\n\tn = math.ceil(l * d)\n\tf, i = Fraction(n, d), Fraction(1, d)\n\tif f == l:\n\t\tf += i\n\twhile f < r:\n\t\tif f.denominator == d:\n\t\t\tsol += 1\n\t\tf += i\nprint(sol)\n","sub_path":"Solution-073.py","file_name":"Solution-073.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"54636066","text":"import os\nimport re\nimport math\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport scipy.stats as st\n\nEARTH_RADIUS_KM = 6371.0\n\n#Función para eliminar las etiquetas de un string\ndef eliminarEtiquetas(texto):\n\tregExp = re.compile(\"<.*?>\") #Expresión regular que identifica las etiquetas\n\tnvoTexto = re.sub(regExp, \" \", texto) #El texto se \"limpia\" y se pasa a un nuevo string\n\treturn nvoTexto #Se retorna el string limpio\n\n#Converts degrees to radians\ndef degrees_to_radians(degrees):\n\treturn ( degrees * math.pi / 180.0 )\n\n\n#Haversine formula\ndef distance_km(lat1, lon1, lat2, lon2):\n\t#Conversion to radians\n\tlat1 = degrees_to_radians( lat1 )\n\tlon1 = degrees_to_radians( lon1 )\n\tlat2 = degrees_to_radians( lat2 )\n\tlon2 = degrees_to_radians( lon2 )\n\n\t#Computing terms based on the differences in longitude and latitud\n\tsin_delta_lat = math.sin( (lat2 - lat1) / 2.0 )\n\tsin_delta_lat *= sin_delta_lat;\n\t\n\tsin_delta_lon = math.sin( (lon2 - lon1) / 2.0 )\n\tsin_delta_lon *= sin_delta_lon\n\n\t#Apply formula and convert to KM\n\thav = ( sin_delta_lat + math.cos( lat1 ) * math.cos( lat2 ) * sin_delta_lon )\n\n\treturn 2.0 * EARTH_RADIUS_KM * math.asin( math.sqrt( hav ) )\n\n\n\nfuerzasPoliciacas = {} #Para guardar el área de cada fuerza policiaca\n\nruta = \"./PoliceForce_KML/\" #Ruta en la que se encuentran los archivos KML\narchivos = os.listdir(ruta) #Lista de archivos KML\narchivos.sort() #Se ordenan los archivos\n\nruta2 = \"./CrimesUK_2011_2017/\" #Ruta de los archivos principales\ndirectorios = os.listdir(ruta2) #lista los directorios que se encuentran dentro de la carpeta principal\n\n#Ciclo para recorrer los archivos. Para cada fuerza policiaca...\nfor f in archivos:\n\tnombreFuerza = os.path.splitext(f)[0] #Se obtiene el nombre de la fuerza policiaca\n\ttotalReportes = 0 #Contador de crímenes reportados por la fuerza\n\tarchivo = open(ruta + f) #Se abre el archivo \"f\" del directorio\n\n\tlatitudes = [] #Lista para guardar las latitudes\n\tlongitudes = [] #Lista para guardar las longitudes\n\n\ti = 0 #Contador de líneas\n\t#Ciclo para recorrer el archivo\n\tfor line in archivo:\n\t\t#Si se ha llegado a la línea 13 (la que contiene las coordenadas)\n\t\tif i == 13:\n\t\t\tcoordenadasTotales = eliminarEtiquetas(line).split() #Se eliminan las etiquetas de esa línea y las coordenadas se guardan en una lista\n\n\t\t\t#Se recorre la lista de coordenadas\n\t\t\tfor coordenadas in coordenadasTotales:\n\t\t\t\tcoordenadas2 = coordenadas.split(\",\") #El string de las coordenadas se separa para guardar por separado la latitud y la longitud \n\t\t\t\tlongitudes.append(float(coordenadas2[0])) #Se guarda la longitud actual en valor decimal\n\t\t\t\tlatitudes.append(float(coordenadas2[1])) #Se guarda la latitud actual en valor decimal\n\n\t\t\tlongitudes.sort() #Se ordenan las longitudes\n\t\t\tlatitudes.sort() #Se ordenan las latitudes\n\t\t\n\t\t\tx1, x2 = latitudes[0], latitudes[-1] #Se sacan los puntos de menor y mayor latitud\n\t\t\ty1, y2 = longitudes[0], longitudes[-1] #Se sacan los puntos de menor y mayor longitud\n\t\t\t\n\t\t\tbase = distance_km(x1, y1, x2, y1) #Se saca la base del área total\n\t\t\taltura = distance_km(x1, y1, x1, y2) #Se saca la altura del área total\n\t\t\tarea = round(base * altura, 2) #Se calcula el área (redondeada a 2 dígitos después del punto)\n\n\t\t\tfuerzasPoliciacas.update({nombreFuerza : {\"area\": area}}) #Se agrega al diccionario el nombre de la fuerza y su área\n\n\t\t\t#Ciclo para recorrer los archivos de reportes principales\n\t\t\tfor f2 in directorios:\n\t\t\t\trutaSecundaria = ruta2+f2+\"/\" #se prepara la ruta donde se buscarán los archivos\n\n\t\t\t\t#se recorren todos los archivos encontrados en ese directorio\n\t\t\t\tfor e in os.listdir(rutaSecundaria):\n\t\t\t\t\t#Se comprueba que el archivo sea el de los reportes de la fuerza policiaca actual\n\t\t\t\t\tif e.find(nombreFuerza) != -1:\n\t\t\t\t\t\tarchivo = open(rutaSecundaria+e) #se abre el archivo\n\t\t\t\t\t\t\n\t\t\t\t\t\tcLine = 0 #variable para que no cuente la primera línea, que es la del encabezado de cada archivo\n\n\t\t\t\t\t\t#Se recorre el archivo\n\t\t\t\t\t\tfor line in archivo:\n\t\t\t\t\t\t\tif(cLine!=0):\n\t\t\t\t\t\t\t\ttotalReportes += 1 #Se aumenta el número de crímenes reportados\n\t\t\t\t\t\t\tcLine+=1\n\t\t\t\t\n\t\t\t\t\t\tbreak #Se rompe el ciclo, ya no es necesario verificar los demás archivos\n\n\t\t\tbreak #Se rompe el ciclo, ya no es necesario verificar los demás archivos\n\n\t\ti += 1 #Se aumenta el contador\n\n\tfuerzasPoliciacas[nombreFuerza].update({\"totalReportes\" : totalReportes}) #Se agrega al diccionario en la fuerza actual el total de reportes\n\nresultados = open(\"dataset-2.csv\", \"a\") #Se abre el archiv\n\n\n#Se asignan los resultados\nfor fuerza in fuerzasPoliciacas:\n\tfila = fuerza + \",\" + str(fuerzasPoliciacas[fuerza][\"totalReportes\"]) + \",\" + str(fuerzasPoliciacas[fuerza][\"area\"]) + \"\\n\"\n\tresultados.write(fila)\n\tprint(fila)\n\nresultados.close() #Se cierra el archivo\n\n\n\n","sub_path":"dataset-2.py","file_name":"dataset-2.py","file_ext":"py","file_size_in_byte":4756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"455375677","text":"import cv2\nimport numpy as np\nfrom numba import njit\nimport os\nfrom pathlib import Path\nimport argparse\nfrom scipy import fftpack\nfrom PIL import Image, ImageDraw\nfrom tqdm import tqdm\nimport time\n\ndef profiler(start_time, end_time, source_np):\n h, w = source_np.shape\n time_image = end_time - start_time\n \n return (time_image, time_image/h/w * 10**6)\n\ndef read_image(path):\n image_name = path.split(\"/\")[-1].split(\".\")[0]\n return cv2.imread(path, 0), image_name\n\n\n@njit\ndef find_skew(x, mu, sigma):\n return np.mean(np.power((x - mu) / sigma, 3))\n\n\n@njit\ndef denoise(image, block_size):\n h, w = image.shape\n sigma = []\n for i in range(h // block_size):\n for j in range(w // block_size):\n block = image[i * block_size: (i + 1) * block_size,\n j * block_size: (j + 1) * block_size]\n sigma.append(block.std())\n nu_2 = np.median(np.array(sigma)**2)\n\n result = np.zeros((h // block_size * block_size, w // block_size * block_size))\n for i in range(h // block_size):\n for j in range(w // block_size):\n block = image[i * block_size: (i + 1) * block_size,\n j * block_size: (j + 1) * block_size]\n block_mean = np.mean(block)\n block_std = np.std(block)\n result[i * block_size: (i + 1) * block_size,\n j * block_size: (j + 1) * block_size] = block_mean + ((block_std ** 2 - nu_2) * (block - block_mean) / (block_std ** 2))\n return result\n\n\n@njit\ndef find_t(block, image_mean, bin_type):\n mu = np.mean(block)\n sigma = np.std(block)\n\n if bin_type == \"sauvola\":\n k = 0.2\n R = 128\n return mu * (1 + k * (sigma / R - 1))\n elif bin_type == \"wolf\":\n k = 0.25\n R = 100\n m = np.min(block)\n return (1 - k) * mu + k * m + k * sigma / R * (mu - m)\n elif bin_type == \"2018\":\n k = 0.2\n R = 100\n return (image_mean + np.max(block)) / 2 * (1 + k * (sigma/R-1))\n elif bin_type == \"skew\":\n k = 0.02\n R = 100\n skew = find_skew(block, mu, sigma)\n return mu * (1 + k * skew * (1 - skew/R))\n\n\n@njit\ndef binarization(image, block_size, bin_type):\n h, w = image.shape\n image_mean = np.mean(image)\n result = np.zeros((h // block_size * block_size, w // block_size * block_size))\n for i in range(h // block_size):\n for j in range(w // block_size):\n block = image[i * block_size: (i + 1) * block_size,\n j * block_size: (j + 1) * block_size]\n T = find_t(block, image_mean, bin_type)\n result[i * block_size: (i + 1) * block_size,\n j * block_size: (j + 1) * block_size] = image[i * block_size: (i + 1) * block_size,\n j * block_size: (j + 1) * block_size] > T\n return result\n\n\ndef get_args():\n \"\"\"Arguments parser.\"\"\"\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument('--imgs_path', required=True,\n help='input images path')\n parser.add_argument('--save_dir', type=str, required=True,\n help='save dir path')\n parser.add_argument('--block_size', type=int, default=50,\n help='Block size for patterns.')\n parser.add_argument('--binarization_type', type=str, choices=[\"sauvola\", \"2018\", \"wolf\", \"skew\"],\n help='type of binarization.')\n return parser.parse_args()\n\n\ndef save_result(img, save_path, image_name):\n image_dir = Path(save_path)\n image_dir.mkdir(exist_ok=True, parents=True)\n\n cv2.imwrite(os.path.join(save_path, f\"{image_name}.tiff\"), img)\n\n\ndef low_pass_filter(img):\n fft1 = fftpack.fftshift(fftpack.fft2(img))\n x, y = img.shape\n e_x, e_y = 10, 10\n bbox = ((x / 2) - (e_x / 2), (y / 2) - (e_y / 2), (x / 2) + (e_x / 2), (y / 2) + (e_y / 2))\n\n low_pass = Image.new(\"L\", (img.shape[0], img.shape[1]), color=0)\n\n draw1 = ImageDraw.Draw(low_pass)\n draw1.ellipse(bbox, fill=1)\n\n low_pass_np = np.array(low_pass)\n # multiply both the images\n filtered = np.multiply(fft1, low_pass_np.T)\n\n # inverse fft\n ifft2 = np.real(fftpack.ifft2(fftpack.ifftshift(filtered)))\n ifft2 = np.maximum(0, np.minimum(ifft2, 255))\n return ifft2.astype(np.uint8)\n\n\ndef contrast_adjustment(img):\n hist, bins = np.histogram(img.flatten(), 256, [0, 256])\n cdf = hist.cumsum()\n cdf_m = np.ma.masked_equal(cdf, 0)\n cdf_m = (cdf_m - cdf_m.min()) * 255 / (cdf_m.max() - cdf_m.min())\n cdf = np.ma.filled(cdf_m, 0).astype('uint8')\n return cdf[img]\n\n\ndef main():\n args = get_args()\n pathes = [os.path.join(args.imgs_path, image_path) for image_path in os.listdir(args.imgs_path)]\n for image_path in tqdm(pathes):\n img, image_name = read_image(image_path)\n img_c = contrast_adjustment(img)\n img_c = np.clip(img_c, 0, 255)\n img_c = binarization(img_c.astype(np.float64), args.block_size, args.binarization_type)\n start_time = time.time()\n img = binarization(img.astype(np.float64), args.block_size, args.binarization_type)\n end_time = time.time()\n time_image, time_mp = profiler(start_time, end_time, img)\n print(\"time for image {}s time for mp {}s\".format(time_image, time_mp))\n save_result((255 * img).astype(\"uint\"), args.save_dir, image_name)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"binarization/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"85286162","text":"from django.http import HttpResponse, JsonResponse\n\nfrom newsletter.models import Join\nfrom newsletter.utils import SendSubscriberMail\n\n\ndef subscribe(request):\n if request.POST:\n email = request.POST['email_id']\n email_qs = Join.objects.filter(email=email)\n if email_qs.exists():\n data = {\"status\": \"404\"}\n return JsonResponse(data)\n else:\n Join.objects.create(email=email)\n SendSubscriberMail(email)\n return HttpResponse(\"/\")","sub_path":"newsletter/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"162873801","text":"# coding=utf-8\nimport numpy as np\nfrom matplotlib import cm\nfrom MachineLearn.Classes import Experiment,DataSet, Data\n\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import KFold\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense\nfrom keras.optimizers import *\nfrom keras.utils import to_categorical\nfrom rbflayer import RBFLayer, InitCentersRandom\nfrom sklearn.preprocessing import LabelBinarizer\nimport matplotlib.pyplot as plt\n\nfrom T6_2.kmeans_initializer import InitCentersKMeans\n\nCOLOR = cm.rainbow(np.linspace(0, 1, 5))\nLEARNING_RATE = 0.1\nepochs = 300\nK_FOLD = 3\nGRID_NEURON = [20, 15, 10, 5]\nGRID_B = [.25, .5, .75, 1]\n_OPTIMIZER = RMSprop(learning_rate=LEARNING_RATE)\n\noExp = Experiment()\n\n\noDataSet = DataSet()\nbase = np.loadtxt(\"Datasets/measurements.csv\", usecols=range(7), delimiter=\",\")\nclasses = np.loadtxt(\"Datasets/measurements.csv\", usecols=-1, delimiter=\",\")\n\nfor x, y in enumerate(base):\n oDataSet.add_sample_of_attribute(np.array(list(np.float32(y)) + [classes[x]]))\noDataSet.attributes = oDataSet.attributes.astype(float)\noDataSet.normalize_data_set()\noDataSet.labels = np.array([classes]).T\n\n\nfor j in range(10):\n slices = KFold(n_splits=K_FOLD, shuffle=True)\n oData = Data(1, 31, samples=50)\n indices = np.arange(oDataSet.attributes.shape[0])\n np.random.shuffle(indices)\n oData.Testing_indexes = indices[int(oDataSet.attributes.shape[0] * 0.85):]\n oData.Training_indexes = indices[:int(oDataSet.attributes.shape[0] * 0.85)]\n\n grid_result = np.zeros((len(GRID_NEURON), len(GRID_B), K_FOLD))\n for g1, g_param in enumerate(GRID_NEURON):\n for g2, g2_param in enumerate(GRID_B):\n k_slice = 0\n for train, test in slices.split(oData.Training_indexes):\n model = Sequential()\n rbflayer = RBFLayer(g_param,\n initializer=InitCentersRandom(oDataSet.attributes[oData.Training_indexes[train]]),\n betas=g2_param,\n input_shape=(base.shape[1],))\n model.add(rbflayer)\n model.add(Dense(1))\n model.compile(loss='mse',\n optimizer=_OPTIMIZER)\n\n model.fit(oDataSet.attributes[oData.Training_indexes[train]],\n oDataSet.labels[oData.Training_indexes[train]],\n batch_size=50,\n epochs=epochs,\n verbose=0)\n\n y_pred = model.predict(oDataSet.attributes[oData.Training_indexes[test]])\n y_true = oDataSet.labels[oData.Training_indexes[test]]\n grid_result[g1, g2, k_slice] = mean_squared_error(y_true, y_pred)\n k_slice += 1\n print(grid_result)\n best_p = GRID_NEURON[np.unravel_index(np.argmin(np.mean(grid_result, axis=2)), grid_result.shape[:2])[0]]\n best_b = GRID_B[np.unravel_index(np.argmin(np.mean(grid_result, axis=2)), grid_result.shape[:2])[1]]\n\n model = Sequential()\n rbflayer = RBFLayer(best_p,\n initializer=InitCentersRandom(oDataSet.attributes[oData.Training_indexes]),\n betas=best_b,\n input_shape=(base.shape[1],))\n\n model.add(rbflayer)\n model.add(Dense(1))\n model.compile(loss='mse',\n optimizer=_OPTIMIZER)\n model.fit(oDataSet.attributes[oData.Training_indexes],\n oDataSet.labels[oData.Training_indexes],\n batch_size=50,\n epochs=epochs,\n verbose=1)\n\n y_pred = model.predict(oDataSet.attributes[oData.Testing_indexes])\n y_true = oDataSet.labels[oData.Testing_indexes]\n\n model.save('model.h5')\n myArr = None\n with open(\"model.h5\", \"rb\") as binaryfile:\n myArr = bytearray(binaryfile.read())\n oData.model = myArr, model.history.history['loss']\n oData.params = {\"k_fold\": K_FOLD, \"GRID_RESULT\": grid_result, \"GRID_VALUES\": (best_b,best_p), \"LEARNING RATE\": LEARNING_RATE,\n \"EPOCHS\": epochs, \"MSE\": mean_squared_error(y_true, y_pred),\n \"RMSE\": np.sqrt(mean_squared_error(y_true, y_pred))}\n\n oDataSet.append(oData)\noExp.add_data_set(oDataSet,\n description=\" Experimento Consumo Gasolina MLP 20 realizaçoes.\".format())\noExp.save(\"Objects/EXP02_3_LP_20.gzip\".format())\n","sub_path":"T6_2/Dts_3_2.py","file_name":"Dts_3_2.py","file_ext":"py","file_size_in_byte":4423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"440294262","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\ndef load_sand_data(station_number):\n #sand_data_frame = pd.read_csv('../../raw_data/10Hz/station' + str(station_number) + '_10Hz.dat', sep='\\t', header=None, index_col=False, usecols=range(1,3)); # reason for usecols is because of the specific formant of the 10Hz sand data!\n sand_data_frame = pd.read_csv('../filtered_data/data_thresh_01/station' + str(station_number) + '.dat', sep = '\\t', header=None, index_col=False);\n return sand_data_frame\n\ndef load_wind_data(station_number):\n wind_data_frame = pd.read_csv('../../data_exploration/wind_scalar/scalar_binned_averages/station' + str(station_number) + '.dat', sep = '\\t', header=None, index_col=False);\n return wind_data_frame\n\ndef plot_histograms(poisson1, poisson2, poisson3):\n plt.hist(poisson1, 50, normed = 0, histtype = 'bar', log = 0, facecolor='blue', alpha=0.25)\n plt.hist(poisson2, 50, normed = 0, histtype = 'bar', log = 0, facecolor='red', alpha=0.25)\n plt.hist(poisson3, 50, normed = 0, histtype = 'bar', log = 0, facecolor='green', alpha=0.25)\n plt.xlabel('')\n plt.ylabel('')\n plt.title('')\n plt.savefig('test.eps')\n plt.clf()\n\n\n\nstation_number = 7;\n\nsand_data_frame = load_sand_data(station_number);\nsand_data_array = sand_data_frame;\n#print(np.mean(sand_data_array))\n#print(sand_data_frame.mean())\n\n\nmean1 = 10.4;\nmean2 = 4;\nmean3 = 0.00767;\npoisson1 = np.random.poisson(mean1,10000)\npoisson2 = np.random.poisson(mean2,10000)\npoisson3 = np.random.poisson(mean3,10000)\nplot_histograms(poisson3, poisson3, poisson3)\n","sub_path":"master_scripts/poisson/poisson.py","file_name":"poisson.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"653313079","text":"# -*- encoding: utf-8 -*-\n\nfrom invoke import Collection, run, task\n\n\n@task\ndef build():\n print('Building!')\n\n\n@task\ndef hi(name):\n print('Hi %s!' % name)\n\n\n@task\ndef service_manager():\n service('services.manager')\n\n\n@task\ndef service(name):\n config_command = \"--config ./project/nameko_config.yaml\"\n service_command = 'nameko run %s %s' % (config_command, name)\n run(\n \"{}\".format(\n service_command\n )\n )\n\n\nns = Collection('service')\nns.add_task(service_manager, name='run_manager')\n","sub_path":"tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"380534806","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\nfrom pyglet.gl import *\n\nimport math\n\nfrom pymunk import Vec2d\nfrom lightshader import LightShader\n\n\nshader = None\ndef get_shader():\n global shader\n if shader:\n return shader\n shader = LightShader()\n shader.create_program()\n return shader\n\n\nclass Light():\n def __init__(self, position, radius=600, depth=0.0, color=[1.0, 1.0, 1.0, 1.0]):\n self.position = position\n self.depth = depth\n self.radius = radius\n self.source_radius = 5\n self.color = color\n\n def outer_vector(self, edge, step):\n cv = Vector2((self.position.x - edge.x), \\\n (self.position.y - edge.y))\n\n use_negative = False\n if self.position.x < edge.x:\n use_negative = True\n\n perp_vec = Vector2((self.position.x - edge.x), \\\n (self.position.y - edge.y))\n perp_vec.normalize()\n if step == 1:\n if use_negative:\n perp_vec *= -self.source_radius\n perp_vec.rotate((math.pi*2/4.0))\n else:\n perp_vec *= self.source_radius\n perp_vec.rotate(-(math.pi*2/4.0))\n else:\n if use_negative:\n perp_vec *= -self.source_radius\n perp_vec.rotate(-(math.pi*2/4.0))\n else:\n perp_vec.rotate((math.pi*2/4.0))\n perp_vec *= self.source_radius\n cv = Vector2((self.position.x + perp_vec.x) - edge.x, (self.position.y + perp_vec.y) - edge.y)\n cv *= -1\n\n cv.normalize()\n return cv * self.radius * 10\n\n def inner_vector(self, edge, step):\n cv = Vector2((self.position.x - edge.x), \\\n (self.position.y - edge.y))\n\n use_negative = False\n if self.position.x < edge.x:\n use_negative = True\n\n perp_vec = Vector2((self.position.x - edge.x), \\\n (self.position.y - edge.y))\n perp_vec.normalize()\n if step == 1:\n if use_negative:\n perp_vec *= -self.source_radius\n perp_vec.rotate(-(math.pi*2/4.0))\n else:\n perp_vec.rotate((math.pi*2/4.0))\n perp_vec *= self.source_radius\n else:\n if use_negative:\n perp_vec *= -self.source_radius\n perp_vec.rotate((math.pi*2/4.0))\n else:\n perp_vec *= self.source_radius\n perp_vec.rotate(-(math.pi*2/4.0))\n\n cv = Vector2((self.position.x + perp_vec.x) - edge.x, (self.position.y + perp_vec.y) - edge.y)\n cv *= -1\n\n cv.normalize()\n return cv * self.radius * 10\n\n def _render_source(self):\n glBegin(GL_TRIANGLE_FAN)\n\n # Color\n glColor4f(1.0, 1.0, 1.0, 1.0)\n glVertex3f(self.position.x, self.position.y, self.depth)\n\n angle = 0\n while angle <= math.pi * 2:\n glVertex3f(self.source_radius * math.cos(angle) + self.position.x,\n self.source_radius * math.sin(angle) + self.position.y,\n self.depth)\n angle += math.pi * 2 / 12.0\n glVertex3f(self.position.x + self.source_radius, self.position.y,\n self.depth)\n\n glEnd()\n\n def render(self, camera):\n shader = get_shader()\n shader.enable()\n shader.set_state(self.color)\n \n position = self.position - camera.position\n glPushMatrix()\n glTranslated(position.x, position.y, 0)\n glScaled(self.radius, self.radius, 0)\n glBegin(GL_QUADS)\n glVertex3f(-1.0, -1.0, self.depth)\n glVertex3f(1.0, -1.0, self.depth)\n glVertex3f(1.0, 1.0, self.depth)\n glVertex3f(-1.0, 1.0, self.depth)\n glEnd()\n glPopMatrix()\n \n shader.disable()\n \n def update(self, dt):\n pass\n \nclass BindableLight(Light):\n def __init__(self, target, radius=600, depth=0.0, color=[1.0, 1.0, 1.0, 1.0]):\n self.target = target\n Light.__init__(self, self.target.center.clone(), radius, depth, color)\n \n def update(self, dt):\n self.position = self.target.center.clone()","sub_path":"graphics/lighting/light.py","file_name":"light.py","file_ext":"py","file_size_in_byte":4204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"270148908","text":"from django.shortcuts import render, redirect, HttpResponse\nfrom django.utils.crypto import get_random_string\n\ndef index(request):\n return render(request,'word_app/index.html')\n\ndef r_word(request):\n if 'count' in request.session:\n request.session['count'] += 1\n else:\n request.session['count'] = 1\n \n random_word = get_random_string(length=14)\n word = {\n 'random_word': random_word\n }\n print(random_word)\n return render(request, 'word_app/index.html', word)\n\ndef reset(request):\n request.session.clear()\n return redirect('/')\n\n","sub_path":"django/django_intro/random_word/apps/word_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"40165612","text":"# coding: utf-8\n# prepreocess conv\n\nimport sys\nimport csv\n\n\ndef preprocess_yml(f):\n data = f.readlines()[3:]\n ques = [data[i][4:].strip() for i in range(len(data))]\n yield ques\n\n\n\ndef preprocess_conv(f):\n ret = []\n for line in f.readlines():\n if line.strip() != \"E\":\n ret.append(line[1:].strip())\n if line.strip() == \"E\" and len(ret) > 0:\n # yield [[x for i, x in enumerate(ret) if i%2 == 0], [x for i, x in enumerate(ret) if i%2 == 1]]\n yield ret\n ret = []\n\n # E as an ending\n # pass\n\n\ndef preprocess_conv_fenzi(f):\n ret = []\n for line in f.readlines():\n if line.strip() != \"E\":\n ret.append(line[1:].strip().replace(\"/\", \"\"))\n if line.strip() == \"E\" and len(ret) > 0:\n # yield [[x for i, x in enumerate(ret) if i%2 == 0], [x for i, x in enumerate(ret) if i%2 == 1]]\n yield ret\n ret = []\n\n # E as an ending\n # pass\n\n\ndef preprocess_qingyun(f):\n for line in f.readlines():\n conv = line.strip().split(\"|\")\n conv = [x.strip() for x in conv]\n yield conv\n\n\ndef preprocess_qa(f):\n ret = []\n for line in f:\n q, a = line.strip().split(\"\\t\")\n if len(ret) == 0:\n ret.append(q)\n ret.append(a)\n else:\n if ret[-1] == q:\n ret.append(a)\n else:\n yield ret\n ret = []\n\ndef preprocess_unknown(f):\n ret = []\n i = 0\n for line in f:\n ret.append(line.strip())\n if i % 2 != 0:\n yield ret\n ret = []\n i = 0 # 防止溢出\n i += 1\n\n\ntail_name_func = {\n \"conv\": preprocess_conv,\n \"conv_fenzi\": preprocess_conv_fenzi,\n \"qa\": preprocess_qa,\n \"qingyun\": preprocess_qingyun,\n \"yml\": preprocess_yml,\n}\n\n\nif __name__ == \"__main__\":\n f = open(\"E:\\PySpace\\Amadeus\\Amadeus\\data\\yuliao\\\\ai.yml\", encoding=\"utf-8\")\n for x in preprocess_yml(f):\n print(x)\n","sub_path":"Amadeus/data/yuliao_process.py","file_name":"yuliao_process.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"518268391","text":"from pathlib import Path\nparent_dir = Path(__file__).parent\nfile_name = Path(__file__).stem\n\nimport sys\nsys.stdin = open(f\"{parent_dir}\\{file_name} input.txt\")\ninput = sys.stdin.readline\n\n\n\"\"\"\n* 구현 문제 \n <- 그리디 X, DP X, 탐색 X\n <- 매 단계마다 다양한 상황이 주어지기 때문\n\n0. 큰 수 -> L, R 경계값만 필요\n\n1. 추가 \n -> 항상 좌측 빈 방부터\n -> 항상 좌측부터 찾아야 함\n -> 방 시작 번호 기준, 오름차순 '정렬' 필요 \n -> 정렬 (혹은 연결 리스트)\n\n2. 삭제\n -> 시간 순으로 찾음\n -> 추가할 때마다 위치 변해서\n 위치 인덱스 연동은 불가\n -> 그냥 '순회' 필요\n\"\"\"\n\nN, Q = map(int, input().split())\nrooms = []\nroom_count = 1\n\nfor _ in range(Q):\n task, x, y = input().split()\n if task == 'new':\n people = int(x)\n needed = int(y)\n next_left = prev_right = 0\n\n # 현재 방 끝 번호 ~ 다음 방 시작 번호 간격이 \n # 요구되는 방의 크기보다 크면 됨.\n for room in rooms:\n next_left = room[0]\n if next_left - prev_right > needed:\n break\n prev_right = room[1]\n \n # 끝까지 돌았는데도 요구를 충족 못 시키면 넘김.\n if N - prev_right < needed:\n print('REJECTED')\n continue\n\n # 현재 방 다음 ~ 필요한 만큼. 다른 값들도 추가\n rooms.append([prev_right + 1, prev_right + needed, people, room_count])\n # 방 시작 순서로 정렬!!!\n rooms.sort()\n room_count += 1\n\n print(prev_right + 1, prev_right + needed)\n \n elif task == 'in':\n room_num = int(x)\n people = int(y)\n\n # 맞는 방 번호 찾아서 사람 추가\n for room in rooms:\n if room[3] == room_num:\n room[2] += people\n break\n \n elif task == 'out':\n room_num = int(x)\n people = int(y)\n isEmpty = False\n\n # 맞는 방 번호 찾아서 사람 빼기\n for i in range(len(rooms)):\n if rooms[i][3] == room_num:\n rooms[i][2] -= people\n # 0이 되면 방 비워야 함\n if rooms[i][2] == 0:\n isEmpty = True\n break\n\n # 0이었던 경우 방 비우기\n if isEmpty:\n left, right, people, room_num = rooms.pop(i)\n print(f'CLEAN {left} {right}')\n","sub_path":"신인호/1028 문제풀이/16738. 초특가 숭놀자.py","file_name":"16738. 초특가 숭놀자.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"494480510","text":"n, ans = int(input()), 0\na, b, c = [False]*n, [False]*(2*n-1), [False]*(2*n-1)\n\ndef solve(i):\n global ans\n\n if i == n:\n ans += 1\n return\n \n for j in range(n):\n\n if a[j] == False and b[i+j] == False and c[i-j+n-1] == False :\n\n a[j] = b[i+j] = c[i-j+n-1] = True\n\n solve(i+1)\n\n a[j] = b[i+j] = c[i-j+n-1] = False # 해제\n\nsolve(0)\nprint(ans)\n\n\n# 백트래킹, 가지치기, 경우를 검사할때, 불가하다 판단되면 그쪽 가지는 폐쇄(가지치기) 시키고 다음 가지로 넘어가서 검사함.\n# https://idea-sketch.tistory.com/29\n# https://rebas.kr/761\n\n# N = 4일때,\n# i, j / row ,column\n\n# i = 0 , j = 0 일때부터 시작\n# i = 1, j = 0~3 중 조건에 맞는 것만 검사\n\n# 조건에 맞는 i = 1, j=2 은 그 이후\n\n# i = 2, j = 0~ 3 로 도약,\n# 하지만 , i = 2, j = 0~ 3 인 경우 모두 불가\n# a[j] = b[i+j] = c[i-j+n-1] = False 로 True를 False로 해제시킴(F-> 될것이라고 예상하고 T로 바꿈, T-> 불가하다고 판정나면 -> F (해제 시킴))\n# 따라서 i = 0 , j = 0 / i = 1, j = 2 이 가지는 불가\n\n# i = 1, j = 0~3 중 다음 조건 i = 1, j = 3 검사,\n\n# i = 4가 되어 모든 행(row)의 검사가 통과 그러면, result += 1, 하나의 조건을 만족하는 경우(case,instance, 이 가지는 행을 하나씩 덤어가서, 끝까지 같을때까지도 조건 만족) 가 생김,\n\n# 이게 i =0, j =0 의 '한 사이클' 이 끝난 경우//\n\n# 다음은 i = 0, j = 1 => '한 사이클'\n# 그 다음은 i = 0, j = 2 => '한 사이클'\n# 그 다음은 i = 0, j = 3 => '한 사이클'\n\n# 총 4개의 '큰 사이클'\n\n# 다 끝나면, global result(모든조건을 만족하고 살아남은 가지의 갯수, 정답) 를 출력\n\n\n","sub_path":"BoJ/BoJ.9663.py","file_name":"BoJ.9663.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"476082585","text":"from simtk import openmm, unit\nfrom simtk.openmm import app\nimport numpy as np\nfrom openmmtools.integrators import LangevinIntegrator\nimport argparse\nimport time\nimport progressbar\n\nparser = argparse.ArgumentParser()\nparser.add_argument('model_index', type=int)\nargs = parser.parse_args()\nmodel_index = args.model_index\n\nffxml_filenames = ['amber99sbildn.xml', 'tip3p.xml']\n\npressure = 1.0 * unit.atmospheres\ntemperature = 450.0 * unit.kelvin\ncollision_rate = 1.0 / unit.picoseconds\ntimestep = 5.0 * unit.femtoseconds\nhydrogen_mass = 3 * unit.amu\nsplitting = 'V R O R V'\nnsteps = 500 # 2.5 ps\nniterations = 4000 # 10 ns\n\nequilibrated_pdb_filename = '%s/equilibrated_hmr_600K.pdb' % model_index\nsystem_xml_filename = '%s/system_hmr_600K.xml' % model_index\nintegrator_xml_filename = '%s/integrator_hmr_600K.xml' % model_index\nstate_xml_filename = '%s/state_hmr_600K.xml' % model_index\n\n# Read equilibrated pdb\npdb_filename = '%s/equilibrated.pdb' % model_index\nprint('Loading %s' % pdb_filename)\npdb = app.PDBFile(pdb_filename)\n\nprint(\"Loading forcefield: %s\" % ffxml_filenames)\nforcefield = app.ForceField(*ffxml_filenames)\n\n# Create the system\nprint('Creating OpenMM System...')\nsystem = forcefield.createSystem(pdb.topology, nonbondedMethod=app.PME, constraints=app.HBonds, removeCMMotion=False, hydrogenMass=hydrogen_mass)\n\n# Add a barostat\nprint('Adding barostat...')\nbarostat = openmm.MonteCarloBarostat(pressure, temperature)\nsystem.addForce(barostat)\n\n# Serialize integrator\nprint('Serializing integrator to %s' % integrator_xml_filename)\nintegrator = LangevinIntegrator(temperature, collision_rate, timestep, splitting)\nwith open(integrator_xml_filename, 'w') as outfile:\n xml = openmm.XmlSerializer.serialize(integrator)\n outfile.write(xml)\n \n# Prepare context\nprint('Preparing context...')\ncontext = openmm.Context(system, integrator)\ncontext.setPositions(pdb.positions) \n\n# Equilibrate\nprint('Equilibrating...')\ninitial_time = time.time()\nfor iteration in progressbar.progressbar(range(niterations)):\n integrator.step(nsteps)\nelapsed_time = (time.time() - initial_time) * unit.seconds\nsimulation_time = niterations * nsteps * timestep\nprint(' Equilibration took %.3f s for %.3f ns (%8.3f ns/day)' % (elapsed_time / unit.seconds, simulation_time / unit.nanoseconds, simulation_time / elapsed_time * unit.day / unit.nanoseconds))\nwith open(equilibrated_pdb_filename, 'w') as outfile:\n app.PDBFile.writeFile(pdb.topology, context.getState(getPositions=True,enforcePeriodicBox=True).getPositions(), file=outfile, keepIds=True)\nprint(' final : %8.3f kcal/mol' % (context.getState(getEnergy=True).getPotentialEnergy()/unit.kilocalories_per_mole))\n\n# Serialize state\nprint('Serializing state to %s' % state_xml_filename)\nstate = context.getState(getPositions=True, getVelocities=True, getEnergy=True, getForces=True)\nwith open(state_xml_filename, 'w') as outfile:\n xml = openmm.XmlSerializer.serialize(state)\n outfile.write(xml)\n\n# Serialize system\nprint('Serializing System to %s' % system_xml_filename)\nsystem.setDefaultPeriodicBoxVectors(*state.getPeriodicBoxVectors())\nwith open(system_xml_filename, 'w') as outfile:\n xml = openmm.XmlSerializer.serialize(system)\n outfile.write(xml)\n","sub_path":"high_temp_unfold/prepare-for-fah_hmr_600K.py","file_name":"prepare-for-fah_hmr_600K.py","file_ext":"py","file_size_in_byte":3226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"191908463","text":"import json\nfrom django.shortcuts import render\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom news.models import Article\nfrom guardian.shortcuts import get_objects_for_user\nfrom cilantro.models import UserPreferences\nfrom varify.samples.models import Sample\n\n\ndef app(request, project=None, batch=None, sample=None):\n if hasattr(request, 'user') and request.user.is_authenticated():\n kwargs = {'user': request.user}\n else:\n kwargs = {'session_key': request.session.session_key}\n\n obj, created = UserPreferences.objects.get_or_create(**kwargs)\n preferences = obj.json\n preferences['id'] = obj.pk\n\n selectedProband = {}\n if project and batch and sample:\n selectedProband['project'] = project\n selectedProband['batch'] = batch\n selectedProband['sample'] = sample\n\n projects = get_objects_for_user(request.user, 'samples.view_project')\n\n queryset = Sample.objects.select_related('batch', 'project')\\\n .filter(published=True, batch__published=True, project__in=projects)\\\n .values_list('pk', 'label', 'batch__name', 'project__name')\\\n .order_by('project', 'batch', 'label')\n\n samples = []\n keys = ['id', 'sample', 'batch', 'project']\n for row in queryset:\n samples.append(dict(zip(keys, row)))\n\n return render(request, 'cilantro/index.html', {\n 'user_preferences': json.dumps(preferences),\n 'samples': json.dumps(samples),\n 'selected_proband': json.dumps(selectedProband),\n })\n\n\ndef index(request):\n \"Index/splash page\"\n articles = Article.objects.filter(published=True)\\\n .values('title', 'slug', 'created', 'summary')[:3]\n form = AuthenticationForm()\n return render(request, 'index.html', {\n 'form': form,\n 'articles': articles,\n })\n\n\ndef news(request):\n articles = Article.objects.filter(published=True)\n return render(request, 'news/list.html', {\n 'articles': articles,\n })\n","sub_path":"varify/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"428323078","text":"\n#region capture Calm variables\nusername = '@@{cred_PCDemo.username}@@'\nusername_secret = \"@@{cred_PCDemo.secret}@@\"\napi_server = \"@@{address}@@\"\nentity_name = \"NTNX_LOCAL_AZ\"\n\n#endregion\n\n#region define variables\nenvironment_uuids = []\n#endregion\n\n# region prepare api call\napi_server_port = \"9440\"\napi_server_endpoint = \"/api/nutanix/v3/accounts/list\"\nlength = 100\nurl = \"https://{}:{}{}\".format(\n api_server,\n api_server_port,\n api_server_endpoint\n)\nmethod = \"POST\"\nheaders = {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json'\n}\n\n# Compose the json payload\npayload = {\"length\": length}\n# endregion\n\n#region make the api call\nprint(\"Making a {} API call to {}\".format(method, url))\nresp = urlreq(\n url,\n verb=method,\n auth='BASIC',\n user=username,\n passwd=username_secret,\n params=json.dumps(payload),\n headers=headers,\n verify=False\n)\n#endregion\n\n#region process the results\nif resp.ok:\n json_resp = json.loads(resp.content)\n for entity in json_resp[\"entities\"]:\n if entity[\"status\"][\"name\"] == entity_name:\n print (\"nutanix_calm_account_uuid={}\").format(entity[\"metadata\"][\"uuid\"])\n exit(0)\nelse:\n # print the content of the response (which should have the error message)\n print(\"Request failed\", json.dumps(\n json.loads(resp.content),\n indent=4\n ))\n print(\"Headers: {}\".format(headers))\n print(\"Payload: {}\".format(payload))\n exit(1)\n# endregion","sub_path":"CreateDemoTenant/scripts/Package_pkg_PrismCentralDemo_Action___install___Task_AccountUuid.py","file_name":"Package_pkg_PrismCentralDemo_Action___install___Task_AccountUuid.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"353682739","text":"from marshmallow import fields, utils\n\n\nclass Date(fields.Date):\n\n def _deserialize(self, value, attr, data):\n \"\"\"\n Deserialize an ISO8601-formatted date string to a :class:`datetime.date` object.\n \"\"\"\n if not value: # falsy values are invalid\n self.fail('invalid')\n try:\n return utils.from_iso_date(value, use_dateutil=False)\n except (AttributeError, TypeError, ValueError):\n self.fail('invalid')\n","sub_path":"api/core/serializers/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"371319003","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nclass Node:\n def __init__(self, key):\n self.left = None\n self.right = None\n self.val = key\n \nroot = Node(5)\nroot.left = Node(3)\nroot.right = Node(6)\n\n","sub_path":"DS & Algo/Graph/Binary tree with oop.py","file_name":"Binary tree with oop.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"119243083","text":"\n\n\n\nimport random\n\nfrom celery import task\n# 发送邮件\nfrom django.core.cache import cache\nfrom django.core.mail import send_mail\nfrom bbs import settings\n\n\n@task\ndef send_email(email):\n # 验证马生成\n checkcode = ''\n for i in range(4):\n current = random.randrange(0, 4) # 生成随机数与循环次数比对\n current1 = random.randrange(0, 4)\n if current == i:\n tmp = chr(random.randint(65, 90)) # 65~90为ASCii码表A~Z\n elif current1 == i:\n tmp = chr(random.randint(97, 122)) # 97~122为ASCii码表a~z\n else:\n tmp = random.randint(0, 9)\n checkcode += str(tmp)\n subject = '密码'\t#主题\n message = '%s'%checkcode#内容\n sender = settings.EMAIL_FROM\t\t#发送邮箱,已经在settings.py设置,直接导入\n receiver = [email]\t\t#目标邮箱\n html_message = '

    验证:%s

    '%checkcode#发送html格式\n try:\n send_mail(subject,message,sender,receiver,html_message=html_message)\n # 验证码放入缓存10s\n print('hehe')\n cache.set(email,checkcode,90)\n except Exception as e:\n print(e)","sub_path":"bbs/login_in/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"453716149","text":"\"\"\"MarketWatch URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.10/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 stockwatch import views\nfrom django.contrib.staticfiles.urls import static\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\nfrom django.conf import settings\n\n\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^home/', views.home),\n url(r'^login/', views.login_site),\n url(r'^register/', views.register),\n url(r'^(?P

    [\\w\\-\\_]+)/registeration_comp/', views.registeration_comp),\n url(r'^wishlist/', views.wishlisttable),\n url(r'^remove/', views.remove),\n url(r'^watchlist/', views.watchlist),\n url(r'^news/', views.news),\n url(r'^detail/(?P

    [\\w\\-\\_]+)/$',views.detail),\n url(r'^contact/', views.contact),\n url(r'^logout/', views.logout),\n\n \n\n]\n\nurlpatterns += staticfiles_urlpatterns()\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"Downloads/SHRUTI_USA_PREPARATION/Project/MarketWatch/MarketWatch-master/MarketWatch/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"373165319","text":"#!/usr/bin/python3\n\nfrom flask import Flask, request, jsonify\nimport paho.mqtt.client as mqtt_client\nimport threading\nimport json\n\napp = Flask(\"Web App Rumah sakit\")\n\n\n# Data awal\ndata_pasien = [\n {\n \"nik\" : \"123\",\n \"nama\" : \"Andi\",\n \"alamat\" : \"malang\",\n \"penyakit\" : \"maag\"\n },\n {\n \"nik\" : \"124\",\n \"nama\" : \"Dian\",\n \"alamat\" : \"Ngalam\",\n \"penyakit\" : \"Gaam\"\n }\n]\n\n@app.route('/input_data', methods=['POST'])\ndef create_data():\n nik = request.json['nik']\n nama = request.json['nama']\n alamat = request.json['alamat']\n penyakit = request.json['penyakit']\n \n data_baru = {\n \"nik\" : nik,\n \"nama\" : nama,\n \"alamat\" : alamat,\n \"penyakit\" : penyakit\n }\n data_pasien.append(data_baru)\n pub = mqtt_client.Client()\n data_baru = json.dumps(data_baru)\n pub.connect('127.0.0.1', port=1883)\n pub.on_message = handle_message\n pub.publish(\"/rs\", data_baru)\n # Return OK\n return \"OK\"\n\n@app.route('/output_data', methods=['GET'])\ndef get_data():\n json_pasien = json.dumps(data_pasien)\n return json_pasien\n\n\n# BAGIAN PUBLISH SUBSCRIBE\n# BERHASIL = DATA DI JSON DATA_PASIAN AKAN ADA 2\n\ndef handle_message(client, object, msg):\n data = msg.payload.decode('ascii')\n data = json.loads(data)\n data_pasien.append(data)\n print(data)\n\ndef handle_server():\n sub = mqtt_client.Client()\n sub.connect(\"127.0.0.1\", 1883)\n sub.on_message = handle_message\n sub.subscribe(\"/rs\")\n sub.loop_forever()\n\nt = threading.Thread(target=handle_server)\nt.start()\n\n# ganti port jika ingin coba menjalankan >1 server, sesuaikan di client juga\nprint(\"Server HTTP run di port 7111\")\napp.run(port=7111)","sub_path":"MQTT/server_rumahsakit.py","file_name":"server_rumahsakit.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"578619426","text":"import unittest\n\nfrom dojo.dojo import Dojo\n\n\nclass TestsForTask2ReallocatePerson(unittest.TestCase):\n \"\"\"\n Test cases for the reallocate_room method and functionality\n \"\"\"\n\n def setUp(self):\n \"\"\"Set up the test case class\"\"\"\n self.dojo = Dojo()\n\n def test_reallocate_to_no_non_existent_room(self):\n \"\"\"\"\n Test if reallocating to a room that doesn't exist fails with a message\n \"\"\"\n no_room = self.dojo.reallocate_person(\"one\", \"two\", \"non_existent\")\n self.assertEqual(no_room, \"no_room\")\n\n def test_if_available_room_is_reallocated_to(self):\n \"\"\"\n Test if an available room to be reallocated to is actually found\n :return:\n \"\"\"\n self.dojo.create_room(\"livingspace\", \"my_room\")\n self.dojo.reallocate_person(\"fName\", \"lName\", \"my_room\")\n self.assertEqual(self.dojo.all_rooms[-1].room_name, \"my_room\") # the last entered room is found\n\n def test_reallocate_to_non_existent_person(self):\n \"\"\"\n Test if reallocating to a person who is not in the system fails\n :return:\n \"\"\"\n self.dojo.create_room(\"livingspace\", \"my_room\")\n no_person = self.dojo.reallocate_person(\"romain\", \"guy\", \"my_room\")\n self.assertEqual(no_person, \"no_person\", msg=\"Should return no_person\")\n\n def test_reallocate_to_an_unallocated_person(self):\n \"\"\"\n Test if reallocating a person who has not been fully allocated before\n :return:\n \"\"\"\n self.dojo.create_room(\"livingspace\", \"my_space\")\n self.dojo.add_person(\"welike\", \"elly\", \"fellow\", \"y\")\n unallocated = self.dojo.reallocate_person(\"welike\", \"elly\", \"my_space\")\n self.assertEqual(unallocated, \"unallocated_person\")\n\n def test_reallocate_an_allocated_person(self):\n \"\"\"\n Test if a fully allocated person is found and the room entered is also found\n :return:\n \"\"\"\n self.dojo.create_room(\"office\", \"my_office\")\n self.dojo.add_person(\"john\", \"ike\", \"staff\")\n self.dojo.reallocate_person(\"john\", \"ike\", \"my_office\")\n self.assertEqual(self.dojo.all_people[-1].is_allocated, True)\n\n def test_cant_move_staff_to_living_space(self):\n \"\"\"\n Test if Staff can't be reallocated to a living space room\n :return:\n \"\"\"\n self.dojo.create_room(\"livingspace\", \"my_space\")\n self.dojo.create_room(\"office\", \"my_office\")\n self.dojo.add_person(\"john\", \"ike\", \"staff\")\n no_living_space = self.dojo.reallocate_person(\"john\", \"ike\", \"my_space\")\n self.assertEqual(no_living_space, \"staff_no_living_space\")\n\n def test_reallocate_to_the_same_room(self):\n \"\"\"\n Test if the room to reallocate to is the same as what the person is already assigned to\n :return:\n \"\"\"\n self.dojo.create_room(\"livingspace\", \"my_space\")\n self.dojo.create_room(\"office\", \"my_office\")\n self.dojo.add_person(\"john\", \"ike\", \"staff\")\n same_room = self.dojo.reallocate_person(\"john\", \"ike\", \"my_office\")\n self.assertEqual(same_room, \"same_room\")\n\n def test_if_person_has_been_moved_from_the_former_room(self):\n \"\"\"\n Test the number of occupants of the old room have been reduced by 1\n :return:\n \"\"\"\n self.dojo.create_room(\"office\", \"my_first_office\")\n self.dojo.add_person(\"john\", \"ike\", \"staff\")\n first_office_occupants_number_before = len(self.dojo.all_rooms[0].occupants)\n self.dojo.create_room(\"office\", \"my_second_office\")\n self.dojo.reallocate_person(\"john\", \"ike\", \"my_second_office\")\n first_office_occupants_number_after = len(self.dojo.all_rooms[0].occupants)\n self.assertEqual(first_office_occupants_number_before - first_office_occupants_number_after, 1)\n\n def test_if_person_has_been_added_to_the_new_room(self):\n \"\"\"\n Test if the number of occupants of the room moved to has increased by 1\n :return:\n \"\"\"\n self.dojo.create_room(\"office\", \"my_first_office\")\n self.dojo.add_person(\"john\", \"ike\", \"staff\")\n self.dojo.create_room(\"office\", \"my_second_office\")\n second_office_occupants_number_before = len(self.dojo.all_rooms[1].occupants)\n self.dojo.reallocate_person(\"john\", \"ike\", \"my_second_office\")\n second_office_occupants_number_after = len(self.dojo.all_rooms[1].occupants)\n self.assertEqual(second_office_occupants_number_after - second_office_occupants_number_before, 1)\n\n def test_if_function_runs_successfully_as_expected(self):\n \"\"\"\n Test if the expected strings are returned from each conditions\n :return:\n \"\"\"\n self.dojo.create_room(\"office\", \"my_first_office\")\n self.dojo.add_person(\"john\", \"ike\", \"staff\")\n self.dojo.create_room(\"office\", \"my_second_office\")\n string_expected = self.dojo.reallocate_person(\"john\", \"ike\", \"my_second_office\")\n self.assertEqual(string_expected, \"my_second_office, john ike, staff, office, my_first_office\")\n","sub_path":"tests/tests_for_task_2_reallocate_person.py","file_name":"tests_for_task_2_reallocate_person.py","file_ext":"py","file_size_in_byte":5071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"199950784","text":"# from fpdf import FPDF \n# pdf = FPDF() \n# # Add a page \n# pdf.add_page() \n# # set style and size of font \n# # that you want in the pdf \n# pdf.set_font(\"Arial\", size = 15)\n# # open the text file in read mode \n\n# f = open(\"sampletxt.txt\", \"r\") \n\n# # insert the texts in pdf \n# for x in f: \n# pdf.cell(0,20, txt = x, ln = 1, align = 'C') \n# # save the pdf with name pdf \n# pdf.output(\"t2extpdfoutput.pdf\")\n\nfrom reportlab.platypus import SimpleDocTemplate, Paragraph\nfrom reportlab.lib.styles import getSampleStyleSheet\nfrom reportlab.lib.units import inch\nfrom reportlab.lib.pagesizes import letter\n\n\nstyles = getSampleStyleSheet()\nstyleN = styles['Normal']\nstyleH = styles['Heading1']\nstory = []\n\nfile_loc = \"\"\n#file_in_base = \"output_file_histos-20200929-07-50\"\nfile_in_base = \"output_file_histos-20200930-06-43\"\n#file_in_base = \"output_file_histos-20200927-13-54\"\n#../../groovy/hipo-root-files/output_file_histos-20200930-06-43.hipo.root\n\nfile_in = file_loc + file_in_base + \".txt\"\npdf_name = \"aaa\"+file_in_base + \".pdf\"\n\ndoc = SimpleDocTemplate(\n pdf_name,\n pagesize=letter,\n bottomMargin=.4 * inch,\n topMargin=.6 * inch,\n rightMargin=.8 * inch,\n leftMargin=.8 * inch)\n\n\n\nwith open(file_in, \"r\") as txt_file:\n text_content = txt_file.read()\n\ntextarray = text_content.split(\"\\n\")\n\nfor sentence in textarray:\n P = Paragraph(sentence, styleN)\n story.append(P)\n\ndoc.build(\n story,\n)\n","sub_path":"python/src/texttopdf.py","file_name":"texttopdf.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"319953076","text":"import torchvision\nimport struct\nimport torch\nfrom torchvision import datasets, transforms\nfrom torch import nn\nimport torch.nn.functional as F\n\n\nclass LeNet(nn.Module):\n def __init__(self):\n super(LeNet, self).__init__()\n self.conv = nn.Sequential(\n nn.Conv2d(1, 6, 5, stride=1, padding=2 ,bias=False),\n nn.MaxPool2d(2, 2),\n nn.Conv2d(6, 16, 5, stride=1, padding=0 ,bias=False),\n nn.MaxPool2d(2, 2))\n\n self.fc = nn.Sequential(\n nn.Linear(16*25, 120 ,bias=False),\n nn.Linear(120, 84,bias=False),\n nn.Linear(84, 10,bias=False))\n\n def forward(self, x):\n out = self.conv(x)\n out = out.view(out.size(0), -1)\n out = self.fc(out)\n return out\n\n\ndef train(model, train_loader, device, batch_size):\n model.train()\n cost = torch.nn.CrossEntropyLoss()\n for epoch in range(20):\n print('train epoch ', epoch)\n for batch_idx, (data, target) in enumerate(train_loader):\n if((batch_idx + 1) * batch_size > 60000):\n break\n data, target = data.to(device), target.to(device)\n #pad = nn.ZeroPad2d(padding=(2, 2, 2, 2))\n #data = pad(data)\n\n optimizer.zero_grad()\n output = model(data)\n loss = cost(output, target)\n loss.backward()\n optimizer.step()\n\n\ndef test(model, test_loader, device):\n model.eval()\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n #pad = nn.ZeroPad2d(padding=(2, 2, 2, 2))\n #data = pad(data)\n output = F.softmax(model(data), 1)\n # get the index of the max log-probability\n pred = output.argmax(dim=1, keepdim=True)\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n print('\\nTest set: Accuracy: {}/{} ({:.3f}%)\\n'.format(\n correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))\n\n\ndef save(model):\n model = model.cpu()\n file = open('../bin/DATA/LeNet-MNIST/weight.bin', 'wb')\n\n weight = model.conv[0].weight.detach()\n print('conv1')\n print(weight.max())\n print(weight.min())\n weight = weight.reshape(-1).numpy().tolist()\n for i in range(len(weight)):\n bytes = struct.pack('f', weight[i])\n file.write(bytes)\n\n weight = model.conv[2].weight.detach()\n print('conv1')\n print(weight.max())\n print(weight.min())\n weight = weight.reshape(-1).numpy().tolist()\n for i in range(len(weight)):\n bytes = struct.pack('f', weight[i])\n file.write(bytes)\n\n for i in range(3):\n weight = model.fc[i].weight.detach()\n print('fc')\n print(weight.max())\n print(weight.min())\n weight = weight.reshape(-1).numpy().tolist()\n for j in range(len(weight)):\n bytes = struct.pack('f', weight[j])\n file.write(bytes)\n\n\nif __name__ == \"__main__\":\n\n transform = transforms.Compose([transforms.ToTensor()])\n\n batch_size = 128\n dataset1 = datasets.MNIST('./data', train=True,\n download=True, transform=transform)\n dataset2 = datasets.MNIST('./data', train=False, transform=transform)\n train_loader = torch.utils.data.DataLoader(\n dataset1, batch_size, shuffle=True)\n test_loader = torch.utils.data.DataLoader(\n dataset2, 100, shuffle=True)\n\n model = LeNet()\n optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n\n device = torch.device(\"cuda\")\n model = model.to(device)\n\n train(model, train_loader, device, batch_size)\n test(model, test_loader, device)\n\n save(model)\n","sub_path":"train/LeNet-MNIST.py","file_name":"LeNet-MNIST.py","file_ext":"py","file_size_in_byte":3734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"415588789","text":"import numpy as nump\nfrom sklearn import linear_model\nfrom sklearn.metrics import mean_squared_error, r2_score\nfrom movie_classification import preprocess\nimport matplotlib.pyplot as plot\nimport sklearn.metrics as metrics\nimport seaborn as sns\n\n\n# linear regression based on feature, target and size of test data\ndef linear_regression(d, features, target, ts=300):\n x = d[:, features]\n y = d[:, target]\n x_train = x[:-ts]\n y_train = y[:-ts]\n x_test = x[-ts:]\n y_test = y[-ts:]\n reg = linear_model.LinearRegression()\n reg.fit(x_train, y_train)\n y_pred = reg.predict(x_test)\n coef = reg.coef_\n mse = mean_squared_error(y_test, y_pred)\n r2 = r2_score(y_test, y_pred)\n return y_test, y_pred, coef, mse, r2\n\n\nD = preprocess.pre_process()\nprint(D)\n\n# Prediction of revenue\n# features: popularity, budget, runtime, vote_count, vote_average\nFeatures = [0, 3, 4, 5, 6]\n# Features = [0]\n# Features = [0, 5]\n# target: revenue\nTarget = 7\nTs = 500\nTest, Pred, COEF, MSE, R2 = linear_regression(D, features=Features, target=Target, ts=Ts)\n\nprint(Pred)\n\nprint(\"coefficients:\" + str(COEF))\nprint(\"mean squared error: \" + str(MSE))\nprint(\"r2 score: \" + str(R2))\n\n\nL1 = nump.zeros(len(D))\nL2 = nump.zeros(len(D))\nplot.scatter(D[:-Ts, 1], D[:-Ts, 2], edgecolors='black')\nplot.xlabel(\"Budget in Training Data\")\nplot.ylabel(\"Revenue in Training Data\")\nplot.title(\"Budget in Training Data v.s. Revenue in Training Data\")\nplot.show()\n\nplot.scatter(D[-Ts:, 1], D[-Ts:, 2], edgecolors='black')\nplot.xlabel(\"Budget in Test Data\")\nplot.ylabel(\"Revenue in Test Data\")\nplot.title(\"Budget in Test Data v.s. Revenue in Test Data\")\nplot.show()\n\nplot.scatter(D[-Ts:, 1], Pred, edgecolors='black')\nplot.xlabel(\"Budget in Test Data\")\nplot.ylabel(\"Predicted Revenue\")\nplot.title(\"Budget in Test Data v.s. Predicted Revenue\")\nplot.show()\n#\n# profit = D[:-Ts, 2] - D[:-Ts, 1]\n#\n# max_profit = nump.max(profit)\n# min_profit = nump.min(profit)\n# print(max_profit)\n# print(min_profit)\n#\n# pred_profit = Pred - D[-Ts:, 1]\n# max_pred_profit = nump.max(pred_profit)\n# min_pred_profit = nump.min(pred_profit)\n# print(max_pred_profit)\n# print(min_pred_profit)\n# print(nump.sum(pred_profit) / len(pred_profit))\n\n# B9 = 3000000000\n# B8 = 2000000000\n# B7 = 700000000\n# B6 = 600000000\n# B5 = 500000000\nB4 = 1000000000\nB3 = 600000000\nB2 = 300000000\nB1 = 100000000\nB0 = 50000000\nTrueCluster = nump.zeros(Ts)\nPredictedCluster = nump.zeros(Ts)\nfor i in range(Ts):\n true_reve = D[-Ts + i, 2]\n pred_reve = Pred[i]\n if true_reve <= B0:\n TrueCluster[i] = 0\n elif true_reve <= B1:\n TrueCluster[i] = 1\n elif true_reve <= B2:\n TrueCluster[i] = 2\n elif true_reve <= B3:\n TrueCluster[i] = 3\n elif true_reve <= B4:\n TrueCluster[i] = 4\n # elif true_reve <= B5:\n # TrueCluster[i] = 5\n # elif true_reve <= B6:\n # TrueCluster[i] = 6\n # elif true_reve <= B7:\n # TrueCluster[i] = 7\n # elif true_reve <= B8:\n # # TrueCluster[i] = 8\n # else:\n # TrueCluster[i] = 5\n\n if pred_reve <= B0:\n PredictedCluster[i] = 0\n elif pred_reve <= B1:\n PredictedCluster[i] = 1\n elif pred_reve <= B2:\n PredictedCluster[i] = 2\n elif pred_reve <= B3:\n PredictedCluster[i] = 3\n elif pred_reve <= B4:\n PredictedCluster[i] = 4\n # elif pred_reve <= B5:\n # PredictedCluster[i] = 5\n # elif pred_reve <= B6:\n # PredictedCluster[i] = 6\n # elif pred_reve <= B7:\n # PredictedCluster[i] = 7\n # elif pred_reve <= B8:\n # PredictedCluster[i] = 8\n # else:\n # PredictedCluster[i] = 5\n\nC = metrics.confusion_matrix(TrueCluster, PredictedCluster, labels=range(5))\nprint(metrics.classification_report(TrueCluster, PredictedCluster, labels=range(5)))\nsns.set()\nsns.heatmap(C, annot=True)\nplot.show()\nprint(TrueCluster)\nprint(PredictedCluster)\n\n","sub_path":"classifications/ordinary_least_squares.py","file_name":"ordinary_least_squares.py","file_ext":"py","file_size_in_byte":3876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"450587891","text":"# coding=utf-8\n# CURSO EM VÍDEO\n# Curso de Programação em Python\n# Professor: Gustavo Guanabara\n\nprint('====== DESAFIO 086 ======')\n# Crie um programa que crie uma matriz de dimensão 3x3 e preencha\n# com valores lidos pelo teclado. No final mostre a matriz na tela,\n# com formatação correta.\n\nimport random\n\ndim = int(input('Insira a dimensão da matriz: '))\nMatrix = list()\n\n# Matriz Vazia\nfor i in range(0,dim):\n\tMatrix.append(list())\n\nfor i in range(0,dim):\n for j in range(0,dim):\n num = random.randint(0,10)\n #num = int(input('Insira um número: '))\n Matrix[i].append(num)\n\nfor i in range(0,dim):\n for j in range(0,dim):\n print(f'[{Matrix[i][j]:^5}]',end='')\n print('')\n","sub_path":"Cev/Desafio086.py","file_name":"Desafio086.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"119530223","text":"# 请求定制\nimport time\nimport uuid\n\nfrom flask import render_template\nfrom flask_mail import Message\nfrom flask_restful import reqparse, fields, Resource, marshal_with\n\nfrom qqx.ext import mail, db,cache\nfrom qqx.models import User\n\nparser = reqparse.RequestParser()\nparser.add_argument('phone',type=str,required=True,help='请提供手机号码')\nparser.add_argument('password',type=str,required=True,help='请输入密码')\nparser.add_argument('email',type=str,required=True,help='请输入邮箱')\n\n\n\n\n# 响应格式示例\n\"\"\"\n{\n 'msg' : '注册成功',\n 'status' : 200,\n 'date' : 'xxxx',\n 'data' : {\n 'phone' : '15879764436',\n 'icon' : '/static/images/logo1.jpg/',\n 'permissions' : 1,\n },\n 'token' : 'xxxxxx',\n}\n\"\"\"\n\n# 响应格式定制\n\n#自定义属性\nclass IconFormat(fields.Raw):\n def format(self, value):\n return '/static/images/' +value\n\n\n\nuser_fields = {\n 'phone' : fields.String,\n 'icon' : IconFormat(attribute='icon'), #自定义属性\n 'permissions' : fields.Integer,\n }\n\n\nresult_fields = {\n 'msg' : fields.String,\n 'status' : fields.Integer,\n 'date' : fields.String,\n 'user' : fields.Nested(user_fields,default={}),\n 'token' : fields.String,\n}\n\n\n#定义资源\nclass Register(Resource):\n @marshal_with(result_fields)\n def post(self):\n # 用户\n parse = parser.parse_args()\n user = User()\n user.phone = parse.get('phone')\n user.password = parse.get('password')\n user.email = parse.get('email')\n\n\n response_data = {\n 'date' : str(time.time()),\n }\n\n\n #数据处理\n response_data['status'] = '406'\n response_data['user'] = ''\n\n users = User.query.filter(User.phone == user.phone)\n if users.count():\n response_data['msg'] = '该用户名已经存在,注册失败'\n return response_data\n\n users = User.query.filter(User.email == user.email)\n if users.count():\n response_data['msg'] = '邮箱已存在,注册失败'\n return response_data\n\n # 存入数据库\n db.session.add(user)\n db.session.commit()\n\n token = uuid.uuid5(uuid.uuid4(),'regisger').hex\n cache.set(token,user.id,timeout=60*3)\n\n active_url = 'http://10.20.152.194:5000/api/v1/active/?token=' +token\n tempplate_str = render_template('mail_active.html',active_url=active_url,phone=user.phone)\n msg = Message(\n subject='梦芭莎激活邮件',\n sender='976393191@qq.com',\n recipients=[user.email],\n html=tempplate_str\n\n )\n\n mail.send(msg)\n\n\n # 返回数据\n response_data['msg'] = '注册成功'\n response_data['status'] = 200\n response_data['user'] = user\n response_data['token'] = token\n\n return response_data","sub_path":"qqx/Apis/RegisterApi.py","file_name":"RegisterApi.py","file_ext":"py","file_size_in_byte":2902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"96199869","text":"import csv\n\nclass Student:\n\n def __init__(self,id,prefix,first_name,last_name):\n self.id = id\n self.prefix = prefix\n self.first_name = first_name\n self.last_name = last_name\n\n self.plan = \"\"\n self.gpa = -1\n \n self.chooses = []\n self.score = {}\n self.data = {}\n\n self.min_year = \"2560\"\n # minimun year\n\n def load_data_with_year(self, year_str, data):\n for key in data:\n if year_str not in self.data: self.data[year_str] = {}\n self.data[year_str][key] = data[key]\n\n def get_max_score_by_subject(self, subject):\n tmp = self.get_score_by_subject(subject)\n if not tmp: return []\n return max(tmp)\n \n def get_score_by_subject(self, subject):\n # tmp = [(self.data[year][subject], year) for year in self.data if self.data[year].get(subject,-1) != -1 and year >= self.min_year]\n tmp = [(self.data[year][subject], year) for year in self.data if self.data[year].get(subject,-1) != -1]\n return tmp\n\n def getMaxPat7(self):\n pat7_list = [\"pat7_1\",\"pat7_2\",\"pat7_3\",\"pat7_4\",\"pat7_5\",\"pat7_6\",\"pat7_7\"]\n score = []\n for subj in pat7_list:\n tmp = self.get_max_score_by_subject(subj)\n if tmp: score.append(tmp)\n if not score: return []\n return max(score)\n\n def get_score(self, year, subject):\n return self.data[year][subject], year\n","sub_path":"lib/student.py","file_name":"student.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"28566625","text":"import tushare as ts\nimport pandas as pd\nimport time\nfrom functools import *\n\ndate=time.strftime('%Y-%m-%d',time.localtime(time.time()))\n\n\n\n\nroe2018_2 = ts.get_profit_data(2018,2)\nroe2018_1 = ts.get_profit_data(2018,1)\nroe2017_4 = ts.get_profit_data(2017,4)\nroe2017_3 = ts.get_profit_data(2017,3)\nroe2017_2 = ts.get_profit_data(2017,2)\nroe2017_1 = ts.get_profit_data(2017,1)\nroe2016_4 = ts.get_profit_data(2016,4)\nroe2016_3 = ts.get_profit_data(2016,3)\nroe2016_2 = ts.get_profit_data(2016,2)\n\n\nli=[]\nli=[roe2016_2, roe2016_3, roe2016_4, roe2017_1, roe2017_2, roe2017_3, roe2017_4, roe2018_1, roe2018_2]\n\nfor i in range(len(li)):\n li[i]['name']= li[i]['name'].map(str.strip)\n li[i] = li[i][ ~ li[i]['name'].str.contains('ST')]\n li[i] = li[i][ ~ li[i]['name'].str.contains('退市')]\n\ndef df_join_nm(pd_li,col,rename):\n for i in range(len(pd_li)):\n pd_li[i]=pd_li[i].loc[:,col]\n for j in range(len(col[1:])):\n pd_li[i].rename(columns={col[1:][j]:rename[i]}, inplace = True) \t\n tmp=reduce(lambda x, y:pd.merge(x,y,how='outer',on=col[0]), pd_li)\n tmp = tmp.drop_duplicates()\n return tmp\n\n\n\n\nrename=['roe2016_2','roe2016_3','roe2016_4','roe2017_1','roe2017_2','roe2017_3','roe2017_4','roe2018_1','roe2018_2']\nroe=df_join_nm(li, ['name', 'roe'], rename)\n\n\nbasic = ts.get_stock_basics()\nbasic['name']= basic['name'].map(str.strip)\nbasic['name']= basic['name'].str.replace(' ', '')\nbasic['name']= basic['name'].str.replace('A', 'A')\nbasic['name']= basic['name'].map(str.strip)\nbasic = basic[ ~ basic['name'].str.contains('ST') ]\nbasic = basic[ ~ basic['name'].str.contains('退市')]\n\n\n\nre=pd.merge(roe,basic,how='outer',on='name')\n\n\nre.to_csv(date+'_quarter_all_roe.csv', encoding = 'gbk', index=False)\n\n","sub_path":"stock/Main/quarter_all_roe.py","file_name":"quarter_all_roe.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"133555639","text":"import os\nimport numpy as np\nls = [i for i in os.listdir() if i.find(\"R-\") !=-1] \nls0 = np.argsort([float(i.replace(\"R-\",\"\")) for i in ls])\nls = np.array(ls)\nls = ls[ls0[:-1]]\nprint (ls)\nfiles = ['E.txt', 'µ.txt', 'dij.txt']\n\nfor idir in ls:\n for ifiles in files:\n with open(ifiles, \"ab\") as f:\n print (idir)\n try: \n np.savetxt(f, np.loadtxt(f\"{idir}/{ifiles}\"))\n except:\n print (f\"failed to load {idir}/{ifiles}\")\n \n ","sub_path":"double_well_01/Hm/gather.py","file_name":"gather.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"248117013","text":"import cv2\nimport numpy as np \nimport imutils\ncap = cv2.VideoCapture(0)\nlower_hsv = np.array([0,100,100])\nupper_hsv = np.array([255,255,200])\n\nwhile True :\n rtn, frame = cap.read()\n frame = imutils.resize(frame, width=640, height=360)\n HSV_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n cv2.imshow(\"Camera_HSV\",HSV_frame)\n mask = cv2.inRange(HSV_frame,lower_hsv,upper_hsv)\n res = cv2.bitwise_and(frame,frame,mask = mask)\n cv2.imshow(\"Camera\",res)\n if cv2.waitKey(1) & 0xFF == ord('q') :\n break\n\n\n# H > 100\n# S > 100","sub_path":"HSV_camera.py","file_name":"HSV_camera.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"579010966","text":"import sys\ninput = sys.stdin.readline\n\nn, s = map(int, input().split())\narr = list(map(int, input().split()))\n\nleft = 0\nright = 0\nsum = 0\nresult = 1000001\nwhile True:\n if sum >= s:\n result = min(result, right - left)\n sum -= arr[left]\n left += 1\n elif right == n:\n break\n else:\n sum += arr[right]\n right += 1\n \nif result == 1000001:\n result = 0\nprint(result)\n","sub_path":"Baekjoon training/Python/Baekjoon - 1806 (부분합).py","file_name":"Baekjoon - 1806 (부분합).py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"331505551","text":"import unittest\nimport ip_address\nimport os\nimport re\n \n\n\nclass Test_Ipaddress(unittest.TestCase):\n \n # test case 1 checking if all the ip address are valid according to standards\n # The numbers should be in a range of 0-255\n # It should consist of 4 cells separated by ‘.’\n def test_IpAddressFetch(self):\n \n #storing the main function IP address in result\n result=ip_address.IpAddressFetch('access.log')\n\n\n #valid IP address regex pattern\n pattern =re.compile('''((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)''')\n \n # initializing the list objects\n valid =[]\n invalid=[]\n \n # extracting the IP addresses\n for line in result:\n Indicator = pattern.search(line)\n \n # valid IP addresses\n if Indicator:\n valid.append(line)\n\n \n # invalid IP addresses \n else:\n invalid.append(line)\n \n #asserting the invalid IP address values with the valid one using assert list values\n self.assertEqual(result,valid)\n\n\n\n #test case 2 to check the log file is present or not \n def test_valid_file_exists(self):\n #eter the file name to check for its presence\n filename='access.log'\n\n #get the current directory \n path=os.getcwd()\n\n #check for if the file is present in the current location\n if os.path.exists(f'{path}\\{filename}'):\n filename='access.log'\n else:\n filename=None\n\n #asserting if the file is present with the name\n self.assertEqual(filename,'access.log')\n\n\n #test case 3 to check if the output list file has 10 ip address or not\n def test_output_list_length(self):\n\n #list of all the 10 ip addrss\n IpAddressList=ip_address.IpAddressFetch('access.log')\n\n #number of the ip address present in the list\n ListLength=len(IpAddressList)\n\n #asserting if the number of ip address we get are equal to 10\n self.assertEqual(ListLength,10)\n\n\nif __name__=='__main__':\n unittest.main()","sub_path":"ip_address_test.py","file_name":"ip_address_test.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"407930809","text":"files_name = str(input())\nf1 = open('%s'%files_name, 'r')\nnums = []\nfor i in f1:\n\tnums.append(int(i))\nf1.close()\nn = len(nums)\nindex = n // 2\nnums.sort()\nsummary = 0\nfor i in range(len(nums)):\n\tif i != index:\n\t\tsummary += abs(nums[i]-nums[index])\nprint(summary)","sub_path":"task4.py","file_name":"task4.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"468613303","text":"import numpy as np\n\n\nclass Person:\n def __init__(self, name, age, gender, data=None):\n self.name = name\n self.age = age\n self.gender = gender\n self.data = np.array(data)\n if data is not None:\n self.data = self.normalize()\n\n def normalize(self):\n x = [(i - min(self.data)) / (max(self.data) - i) for i in self.data]\n return np.array(x)\n\n\n @staticmethod\n def match(person1, person2):\n delta = person1.data - person2.data\n return round(sqrt(np.sum(delta.dot(delta)), 5))\n\n\n","sub_path":"person.py","file_name":"person.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"555005044","text":"import socket\nimport threading\nimport json\nimport random\nimport numpy as np\nimport time\nimport os\nimport copy\nfrom tensorflow.keras import datasets, layers, models\n\n\ndef coeff_determination(y_true, y_pred):\n from keras import backend as K\n SS_res = K.sum(K.square(y_true - y_pred))\n SS_tot = K.sum(K.square(y_true - K.mean(y_true)))\n return 1 - SS_res / (SS_tot + K.epsilon())\n\n\nclass NumpyEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, np.ndarray):\n return obj.tolist()\n return json.JSONEncoder.default(self, obj)\n\n\nclass ClientThread(threading.Thread):\n def __init__(self, client_address, client_socket, count_id):\n threading.Thread.__init__(self)\n self.c_socket = client_socket\n self.tower_available = []\n self.tower_map = np.zeros((height, width, 4))\n\n self.conflict = False\n self.task_list = []\n self.data_list = []\n self.id = count_id\n self.have_place = True\n\n print(\"New connection added: \", client_address)\n\n def generate_one_wave(self, tower_available_local, tower_map_local):\n\n place_tower_task = []\n sell_tower_task = []\n upgrade_tower_task = []\n tower_available_copy = tower_available_local.copy() # for sell only\n # one round, place tower\n number_tower_place = random.randint(min_number_tower_place, max_number_tower_place)\n available_place = path.copy()\n\n for index_path in path:\n for index_tower in tower_available_local:\n if index_path['x'] == index_tower['x'] and index_path['y'] == index_tower['y']:\n available_place.remove(index_path)\n if len(available_place) <= 2:\n return None, tower_map_local, tower_available_local\n if number_tower_place > len(available_place):\n number_tower_place = len(available_place)\n index_list = random.sample(available_place, number_tower_place)\n for index in index_list:\n tower_list = [0, 0, 0, 0]\n tower_index = random.randint(0, 3)\n tower_list[tower_index] = 1\n tower_available_local.append({'x': index['x'], 'y': index['y'], 'tower_list': tower_list})\n # add to map\n tower_map_local[index['y']][index['x']][tower_index] = 1\n # add to task\n place_tower_task.append({'x': index['x'], 'y': index['y'], 'type': tower_index + 1})\n\n # print(\"after place tower\")\n # print(tower_available_local)\n # one round, sell tower\n\n number_tower_sell = random.randint(0, max_number_tower_sell)\n\n if len(tower_available_copy) < number_tower_sell:\n number_tower_sell = len(tower_available_copy)\n index_list = random.sample(tower_available_copy, number_tower_sell)\n for index in index_list:\n # update the map\n tower_map_local[index['y']][index['x']] = [0, 0, 0, 0]\n # add to task\n sell_tower_task.append({'x': index['x'],\n 'y': index['y']})\n # remove from list\n # print(\"remove index\")\n # print(index)\n tower_available_local.remove(index)\n\n # print(\"after sell tower\")\n # print(tower_available_local)\n # one round, upgrade tower\n\n number_tower_upgrade = random.randint(0, max_number_tower_upgrade)\n if len(tower_available_local) < number_tower_upgrade:\n number_tower_upgrade = len(tower_available_local)\n index_list = random.sample(tower_available_local, number_tower_upgrade)\n for index in index_list:\n upgrade_level = random.randint(1, max_upgrade_level)\n tower_list = index['tower_list']\n # print(\"tower_list\")\n # print(tower_list)\n for pointer in range(len(tower_list)):\n if tower_list[pointer] == 1:\n tower_list[pointer] += upgrade_level\n tower_map_local[index['y']][index['x']][pointer] = tower_list[pointer]\n break\n for pointer in range(len(tower_available_local)):\n if tower_available_local[pointer] == index:\n tower_available_local[pointer]['tower_list'] = tower_list\n upgrade_tower_task.append({'x': index['x'], 'y': index['y'], 'level': upgrade_level})\n\n # print(\"after upgrade tower\")\n # print(tower_available_local)\n\n task = {'place_tower': place_tower_task, 'sell_tower': sell_tower_task, 'upgrade_tower': upgrade_tower_task}\n # self.layers.append(self.tower_map)\n return task, tower_map_local, tower_available_local\n\n def run(self):\n print(\"Connection from : \", clientAddress)\n init = True\n\n while True:\n if init:\n para = {'wave_round': wave_round, 'init_money': init_money, 'init_lives': init_lives,\n 'time_left': time_left, 'game_map': lines, 'start': start, 'end': end,\n 'orthographic_size': orthographic_size, 'time_scale': time_scale,\n 'time_one_wave': time_one_wave}\n self.c_socket.send(json.dumps(para).encode('utf8'))\n init = False\n\n data = self.c_socket.recv(2048)\n\n if not data:\n break\n\n received = data.decode('utf8')\n if 'ok' in received:\n wave_number = 0\n # print(received)\n try:\n get_json = json.loads(received)\n min_path_length = get_json['min_path_length']\n lives = get_json['lives']\n reward = get_json['reward']\n wave_number = get_json['wave_number']\n self.data_list.append({'game_map': self.tower_map, 'lives': lives, 'wave_number': wave_number,\n 'min_path_length': min_path_length, 'reward': reward})\n except ValueError:\n print(\"first round\")\n\n task_selection = []\n tower_map_selection = []\n tower_available_selection = []\n input_selection = []\n for random_sample_index in range(max_sample_one_wave):\n task_one_wave, tower_map_one_wave, tower_available_one_wave = self.generate_one_wave(\n copy.deepcopy(self.tower_available), copy.deepcopy(self.tower_map))\n if not task_one_wave:\n self.c_socket.send('stop'.encode('utf8'))\n print(\"send stop, reason: no place for tower!\")\n self.have_place = False\n break\n task_selection.append(task_one_wave)\n tower_map_selection.append(tower_map_one_wave)\n map_1d = np.array(tower_map_one_wave).reshape((height, width, 4)).reshape(-1)\n one_input = np.append(map_1d, wave_number)/20\n input_selection.append(one_input)\n tower_available_selection.append(tower_available_one_wave)\n if not self.have_place:\n self.have_place = True\n continue\n predict_list = model.predict(np.stack(input_selection))\n max_index = int(np.argmax(predict_list))\n task = task_selection[max_index]\n self.task_list.append(task)\n self.tower_available = tower_available_selection[max_index]\n self.tower_map = tower_map_selection[max_index]\n print(json.dumps(task))\n\n self.c_socket.send(json.dumps(task).encode('utf8'))\n\n if 'stop' in received:\n\n # game_map = np.stack(self.layers)\n print(received)\n try:\n get_json = json.loads(received)\n except ValueError:\n print(\"game internal error! skip!\")\n self.c_socket.close()\n break\n\n for my_data in self.data_list:\n folder_name = 'test_wave_' + str(my_data['wave_number'])\n if not os.path.exists(folder_name):\n os.makedirs(folder_name)\n my_file = open('./' + folder_name + '/' + str(self.id) + '.txt', 'w')\n my_file.write(json.dumps(my_data, cls=NumpyEncoder))\n my_file.close()\n self.c_socket.close()\n\n break\n pass\n pass\n\n\n# set parameters here, for each wave\nmax_number_tower_place = 6\nmin_number_tower_place = 2\nmax_number_tower_sell = 2\nmax_number_tower_upgrade = 2\nmax_upgrade_level = 2\nwave_round = 5 # disabled in game\ninit_money = 150\ninit_lives = 50\ntime_left = 1800 # disabled in game\ntime_one_wave = 400\northographic_size = 5\ntime_scale = 20\nstart = {'x': 0, 'y': 0}\nend = {'x': 11, 'y': 6}\nwidth = 12\nheight = 8\nmax_number_verify = 300\nmax_sample_one_wave = 1000\n\nf = open('game_map.txt', 'r')\nlines = []\nmatrix = []\nwhile True:\n line = f.readline()\n if line == '':\n break\n matrix.append(list(line[:-1]))\n lines.append(line[:-1])\n\n# print(matrix)\npath = []\nfor i in range(0, height):\n for j in range(0, width):\n\n if matrix[i][j] == '1':\n path.append({'x': j, 'y': i})\n# print(path)\n\ninput_shape = (height*width*4+1,)\nmodel = models.Sequential()\nmodel.add(layers.Dense(2048, activation='relu', use_bias=True, input_shape=input_shape))\nmodel.add(layers.Dense(2048, activation='relu', use_bias=True))\nmodel.add(layers.Dense(2048, activation='relu', use_bias=True))\nmodel.add(layers.Dense(1, use_bias=True))\n\nmodel.compile(loss=\"mean_squared_error\", optimizer=\"adam\", metrics=[coeff_determination])\n\nfile_list = os.listdir('weight')\ncoeff_determination_list = []\nfor file in file_list:\n coeff_determination_list.append(float(file[12:-5]))\n\nweight_file = file_list[coeff_determination_list.index(max(coeff_determination_list))]\nmodel.load_weights('weight/'+weight_file)\n\n# host parameters\nLOCALHOST = \"127.0.0.1\"\nPORT = 8081\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nserver.bind((LOCALHOST, PORT))\nprint(\"Server started\")\nprint(\"Waiting for client request..\")\ncount = 0\nwhile True:\n if count >= max_number_verify:\n break\n server.listen(1)\n client_sock, clientAddress = server.accept()\n new_thread = ClientThread(clientAddress, client_sock, count)\n new_thread.start()\n count += 1\n","sub_path":"verify_model.py","file_name":"verify_model.py","file_ext":"py","file_size_in_byte":10669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"578816744","text":"#! python3\n\n\"\"\"This is an APNG module, which can create apng file from pngs\n\nReference:\nhttp://littlesvr.ca/apng/\nhttp://wiki.mozilla.org/APNG_Specification\nhttps://www.w3.org/TR/PNG/\n\"\"\"\n\nimport struct\nimport binascii\nimport itertools\nimport io\n\n__version__ = \"0.2.1\"\n\ntry:\n\timport PIL.Image\nexcept ImportError:\n\t# Without Pillow, apng can only handle PNG images\n\tpass\n\nPNG_SIGN = b\"\\x89\\x50\\x4E\\x47\\x0D\\x0A\\x1A\\x0A\"\n\n# http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html#C.Summary-of-standard-chunks\nCHUNK_BEFORE_IDAT = {\n\t\"cHRM\", \"gAMA\", \"iCCP\", \"sBIT\", \"sRGB\", \"bKGD\", \"hIST\", \"tRNS\", \"pHYs\",\n\t\"sPLT\", \"tIME\", \"PLTE\"\n}\n\ndef is_png(png):\n\t\"\"\"Test if ``png`` is a valid PNG file by checking the signature.\n\t\n\t:arg png: If ``png`` is a :any:`path-like object` or :any:`file-like object`\n\t\tobject, read the content into bytes.\n\t:type png: path-like, file-like, or bytes\n\t:rtype: bool\n\t\"\"\"\n\tif isinstance(png, str) or hasattr(png, \"__fspath__\"):\n\t\twith open(png, \"rb\") as f:\n\t\t\tpng_header = f.read(8)\t\t\n\telif hasattr(png, \"read\"):\n\t\tposition = png.tell()\n\t\tpng_header = png.read(8)\n\t\tpng.seek(position)\n\telif isinstance(png, bytes):\n\t\tpng_header = png[:8]\n\telse:\n\t\traise TypeError(\"Must be file, bytes, or str but get {}\"\n\t\t\t\t.format(type(png)))\n\t\t\t\n\treturn png_header == PNG_SIGN\n\t\t\t\ndef chunks_read(b):\n\t\"\"\"Parse PNG bytes into different chunks, yielding (type, data). \n\t\n\t@type is a string of chunk type.\n\t@data is the bytes of the chunk. Including length, type, data, and crc.\n\t\"\"\"\n\t# skip signature\n\ti = 8\n\t# yield chunks\n\twhile i < len(b):\n\t\tdata_len, = struct.unpack(\"!I\", b[i:i+4])\n\t\ttype = b[i+4:i+8].decode(\"latin-1\")\n\t\tyield type, b[i:i+data_len+12]\n\t\ti += data_len + 12\n\ndef chunks(png):\n\t\"\"\"Yield ``(chunk_type, chunk_raw_data)`` from ``png``.\n\t\n\t.. note::\n\t\n\t\t``chunk_raw_data`` includes chunk length, type, and CRC.\n\t\n\t:arg png: If ``png`` is a :any:`path-like object` or :any:`file-like object`\n\t\tobject, read the content into bytes.\n\t:type png: path-like, file-like, or bytes\n\t:rtype: Generator[tuple(str, bytes)]\n\t\"\"\"\n\tif not is_png(png):\n\t\t# convert to png\n\t\tif isinstance(png, bytes):\n\t\t\twith io.BytesIO(png) as f:\n\t\t\t\twith io.BytesIO() as f2:\n\t\t\t\t\tPIL.Image.open(f).save(f2, \"PNG\", optimize=True)\n\t\t\t\t\tpng = f2.getvalue()\n\t\telse:\n\t\t\twith io.BytesIO() as f2:\n\t\t\t\tPIL.Image.open(png).save(f2, \"PNG\", optimize=True)\n\t\t\t\tpng = f2.getvalue()\n\t\n\tif isinstance(png, str) or hasattr(png, \"__fspath__\"):\n\t\t# path like\n\t\twith open(png, \"rb\") as f:\n\t\t\tpng = f.read()\t\t\n\telif hasattr(png, \"read\"):\n\t\t# file like\n\t\tpng = png.read()\n\t\t\n\treturn chunks_read(png)\n\t\t\ndef make_chunk(type, data):\n\t\"\"\"Create a raw chunk by composing chunk's ``type`` and ``data``. It\n\tcalculates chunk length and CRC for you.\n\n\t:arg str type: PNG chunk type.\n\t:arg bytes data: PNG chunk data, **excluding chunk length, type, and CRC**.\n\t:rtype: bytes\n\t\"\"\"\n\tout = struct.pack(\"!I\", len(data))\n\tdata = type.encode(\"latin-1\") + data\n\tout += data + struct.pack(\"!I\", binascii.crc32(data))\n\treturn out\n\t\nclass PNG:\n\t\"\"\"Represent PNG image. This class should only be initiated with\n\tclassmethods.\"\"\"\n\tdef __init__(self):\n\t\tself.hdr = None\n\t\tself.end = None\n\t\tself.width = None\n\t\tself.height = None\n\t\tself.chunks = []\n\t\t\n\tdef init(self):\n\t\t\"\"\"Extract some info from chunks\"\"\"\n\t\tfor type, data in self.chunks:\n\t\t\tif type == \"IHDR\":\n\t\t\t\tself.hdr = data\n\t\t\telif type == \"IEND\":\n\t\t\t\tself.end = data\n\t\t\t\t\n\t\tif self.hdr:\n\t\t\t# grab w, h info\n\t\t\tself.width, self.height = struct.unpack(\"!II\", self.hdr[8:16])\n\t\t\t\n\t@classmethod\n\tdef open(cls, png):\n\t\t\"\"\"Open a PNG file.\n\t\t\n\t\t:arg png: See :func:`chunks`.\n\t\t:rtype: :class:`PNG`\n\t\t\"\"\"\n\t\to = cls()\n\t\to.chunks = list(chunks(png))\n\t\to.init()\n\t\treturn o\n\t\t\n\t@classmethod\n\tdef from_chunks(cls, chunks):\n\t\t\"\"\"Construct PNG from raw chunks.\n\t\t\n\t\t:arg chunks: A list of ``(chunk_type, chunk_raw_data)``. Also see\n\t\t\t:func:`chunks`.\n\t\t:type chunks: list[tuple(str, bytes)]\n\t\t\"\"\"\n\t\to = cls()\n\t\to.chunks = chunks\n\t\to.init()\n\t\treturn o\n\t\t\n\tdef to_bytes(self):\n\t\t\"\"\"Convert entire image to bytes.\n\t\t\n\t\t:rtype: bytes\n\t\t\"\"\"\n\t\tchunks = [PNG_SIGN]\n\t\tchunks.extend(c[1] for c in self.chunks)\n\t\treturn b\"\".join(chunks)\n\t\t\n\tdef save(self, file):\n\t\t\"\"\"Save entire image to a file.\n\n\t\t:arg file: The destination.\n\t\t:type file: path-like or file-like\n\t\t\"\"\"\n\t\tif isinstance(file, str) or hasattr(file, \"__fspath__\"):\n\t\t\twith open(file, \"wb\") as f:\n\t\t\t\tf.write(self.to_bytes())\n\t\telse:\n\t\t\tfile.write(self.to_bytes())\n\t\t\nclass FrameControl:\n\t\"\"\"A data class holding fcTL info.\"\"\"\n\tdef __init__(self, width=None, height=None, x_offset=0, y_offset=0, delay=100, delay_den=1000, depose_op=1, blend_op=0):\n\t\t\"\"\"Parameters are assigned as object members. See `https://wiki.mozilla.org/APNG_Specification `_ for the detail of fcTL.\n\t\t\"\"\"\n\t\tself.width = width\n\t\tself.height = height\n\t\tself.x_offset = x_offset\n\t\tself.y_offset = y_offset\n\t\tself.delay = delay\n\t\tself.delay_den = delay_den\n\t\tself.depose_op = depose_op\n\t\tself.blend_op = blend_op\n\t\t\n\tdef to_bytes(self):\n\t\t\"\"\"Convert to bytes.\n\t\t\n\t\t:rtype: bytes\n\t\t\"\"\"\n\t\treturn struct.pack(\"!IIIIHHbb\", self.width, self.height, self.x_offset, self.y_offset, self.delay, self.delay_den, self.depose_op, self.blend_op)\n\t\t\n\t@classmethod\n\tdef from_bytes(cls, b):\n\t\t\"\"\"Contruct fcTL info from bytes.\n\t\t\n\t\t:arg bytes b: The length of ``b`` must be *28*, excluding sequence\n\t\t\tnumber and CRC.\n\t\t\"\"\"\n\t\treturn cls(*struct.unpack(\"!IIIIHHbb\", b))\n\nclass APNG:\n\t\"\"\"Represent APNG image.\"\"\"\n\tdef __init__(self, num_plays=0):\n\t\t\"\"\"APNG is composed by multiple PNGs, which can be inserted with \n\t\t:meth:`append`.\n\t\t\n\t\t:arg int num_plays: Number of times to loop. 0 = infinite.\n\t\t\t\n\t\t:var frames: Frames of APNG, a list of ``(png, control)`` tuple.\n\t\t:vartype frames: list[tuple(PNG, FrameControl)]\n\t\t:var int num_plays: same as ``num_plays``.\n\t\t\"\"\"\n\t\tself.frames = []\n\t\tself.num_plays = num_plays\n\t\t\n\tdef append(self, png, **options):\n\t\t\"\"\"Read a PNG file and append one frame.\n\t\t\n\t\t:arg png: See :meth:`PNG.open`.\n\t\t:arg options: See :class:`FrameControl`.\n\t\t\"\"\"\n\t\tpng = PNG.open(png)\n\t\tcontrol = FrameControl(**options)\n\t\tif control.width is None:\n\t\t\tcontrol.width = png.width\n\t\tif control.height is None:\n\t\t\tcontrol.height = png.height\n\t\tself.frames.append((png, control))\n\t\t\n\tdef to_bytes(self):\n\t\t\"\"\"Convert entire image to bytes.\n\t\t\n\t\t:rtype: bytes\n\t\t\"\"\"\n\t\t\n\t\t# grab the chunks we needs\n\t\tout = [PNG_SIGN]\n\t\t# FIXME: it's tricky to define \"other_chunks\". HoneyView stop the \n\t\t# animation if it sees chunks other than fctl or idat, so we put other\n\t\t# chunks to the end of the file\n\t\tother_chunks = []\n\t\tseq = 0\n\t\t\n\t\t# for first frame\n\t\tpng, control = self.frames[0]\n\t\t\n\t\t# header\n\t\tout.append(png.hdr)\n\t\t\n\t\t# acTL\n\t\tout.append(make_chunk(\"acTL\", struct.pack(\"!II\", len(self.frames), self.num_plays)))\n\t\t\n\t\t# fcTL\n\t\tif control:\n\t\t\tout.append(make_chunk(\"fcTL\", struct.pack(\"!I\", seq) + control.to_bytes()))\n\t\t\tseq += 1\n\t\t\n\t\t# and others...\n\t\tidat_chunks = []\n\t\tfor type, data in png.chunks:\n\t\t\tif type in (\"IHDR\", \"IEND\"):\n\t\t\t\tcontinue\n\t\t\tif type == \"IDAT\":\n\t\t\t\t# put at last\n\t\t\t\tidat_chunks.append(data)\n\t\t\t\tcontinue\n\t\t\tout.append(data)\n\t\tout.extend(idat_chunks)\n\t\t\n\t\t# FIXME: we should do some optimization to frames...\n\t\t# for other frames\n\t\tfor png, control in self.frames[1:]:\n\t\t\t# fcTL\n\t\t\tout.append(\n\t\t\t\tmake_chunk(\"fcTL\", struct.pack(\"!I\", seq) + control.to_bytes())\n\t\t\t)\n\t\t\tseq += 1\n\t\t\t\n\t\t\t# and others...\n\t\t\tfor type, data in png.chunks:\n\t\t\t\tif type in (\"IHDR\", \"IEND\") or type in CHUNK_BEFORE_IDAT:\n\t\t\t\t\tcontinue\n\t\t\t\telif type == \"IDAT\":\n\t\t\t\t\t# convert IDAT to fdAT\n\t\t\t\t\tout.append(\n\t\t\t\t\t\tmake_chunk(\"fdAT\", struct.pack(\"!I\", seq) + data[8:-4])\n\t\t\t\t\t)\n\t\t\t\t\tseq += 1\n\t\t\t\telse:\n\t\t\t\t\tother_chunks.append(data)\n\t\t\n\t\t# end\n\t\tout.extend(other_chunks)\n\t\tout.append(png.end)\n\t\t\n\t\treturn b\"\".join(out)\n\t\t\n\t@classmethod\n\tdef from_files(cls, files, **options):\n\t\t\"\"\"Create APNG from multiple files.\n\t\t\n\t\tThis is same as::\n\t\t\n\t\t\tim = APNG()\n\t\t\tfor file in files:\n\t\t\t\tim.append(file, **options)\n\t\t\t\t\n\t\t:arg list files: A list of file. See :meth:`PNG.open`.\n\t\t:arg options: Options for :class:`FrameControl`.\n\t\t:rtype: APNG\n\t\t\"\"\"\n\t\to = cls()\n\t\tfor file in files:\n\t\t\to.append(file, **options)\n\t\treturn o\n\t\t\n\t@classmethod\n\tdef open(cls, file):\n\t\t\"\"\"Open an APNG file.\n\t\t\n\t\t:arg file: See :func:`chunks`.\n\t\t:rtype: APNG\n\t\t\"\"\"\n\t\thdr = None\n\t\thead_chunks = []\n\t\tend = (\"IEND\", make_chunk(\"IEND\", b\"\"))\n\t\t\n\t\tframe_chunks = []\n\t\tframes = []\n\t\tnum_plays = 0\n\t\t\n\t\tcontrol = None\n\t\t\n\t\tfor type, data in chunks(file):\n\t\t\tif type == \"IHDR\":\n\t\t\t\thdr = data\n\t\t\t\tframe_chunks.append((type, data))\n\t\t\telif type == \"acTL\":\n\t\t\t\tnum_frames, num_plays = struct.unpack(\"!II\", data[8:-4])\n\t\t\t\tcontinue\n\t\t\telif type == \"fcTL\":\n\t\t\t\tif any(type == \"IDAT\" for type, data in frame_chunks):\n\t\t\t\t\t# IDAT inside chunk, go to next frame\n\t\t\t\t\tframe_chunks.append(end)\n\t\t\t\t\tframes.append((PNG.from_chunks(frame_chunks), control))\n\t\t\t\t\t\n\t\t\t\t\tcontrol = FrameControl.from_bytes(data[12:-4])\n\t\t\t\t\thdr = make_chunk(\"IHDR\", struct.pack(\"!II\", control.width, control.height) + hdr[16:-4])\n\t\t\t\t\tframe_chunks = [(\"IHDR\", hdr)]\n\t\t\t\telse:\n\t\t\t\t\tcontrol = FrameControl.from_bytes(data[12:-4])\n\t\t\telif type == \"IDAT\":\n\t\t\t\tframe_chunks.extend(head_chunks)\n\t\t\t\tframe_chunks.append((type, data))\n\t\t\telif type == \"fdAT\":\n\t\t\t\t# convert to IDAT\n\t\t\t\tframe_chunks.extend(head_chunks)\n\t\t\t\tframe_chunks.append((\"IDAT\", make_chunk(\"IDAT\", data[12:-4])))\n\t\t\telif type == \"IEND\":\n\t\t\t\t# end\n\t\t\t\tframe_chunks.append(end)\n\t\t\t\tframes.append((PNG.from_chunks(frame_chunks), control))\n\t\t\t\tbreak\n\t\t\telif type in CHUNK_BEFORE_IDAT:\n\t\t\t\thead_chunks.append((type, data))\n\t\t\telse:\n\t\t\t\tframe_chunks.append((type, data))\n\t\t\t\t\n\t\to = cls()\n\t\to.frames = frames\n\t\to.num_plays = num_plays\n\t\treturn o\n\t\t\n\tdef save(self, file):\n\t\t\"\"\"Save entire image to a file.\n\n\t\t:arg file: The destination.\n\t\t:type file: path-like or file-like\n\t\t\"\"\"\n\t\tif isinstance(file, str) or hasattr(file, \"__fspath__\"):\n\t\t\twith open(file, \"wb\") as f:\n\t\t\t\tf.write(self.to_bytes())\n\t\telse:\n\t\t\tfile.write(self.to_bytes())\n","sub_path":"apng/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":10018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"111816894","text":"# DetectPlates.py\n\nimport math\nimport random\n\nimport DetectChars\nimport PossibleChar\nimport PossiblePlate\nimport Preprocess\nimport Recognitor\nimport cv2\nimport numpy as np\n\nPLATE_WIDTH_PADDING_FACTOR = 1.3\nPLATE_HEIGHT_PADDING_FACTOR = 1.5\n\n\ndef detectPlatesInScene(img_original_scene):\n listOfPossiblePlates = []\n\n height, width, num_channels = img_original_scene.shape\n\n img_contours = np.zeros((height, width, 3), np.uint8)\n\n cv2.destroyAllWindows()\n\n if Recognitor.showSteps:\n cv2.imshow(\"0\", img_original_scene)\n\n img_grayscale_scene, img_thresh_scene = Preprocess.preprocess(img_original_scene)\n\n if Recognitor.showSteps:\n cv2.imshow(\"1a\", img_grayscale_scene)\n cv2.imshow(\"1b\", img_thresh_scene)\n\n # find all possible chars in the scene,\n # this function first finds all contours, then only includes contours that could be chars\n # (without comparison to other chars yet)\n listOfPossibleCharsInScene = findPossibleCharsInScene(img_thresh_scene)\n\n if Recognitor.showSteps:\n print(\"step 2 - len(listOfPossibleCharsInScene) = \" + str(\n len(listOfPossibleCharsInScene))) # 131 with MCLRNF1 image\n\n img_contours = np.zeros((height, width, 3), np.uint8)\n\n contours = []\n\n for possibleChar in listOfPossibleCharsInScene:\n contours.append(possibleChar.contour)\n\n cv2.drawContours(img_contours, contours, -1, Recognitor.SCALAR_WHITE)\n cv2.imshow(\"2b\", img_contours)\n\n # given a list of all possible chars, find groups of matching chars\n # in the next steps each group of matching chars will attempt to be recognized as a plate\n listOfListsOfMatchingCharsInScene = DetectChars.findListOfListsOfMatchingChars(listOfPossibleCharsInScene)\n\n if Recognitor.showSteps:\n print(\"step 3 - listOfListsOfMatchingCharsInScene.Count = \" + str(\n len(listOfListsOfMatchingCharsInScene))) # 13 with MCLRNF1 image\n\n img_contours = np.zeros((height, width, 3), np.uint8)\n\n for listOfMatchingChars in listOfListsOfMatchingCharsInScene:\n intRandomBlue = random.randint(0, 255)\n intRandomGreen = random.randint(0, 255)\n intRandomRed = random.randint(0, 255)\n\n contours = []\n\n for matchingChar in listOfMatchingChars:\n contours.append(matchingChar.contour)\n\n cv2.drawContours(img_contours, contours, -1, (intRandomBlue, intRandomGreen, intRandomRed))\n\n cv2.imshow(\"3\", img_contours)\n\n for listOfMatchingChars in listOfListsOfMatchingCharsInScene: # for each group of matching chars\n possiblePlate = extractPlate(img_original_scene, listOfMatchingChars) # attempt to extract plate\n\n if possiblePlate.imgPlate is not None:\n listOfPossiblePlates.append(possiblePlate)\n\n print(\"\\n\" + str(len(listOfPossiblePlates)) + \" possible plates found\")\n\n if Recognitor.showSteps:\n print(\"\\n\")\n cv2.imshow(\"4a\", img_contours)\n\n for i in range(0, len(listOfPossiblePlates)):\n p2fRectPoints = cv2.boxPoints(listOfPossiblePlates[i].rrLocationOfPlateInScene)\n\n cv2.line(img_contours, tuple(p2fRectPoints[0]), tuple(p2fRectPoints[1]), Recognitor.SCALAR_RED, 2)\n cv2.line(img_contours, tuple(p2fRectPoints[1]), tuple(p2fRectPoints[2]), Recognitor.SCALAR_RED, 2)\n cv2.line(img_contours, tuple(p2fRectPoints[2]), tuple(p2fRectPoints[3]), Recognitor.SCALAR_RED, 2)\n cv2.line(img_contours, tuple(p2fRectPoints[3]), tuple(p2fRectPoints[0]), Recognitor.SCALAR_RED, 2)\n\n cv2.imshow(\"4a\", img_contours)\n\n print(\"possible plate \" + str(i) + \", click on any image and press a key to continue . . .\")\n\n cv2.imshow(\"4b\", listOfPossiblePlates[i].imgPlate)\n cv2.waitKey(0)\n # end for\n\n print(\"\\nplate detection complete, click on any image and press a key to begin char recognition . . .\\n\")\n cv2.waitKey(0)\n\n return listOfPossiblePlates\n\n\ndef findPossibleCharsInScene(img_thresh):\n possible_chars = []\n\n possible_chars_count = 0\n\n img_thresh_copy = img_thresh.copy()\n\n img_contours, contours, npa_hierarchy = cv2.findContours(img_thresh_copy, cv2.RETR_LIST,\n cv2.CHAIN_APPROX_SIMPLE)\n\n height, width = img_thresh.shape\n img_contours = np.zeros((height, width, 3), np.uint8)\n\n for i in range(0, len(contours)):\n\n if Recognitor.showSteps:\n cv2.drawContours(img_contours, contours, i, Recognitor.SCALAR_WHITE)\n\n possibleChar = PossibleChar.PossibleChar(contours[i])\n\n if DetectChars.checkIfPossibleChar(possibleChar):\n possible_chars_count = possible_chars_count + 1 # increment count of possible chars\n possible_chars.append(possibleChar) # and add to list of possible chars\n\n if Recognitor.showSteps:\n print(\"\\nstep 2 - len(contours) = \" + str(len(contours)))\n print(\"step 2 - intCountOfPossibleChars = \" + str(possible_chars_count))\n cv2.imshow(\"2a\", img_contours)\n\n return possible_chars\n\n\ndef extractPlate(img_original, list_of_matching_chars):\n possible_plate = PossiblePlate.PossiblePlate() # this will be the return value\n\n list_of_matching_chars.sort(key=lambda c: c.intCenterX)\n\n # calculate the center point of the plate\n fltPlateCenterX = (list_of_matching_chars[0].intCenterX + list_of_matching_chars[\n len(list_of_matching_chars) - 1].intCenterX) / 2.0\n fltPlateCenterY = (list_of_matching_chars[0].intCenterY + list_of_matching_chars[\n len(list_of_matching_chars) - 1].intCenterY) / 2.0\n\n ptPlateCenter = fltPlateCenterX, fltPlateCenterY\n\n # calculate plate width and height\n intPlateWidth = int((list_of_matching_chars[len(list_of_matching_chars) - 1].intBoundingRectX + list_of_matching_chars[\n len(list_of_matching_chars) - 1].intBoundingRectWidth - list_of_matching_chars[\n 0].intBoundingRectX) * PLATE_WIDTH_PADDING_FACTOR)\n\n intTotalOfCharHeights = 0\n\n for matchingChar in list_of_matching_chars:\n intTotalOfCharHeights = intTotalOfCharHeights + matchingChar.intBoundingRectHeight\n # end for\n\n fltAverageCharHeight = intTotalOfCharHeights / len(list_of_matching_chars)\n\n intPlateHeight = int(fltAverageCharHeight * PLATE_HEIGHT_PADDING_FACTOR)\n\n # calculate correction angle of plate region\n fltOpposite = list_of_matching_chars[len(list_of_matching_chars) - 1].intCenterY - list_of_matching_chars[0].intCenterY\n fltHypotenuse = DetectChars.distanceBetweenChars(list_of_matching_chars[0],\n list_of_matching_chars[len(list_of_matching_chars) - 1])\n fltCorrectionAngleInRad = math.asin(fltOpposite / fltHypotenuse)\n fltCorrectionAngleInDeg = fltCorrectionAngleInRad * (180.0 / math.pi)\n\n # pack plate region center point, width and height, and correction angle into rotated rect member variable of plate\n possible_plate.rrLocationOfPlateInScene = (tuple(ptPlateCenter),\n (intPlateWidth, intPlateHeight),\n fltCorrectionAngleInDeg)\n\n # final steps are to perform the actual rotation\n\n # get the rotation matrix for our calculated correction angle\n rotationMatrix = cv2.getRotationMatrix2D(tuple(ptPlateCenter), fltCorrectionAngleInDeg, 1.0)\n\n height, width, numChannels = img_original.shape # unpack original image width and height\n\n imgRotated = cv2.warpAffine(img_original, rotationMatrix, (width, height)) # rotate the entire image\n\n imgCropped = cv2.getRectSubPix(imgRotated, (intPlateWidth, intPlateHeight), tuple(ptPlateCenter))\n\n possible_plate.imgPlate = imgCropped\n\n return possible_plate\n","sub_path":"src/DetectPlates.py","file_name":"DetectPlates.py","file_ext":"py","file_size_in_byte":7851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"113431954","text":"import re\nlines = open(\"input.txt\").readlines()\n\n\ndef redraw():\n grid = [[\".\" for x in range(-1, xmax-xmin+2)]\n for y in range(ymax+1)]\n for c in clay:\n grid[c[1]][c[0]+1] = \"#\"\n grid[0][500-xmin+1] = \"+\"\n for w in water:\n grid[w[1]][w[0]+1] = \"~\"\n for p in path:\n grid[p[1]][p[0]+1] = \"|\"\n for g in grid:\n print(\"\".join(g))\n print()\n\n\ndef fill(x, y):\n settleable = True\n x0 = x\n while((x0-1, y) not in clay and ((x0-1, y+1) in clay or (x0-1, y+1) in water)):\n x0 -= 1\n if (x0-1, y) not in clay:\n settleable = False\n x0 -= 1\n x1 = x\n while((x1+1, y) not in clay and ((x1+1, y+1) in clay or (x1+1, y+1) in water)):\n x1 += 1\n if (x1+1, y) not in clay:\n settleable = False\n x1 += 1\n if settleable:\n for i in range(x0, x1+1):\n water.append((i, y))\n if (i, y) in path:\n path.remove((i, y))\n fill(x, y-1)\n\n else:\n for x in range(x0, x1+1):\n if (x, y) not in path:\n path.append((x, y))\n if (x0, y+1) not in clay and (x0, y+1) not in water:\n pour(x0, y)\n if (x1, y+1) not in clay and (x1, y+1) not in water:\n pour(x1, y)\n\n\ndef pour(x, y):\n global ymax, ymin\n flag = False\n while((x, y+1) not in water and (x, y+1) not in clay):\n y += 1\n\n if (x, y) in path:\n return\n else:\n if y >= ymin:\n path.append((x, y))\n if y == ymax:\n return\n fill(x, y)\n\n\ngrid = [[]]\nclay = []\nwater = []\npath = []\n\n\nfor line in lines:\n numbers = re.findall(r'\\d+', line)\n x = []\n y = []\n if line.split()[0][0] == \"x\":\n x.append(int(numbers[0]))\n y.append(int(numbers[1]))\n y.append(int(numbers[2]))\n else:\n y.append(int(numbers[0]))\n x.append(int(numbers[1]))\n x.append(int(numbers[2]))\n for i in range(x[0], x[-1]+1):\n for j in range(y[0], y[-1]+1):\n clay.append((i, j))\n\nxmax = 0\nymax = 0\nfor c in clay:\n if c[0] > xmax:\n xmax = c[0]\n if c[1] > ymax:\n ymax = c[1]\nxmin = xmax\nymin = ymax\nfor c in clay:\n if c[0] < xmin:\n xmin = c[0]\n if c[1] < ymin:\n ymin = c[1]\n\nfor i in range(len(clay)):\n clay[i] = (clay[i][0]-xmin, clay[i][1])\n\npour(500-xmin, 0)\n\n# redraw()\nprint(\"total=\", len(water)+len(path), \", water=\", len(water))\n","sub_path":"AOC18/d17/run1.py","file_name":"run1.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"127283435","text":"#! /usr/bin/python3\n#*************************************************************************\n#\n# Program: boost\n# File: boost.py\n#\n# Version: V1.0\n# Date: 20.06.21\n# Function: build and test XGBoost models using cis/trans proline \n# datasets\n#\n# Author: Ayub Hareed\n#\n#\n# EMail: ayubm56@gmail.com\n#\n#*************************************************************************\n#\n# This program is not in the public domain, but it may be copied\n# according to the conditions laid out in the accompanying file\n# COPYING.DOC\n#\n# The code may be modified as required, but any modifications must be\n# documented so that the person responsible can be identified. If\n# someone else breaks this code, I don't want to be blamed for code\n# that does not work!\n#\n# The code may not be sold commercially or included as part of a\n# commercial product except as described in the file COPYING.DOC.\n#\n#*************************************************************************\n#\n# Usage: used to buid XGBoost models on cis/trans proline dataset\n# ======\n#\n#*************************************************************************\n\n# Import libraries\nimport math\nimport xgboost as xgb\nimport sys\nimport pandas as pd\nfrom sklearn.preprocessing import StandardScaler # normalise the dataset for machine learning\n\nfrom sklearn.metrics import confusion_matrix # using sci kit learn model to extract tp, tn, fp, fn\n\n\n\n\n#-------------------------------------------------------------\ndef readfile(filename):\n \"\"\"\n read in the proline csv file and converts it into pandas dataframe\n\n\n Input: (string) filename - a filename for the csv filr\n Returns: (DataFrame) df - a pandas dataframe where the first line \n of the CSV file is the header\n\n 20.06.21 Original By: Ayub Hareed\n \"\"\"\n df = pd.read_csv(filename)\n return (df)\n#-------------------------------------------------------------\ndef normalise(df):\n \"\"\"\n data in panda dataframe is normalise using sklearn by removing the \n mean and scaling to unit variance\n\n\n Input: (DataFrame) df - a filename for the csv filr\n Returns: (DataFrames) - two dataframe where the label for the\n binary class is place in one DataFrame and the other \n contains scaled features \n\n 20.06.21 Original By: Ayub Hareed\n \"\"\"\n\n print(df.head())\n # df2 = df.drop(['pdb','atom num'], axis='columns')\n # df3 = df2.drop('atom num', axis='columns')\n\n #extract the features by dropping 'type' column\n x = df.drop('type', axis='columns')\n header = x.columns # removes the header\n # extract the label column \n y = df[['type']]\n print(y.head())\n \n # convert the numinol label data into binary class \n y['type'][y.type == 'trans'] = int(0)\n y['type'][y.type == 'cis'] = int(1)\n \n ## scale the features \n scaler = StandardScaler()\n scaled_x = scaler.fit_transform(x)\n \n print(y.head())\n print(y.value_counts())\n df_scaled_x = pd.DataFrame(scaled_x, columns=header)\n \n return (df_scaled_x, y)\n\n\n\n#-------------------------------------------------------------\ndef mcc_cal(y_actual, predictions):\n \"\"\"\n calculates MCC\n\n Input: (list) y_actual, predictions - the actual label and predictied label\n Returns: (float) mcc - MCC score\n\n 20.06.21 Original By: Ayub Hareed \n \"\"\"\n\n # convert to intiger from string \n y_actual['type'] = y_actual['type'].astype(str).astype(int)\n\n # extract true postive, true negative , false postive and false negative\n tn, fp, fn, tp = confusion_matrix(y_actual, predictions).ravel()\n\n # calcualte mcc \n dinominator = (tp * tn) - (fp*fn)\n numirator = (tp + fp) * (tp + fn) * (tn+fp) * (tn+fn)\n root_numirator = math.sqrt(numirator)\n mcc = dinominator/root_numirator\n\n return (mcc)\n#-------------------------------------------------------------\ndef model_build(x,y, weight, max_del):\n \"\"\"\n takes in the training set and trains an XGBoost model\n\n\n Input: (DataFrame) x,y - the training features and label\n (float) weight, max_del - XGBoost parameters\n\n Returns: (XGBoost model) model - using the x and y input an \n XGBoost model is built\n\n 20.06.21 Original By: Ayub Hareed \n \"\"\"\n\n # convert to intiger from string\n y['type'] = y['type'].astype(str).astype(int)\n\n # the model xgboost requires to first run DMatrix for x and y\n dtrain = xgb.DMatrix(x, label=y)\n\n\n # dictonary containing the parameters used for building XGBoost\n # the num_parallel_tree and sample parameters are used to create \n # a Random Forest like model of XGBoost\n tree_param = {'max_depth': 5, 'eta': 0.1, 'num_parallel_tree': 100, 'scale_pos_weight': weight, 'max_delta_step': max_del,\n 'colsample_bynode': 0.8, 'subsample': 0.8, 'objective': 'binary:logistic', 'tree_method': 'exact'}\n\n # trainning the model \n bst = xgb.train(tree_param, dtrain, 20)\n\n return (bst)\n\n#-------------------------------------------------------------\ndef model_pred(model,x_test):\n \"\"\"\n takes in the testing set and to get XGBoost preditictions \n\n\n Input: (1) (DataFrame) x_test - the test features \n (2) (XGBoost model) model - using the x and y input an \n XGBoost model is built\n Returns: predtions from the model\n\n 20.06.21 Original By: Ayub Hareed \n \"\"\"\n\n dtest = xgb.DMatrix(x_test)\n ypred = model.predict(dtest)\n\n return (ypred)\n#-------------------------------------------------------------\ndef save_pred(y_actual, ypred):\n \"\"\"\n creates a string that contains all the predictions from \n the XGBoost model\n\n\n Input: (lisy) y_actual, ypred - the training features and label\n (float) weight, max_del - XGBoost parameters\n\n Returns: (string) final_result - a string that contains all the \n predictions from the XGBoost model\n\n 20.06.21 Original By: Ayub Hareed \n \"\"\"\n\n # convert the y_test DataFrame to a list\n y_test_lst = y_actual['type'].tolist()\n\n y_act = []\n y_pred = []\n prediction = []\n cis = 0\n trans = 0\n final_result = ''\n # get each prediction in a line with data number, predition class and their probalility\n for i, prob in enumerate(ypred):\n\n if (prob <= 0.50 or prob >= 0.50):\n if (prob > 0.5):\n # print('cis', prob[0])\n y_pred.append(1)\n y_item = y_test_lst[i]\n y_act.append(y_item)\n final_result += str(i+1) + ',cis,' + str(prob) + '\\n'\n\n if (prob < 0.5):\n # print('trans', prob[1])\n y_pred.append(0)\n y_item = y_test_lst[i]\n y_act.append(y_item)\n trans_prob = 1 - prob\n final_result += str(i+1) + ',trans,' + str(trans_prob) + '\\n'\n \n return (final_result)\n\n\n#-------------------------------------------------------------\n# main program\n#-------------------------------------------------------------\n\n# read in the trainning and the testing dataset\nif '-f' in sys.argv:\n i = sys.argv.index('-f')\n f = int(sys.argv[i+1])\n filename = sys.argv[f]\n df = readfile(filename)\n\nif '-t' in sys.argv:\n i = sys.argv.index('-t')\n t = int(sys.argv[i+1])\n df_test = readfile(sys.argv[t])\n\n\n# read in weight and max_delta\nif '-w' in sys.argv:\n i = sys.argv.index('-w')\n w = int(sys.argv[i+1])\n weight = float(sys.argv[w])\nelse:\n weight = 25.0\n\nif '-m' in sys.argv:\n i = sys.argv.index('-m')\n m = int(sys.argv[i+1])\n max_del = float(sys.argv[m])\nelse:\n max_del = 1.0\n\n# location to save the xgboost prediction\nif '-l' in sys.argv:\n i = sys.argv.index('-l')\n l = int(sys.argv[i+1])\n file_location = sys.argv[l]\n\n\n\n# normailise the datasets and split the features and \n# class labels \nx, y = normalise(df)\nx_test, y_actual = normalise(df_test)\n\n# build model\n\nmodel = model_build(x, y, weight, max_del)\n\n# test model\nypred = model_pred(model, x_test)\n\npredictions = [round(value) for value in ypred]\nmcc = mcc_cal(y_actual, predictions)\n\nprint(f'mcc:{mcc}')\n\nif 'file_location' in globals():\n file_location_name = file_location + f'/result_xgb_pred.csv'\n # get predictions\n final_result = save_pred(y_actual, ypred)\n with open(file_location, 'w') as f:\n f.write(final_result)\n\n#---------------------------------------------------------------------------------\n","sub_path":"scripts/models/XGBoost/boost.py","file_name":"boost.py","file_ext":"py","file_size_in_byte":8507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"357021748","text":"# Joseph \"Yo-Yu\" Yusufov, William \"Coyote\" Lin\n# SoftDev pd 02\n# K10: Import / Export Bank\n# 2020-03-04\n\n# Dataset: Earth Meteorite Landings\n# Description: A collection of basic information about 1000 meteorites that have landed on the earth\n# since the 1800s\n# Link: https://data.nasa.gov/resource/y77d-th95.json\n# Summary: We used a separate script (populate.py) to import the json file into the Mongo database. For\n# most functions in this script, we use the db.collection.find() method, with the parameters that we\n# are searching for to retrieve the data we want. In one case, for the findYear() function, we had to\n# use a try except structure, because one of the meteorites did not have a year reported.\n\nfrom pymongo import MongoClient\nfrom pprint import pprint\nfrom bson.json_util import loads\nimport json\nimport datetime\n\n\nclient = MongoClient()\ndb = client.WhoLetTheDogsOut\nmeteorites = db.meteorites\n\n\ndef findName(name):\n for meteorite in meteorites.find({\"name\" : str(name)}):\n pprint(meteorite)\n\n\ndef findMass(mass):\n for meteorite in meteorites.find({\"mass\": str(mass)}):\n pprint(meteorite)\n\n\ndef findYear(year):\n i = 0\n for meteorite in meteorites.find():\n try:\n yeartemp = meteorite[\"year\"][:4]\n if (yeartemp == str(year)):\n pprint(meteorite)\n except: pass\n\n\ndef findCoordinates(lat, long):\n for meteorite in meteorites.find({\"$and\":[\n {\"reclat\" : { \"$gt\": str(lat-2), \"$lt\": str(lat+2)}},\n {\"reclong\" : { \"$gt\": str(long-2), \"$lt\": str(long+2)}}\n ]}):\n pprint(meteorite)\n\nprint(\"=== FINDING NAME ===\")\nfindName(\"Aachen\")\nprint(\"=== FINDING MASS ===\")\nfindMass(21)\nprint(\"=== FINDING YEAR ===\")\nfindYear(1952)\nprint(\"=== FINDING COORDS (25, 105) ===\")\nfindCoordinates(25, 105)\n","sub_path":"10_mongo/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"474999537","text":"import unittest\n\nfrom malcolm.core import call_with_params, Process, Post, Subscribe, Return, \\\n Update, Controller, Queue, TimeoutError\nfrom malcolm.modules.demo.parts import HelloPart, CounterPart\n\n\nclass TestHelloDemoSystem(unittest.TestCase):\n def setUp(self):\n self.process = Process(\"proc\")\n parts = [call_with_params(HelloPart, name=\"hpart\")]\n self.controller = Controller(self.process, \"hello_block\", parts)\n self.process.start()\n\n def tearDown(self):\n self.process.stop(timeout=1)\n\n def test_hello_good_input(self):\n q = Queue()\n request = Post(id=44, path=[\"hello_block\", \"greet\"],\n parameters=dict(name=\"thing\"), callback=q.put)\n self.controller.handle_request(request)\n response = q.get(timeout=1.0)\n self.assertIsInstance(response, Return)\n assert response.id == 44\n assert response.value[\"greeting\"] == \"Hello thing\"\n\n\nclass TestCounterDemoSystem(unittest.TestCase):\n def setUp(self):\n self.process = Process(\"proc\")\n parts = [call_with_params(CounterPart, name=\"cpart\")]\n self.controller = Controller(self.process, \"counting\", parts)\n self.process.start()\n\n def tearDown(self):\n self.process.stop(timeout=1)\n\n def test_counter_subscribe(self):\n q = Queue()\n sub = Subscribe(id=20, path=[\"counting\", \"counter\"], delta=False,\n callback=q.put)\n self.controller.handle_request(sub)\n response = q.get(timeout=1.0)\n self.assertIsInstance(response, Update)\n assert response.id == 20\n assert response.value[\"typeid\"] == \"epics:nt/NTScalar:1.0\"\n assert response.value[\"value\"] == 0\n post = Post(id=21, path=[\"counting\", \"increment\"], callback=q.put)\n self.controller.handle_request(post)\n response = q.get(timeout=1)\n self.assertIsInstance(response, Update)\n assert response.id == 20\n assert response.value[\"value\"] == 1\n response = q.get(timeout=1)\n self.assertIsInstance(response, Return)\n assert response.id == 21\n assert response.value == None\n with self.assertRaises(TimeoutError):\n q.get(timeout=0.05)\n","sub_path":"tests/test_core/test_system_core.py","file_name":"test_system_core.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"474991027","text":"# -*- coding: utf-8 -*-\n\"\"\"\n pygments.lexers.sw\n ~~~~~~~~~~~~~~~~~~~~~\n\n Lexers for semantic web languages.\n\n :copyright: 2007 by Philip Cooper .\n :license: BSD, see LICENSE for more details.\n \n Modified and extended by Gerrit Niezen. (LICENSE file described above is missing, wasn't distributed with original file) \n\"\"\"\n\nimport re\n\nfrom pygments.lexer import RegexLexer, include, bygroups\nfrom pygments.token import Error, Punctuation, \\\n Text, Comment, Operator, Keyword, Name, String, Number, Literal\nfrom pygments.util import shebang_matches\n\n\n__all__ = ['Notation3Lexer','SparqlLexer']\n\n\nclass Notation3Lexer(RegexLexer):\n \"\"\"\n Lexer for the N3 / Turtle / NT\n \"\"\"\n name = 'N3'\n aliases = ['n3', 'turtle']\n filenames = ['*.n3', '*.ttl', '*.NT']\n mimetypes = ['text/rdf+n3','application/x-turtle','application/n3']\n\n tokens = {\n 'comments': [\n (r'(\\s*#.*)', Comment)\n ],\n 'root': [\n include('comments'),\n (r'(\\s*@(?:prefix|base|keywords)\\s*)(\\w*:\\s+)?(<[^> ]*>\\s*\\.\\s*)',bygroups(Keyword,Name.Variable,Name.Namespace)),\n (r'\\s*(<[^>]*\\>)', Name.Class, ('triple','predObj')),\n (r'(\\s*[a-zA-Z_:][a-zA-Z0-9\\-_:]*\\s)', Name.Class, ('triple','predObj')),\n (r'\\s*\\[\\]\\s*', Name.Class, ('triple','predObj')),\n ],\n 'triple' : [\n (r'\\s*\\.\\s*', Text, '#pop')\n ],\n 'predObj': [\n include('comments'),\n (r'(\\s*[a-zA-Z_:][a-zA-Z0-9\\-_:]*\\b\\s*)', Operator, 'object'),\n (r'\\s*(<[^>]*\\>)', Operator, 'object'),\n (r'\\s*\\]\\s*', Text, '#pop'),\n (r'(?=\\s*\\.\\s*)', Keyword, '#pop'), \n ],\n 'objList': [\n include('comments'),\n (r'\\s*\\)', Text, '#pop'),\n include('object')\n ],\n 'object': [\n include('comments'),\n (r'\\s*\\[', Text, 'predObj'),\n (r'\\s*<[^> ]*>', Name.Attribute),\n (r'\\s*(\"\"\"(?:.|\\n)*?\"\"\")(\\@[a-z]{2-4}|\\^\\^?)?\\s*', bygroups(Literal.String,Text)),\n (r'\\s*\".*?[^\\\\]\"(?:\\@[a-z]{2-4}|\\^\\^?)?\\s*', Literal.String),\n (r'\\s*[a-zA-Z0-9\\-_\\:]\\s*', Name.Attribute),\n (r'\\s*\\(', Text, 'objList'),\n (r'\\s*;\\s*\\n?', Text, '#pop'),\n (r'(?=\\s*\\])', Text, '#pop'), \n (r'(?=\\s*\\.)', Text, '#pop'), \n ],\n }\n\n\nclass SparqlLexer(RegexLexer):\n \"\"\"\n Lexer for SPARQL Not Complete\n \"\"\"\n name = 'SPARQL'\n aliases = ['sparql']\n filenames = ['*.sparql']\n mimetypes = ['text/x-sql']\n flags = re.IGNORECASE\n tokens = {\n 'comments': [\n (r'(\\s*#.*)', Comment)\n ],\n 'root': [\n include('comments'), \n (r'(\\s*(?:PREFIX|BASE)\\s+)([\\w-]*:[\\w-]*)?(\\s*<[^> ]*>\\s*)',bygroups(Keyword,Name.Variable,Name.Namespace)),\n (r'(\\s*#.*)', Comment),\n (r'(\\s*)(SELECT\\s*(?:DISTINCT|REDUCED)?)(\\s*)',bygroups(Text, Keyword,Text), 'selectVars'),\n (r'(\\s*)((?:ASK|CONSTRUCT|DESCRIBE)\\s*(?:DISTINCT|REDUCED)?\\s*)((?:\\?[a-zA-Z0-9_-]+\\s*)+|\\*)(\\s*)',\n bygroups(Text, Keyword,Name.Variable,Text)),\n (r'(\\s*)((?:LOAD|CLEAR|DROP|CREATE)\\s*(?:SILENT)?\\s*)(\\s*(?:GRAPH)?\\s*)(\\s*<[^> ]*>\\s*)(;)(\\s*)',\n bygroups(Text, Keyword, Keyword, Name.Attribute, Text, Text)),\n (r'(\\s*)((?:ADD|MOVE|COPY)\\s*(?:SILENT)?\\s*)(\\s*(?:GRAPH)?\\s*)(\\s*<[^> ]*>\\s*)((?:TO)\\s*)(\\s*(?:GRAPH)?\\s*)(\\s*<[^> ]*>\\s*)?(;)(\\s*)',\n bygroups(Text, Keyword, Keyword, Name.Attribute, Keyword, Keyword, Name.Attribute, Text, Text)),\n (r'(\\s*)((?:INSERT|DELETE)\\s*(?:DATA)?)\\s*',bygroups(Text, Keyword),'quaddata'),\n (r'(\\s*)(CONSTRUCT)?\\s*({)',bygroups(Text, Keyword,Punctuation),'graph'),\n (r'(\\s*)(FROM\\s*(?:NAMED)?)(\\s*.*)', bygroups(Text, Keyword,Text)),\n (r'(\\s*)(WHERE)?\\s*({)',bygroups(Text, Keyword, Punctuation),'groupgraph'),\n (r'(\\s*)(LIMIT|OFFSET)(\\s*[+-]?[0-9]+)',bygroups(Text, Keyword,Literal.String)),\n\t\t\t(r'(ORDER BY (?:ASC|DESC)\\s*)(\\()\\s*',bygroups(Text, Keyword,Punctuation),'bindgraph'),\n (r'(\\s*)(})', bygroups(Text, Punctuation)), \n ],\n 'selectVars':[\n (r'(\\s*)(\\*)(\\s*)',bygroups(Text,Keyword,Text), '#pop'),\n (r'(?=\\s*(FROM|WHERE|GROUP|HAVING|ORDER|LIMIT|OFFSET))', Text, '#pop'),\n (r'(\\s*)(\\()(\\s*)', bygroups(Text, Punctuation, Text), 'bindgraph'),\n include('variable'),\n (r'\\n', Text),\n (r'', Text, '#pop'),\n ],\n 'quaddata':[\n (r'(\\s*)({)(\\s*)(GRAPH)(\\s*<[^> ]*>\\s*)', bygroups(Text, Punctuation, Text, Keyword, Name.Attribute), 'quads'),\n (r'(\\s*)({)(\\s*)',bygroups(Text,Punctuation,Text), 'graph'),\n (r'', Text, '#pop'),\n ],\n 'quads':[\n (r'(\\s*)({)(\\s*)(GRAPH)(\\s*<[^> ]*>\\s*)', bygroups(Text, Punctuation, Text, Keyword, Name.Attribute), '#push'),\n (r'(\\s*)({)(\\s*)', bygroups(Text,Punctuation,Text), 'graph'),\n (r'(\\s*)(})(\\s*)', bygroups(Text,Punctuation,Text), '#pop'),\n ],\n 'groupgraph':[\n (r'(\\s*)(UNION)(\\s*)({)(\\s*)', bygroups(Text, Keyword, Text, Punctuation, Text), '#push'),\n (r'(\\s*)({)(\\s*)',bygroups(Text, Punctuation, Text), '#push'),\n include('graph'),\n include('root'),\n (r'', Text, '#pop'),\n ],\n 'graph':[\n (r'(\\s*)(<[^>]*\\>)', bygroups(Text, Name.Class), ('triple','predObj')),\n (r'(\\s*[a-zA-Z_0-9\\-]*:[a-zA-Z0-9\\-_]*\\s)', Name.Class, ('triple','predObj')),\n (r'(\\s*\\?[a-zA-Z0-9_-]*)', Name.Variable, ('triple','predObj')), \n (r'\\s*\\[\\]\\s*', Name.Class, ('triple','predObj')),\n (r'(\\s*)(FILTER)(\\s*)',bygroups(Text, Keyword,Text),'filterConstraint'),\n (r'(\\s*)(BIND)(\\s*)(\\()(\\s*)',bygroups(Text, Keyword, Text, Punctuation, Text),'bindgraph'),\n (r'(\\s*)(OPTIONAL)(\\s*)({)',bygroups(Text, Keyword, Text, Punctuation), '#push'),\n (r'(\\s*)(})(\\s*)(\\.)(\\s*)', bygroups(Text, Punctuation, Text, Punctuation, Text), '#pop'),\n (r'(\\s*)(})', bygroups(Text, Punctuation), '#pop'),\n (r'(\\s*)(\\.)(\\s*)', bygroups(Text, Punctuation, Text), '#pop'),\n ],\n 'triple' : [\n (r'(?=\\s*})', Text, '#pop'), \n (r'(\\s*)(\\.)(\\s*)', bygroups(Text, Punctuation, Text), '#pop'),\n ],\n 'predObj': [\n include('comments'),\n (r'(\\s*\\?[a-zA-Z0-9_-]*\\b\\s*)', Name.Variable,'object'), \n (r'(\\s*[a-zA-Z_:][a-zA-Z0-9\\-_:]*\\b\\s*)', Operator, 'object'),\n (r'\\s*(<[^>]*\\>)', Operator, 'object'),\n (r'\\s*\\]\\s*', Text, '#pop'),\n (r'(?=\\s*\\.\\s*)', Keyword, '#pop'), \n ],\n 'objList': [\n (r'(\\s*)(\\))', bygroups(Text, Punctuation), '#pop'),\n include('object'),\n ],\n 'object': [\n include('variable'),\n (r'\\s*\\[', Text, 'predObj'),\n (r'\\s*<[^> ]*>', Name.Attribute),\n (r'(\\s*)(\"\"\"(?:.|\\n)*?\"\"\")(\\@[a-z]{2-4}|\\^\\^?)?\\s*', bygroups(Text, Literal.String,Text)),\n (r'\\s*\".*?[^\\\\]\"(?:\\@[a-z]{2-4}|\\^\\^?)?\\s*', Literal.String),\n (r'(\\s*)((?:[+-])?\\d+\\.?\\d*)(\\s*)', bygroups(Text, Number, Text)),\n (r'\\s*[a-zA-Z0-9\\-_\\:]+\\s*', Name.Attribute),\n (r'(\\s*)(\\()', bygroups(Text, Punctuation), 'objList'),\n (r',', Punctuation),\n (r'(\\s*)(;)(\\s*)', bygroups(Text, Punctuation, Text), '#pop'),\n (r'(?=\\])', Text, '#pop'), \n (r'\\s*(?=\\.)', Text, '#pop'),\n ],\n 'variable':[\n (r'(\\?[a-zA-Z0-9\\-_]+\\s*)', Name.Variable), \n ],\n 'filterConstraint':[\n include('filterBuiltin'),\n (r'(\\s*)(\\()(\\s*)', bygroups(Text, Punctuation, Text), 'filterExp'),\n (r'(\\s*)(\\.)(\\s*)', bygroups(Text, Punctuation, Text), '#pop'),\n ],\n #filterBuiltin is intended to be included, not pushed\n 'filterBuiltin':[\n include('aggregate'),\n (r'(str|lang|langmates|datatype|bound|iri|uri|bnode)(\\s*)(\\()', bygroups(Name.Builtin, Text, Punctuation), 'objList'),\n (r'(abs|ceil|floor|round)(\\s*)(\\()', bygroups(Name.Builtin, Text, Punctuation), 'objList'),\n (r'(strlen|ucase|lcase|encode_for_uri|contains|strstarts|strends|strbefore|strafter)(\\s*)(\\()', bygroups(Name.Builtin, Text, Punctuation), 'objList'),\n (r'(year|month|day|hours|minutes|seconds|timezone|tz)(\\s*)(\\()', bygroups(Name.Builtin, Text, Punctuation), 'objList'),\n (r'(md5|sha1|sha256|sha384|sha512)(\\s*)(\\()', bygroups(Name.Builtin, Text, Punctuation), 'objList'),\n (r'(if|strlang|strdt)(\\s*)(\\()', bygroups(Name.Builtin, Text, Punctuation), 'objList'),\n (r'(sameterm|isIRI|isURI|isBlank|isLiteral|isNumeric)(\\s*)(\\()', bygroups(Name.Builtin, Text, Punctuation), 'objList'),\n (r'(regex)(\\s*)(\\()', bygroups(Name.Builtin, Text, Punctuation), 'objList'),\n ],\n # aggregate is intended to be included, not pushed\n 'aggregate':[\n (r'(\\s*)(COUNT)(\\s*)(\\()(\\s*)(DISTINCT)?(\\s*)(\\*)(\\s*)', \n bygroups(Text, Keyword, Text, Punctuation, Text, Keyword, Text, Keyword, Text)),\n (r'(\\s*)(COUNT|SUM|MIN|MAX|AVG|SAMPLE)(\\s*)(\\()(\\s*)(DISTINCT)?(\\s*)', \n bygroups(Text, Keyword, Text, Punctuation, Text, Keyword, Text), 'filterExp'),\n (r'(\\s*)(GROUP_CONCAT)(\\s*)(\\()(\\s*)(DISTINCT)?(\\s*)', \n bygroups(Text, Keyword, Text, Punctuation, Text, Keyword, Text), 'groupConcatExp'),\n ],\n 'groupConcatExp':[\n (r'(\\s*)(;)(\\s*)(SEPARATOR)(\\s*)(=)(\\s*)', \n bygroups(Text, Punctuation, Text, Keyword, Text, Operator, Text), 'string'),\n include('filterExp'),\n ],\n 'filterExp':[\n include('filterBuiltin'),\n (r'(\\s*)(\\()(\\s*)', bygroups(Text, Punctuation, Text), '#push'),\n include('variable'),\n include('object'),\n (r'\\s*[+*/<>=~!%&|-]+\\s*', Operator),\n (r'(\\s*)(\\))', bygroups(Text, Punctuation), '#pop'), \n ],\n 'bindgraph':[\n (r'(\\s*)(\\()(\\s*)', bygroups(Text, Punctuation, Text), '#push'),\n (r'\\s*AS\\s*', Keyword),\n (r'(\\s*)(IRI)(\\s*)(\\()(\\s*)',bygroups(Text, Keyword, Text, Punctuation, Text),'iri'),\n (r'(\\s*)(\\))(\\s*)', bygroups(Text, Punctuation, Text), '#pop'),\n include('filterExp'),\n include('variable'),\n include('object'),\n (r'', Text, '#pop'),\n ],\n 'iri':[\n include('object'),\n (r'(\\s*)(\\))', bygroups(Text, Punctuation), '#pop'),\n ],\n 'string':[\n (r'(\\s*)(\"\"\"(?:.|\\n)*?\"\"\")(\\@[a-z]{2-4}|\\^\\^?)?\\s*', bygroups(Text,Literal.String,Text), '#pop'),\n (r'\\s*\".*?[^\\\\]\"(?:\\@[a-z]{2-4}|\\^\\^?)?\\s*', Literal.String, '#pop'),\n ],\n }\n","sub_path":"swlexers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":11308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"225155461","text":"from __future__ import division;\nimport numpy as np; \nimport copy; \nimport random\nimport matplotlib.pyplot as plt;\nfrom sys import path\npath.append('/home/luke/Documents/POMDP/src');\n\nfrom softmaxModels import Softmax\nfrom gaussianMixtures import Gaussian\nfrom gaussianMixtures import GM\nfrom scipy.stats import multivariate_normal as mvn\n\n'''\n***********************************************\nFile: switchTestingSoftmax.py\nAuthor: Luke Burks\nDate: January 2017\n\nTesting the swtiching mode extension of CPOMDP\nsuggested in Brunskill 2010. \nAdding in softmax models for the transition and\nobservation\n\nSimple 1D Problem?\n\nDo the corridor problem, -20,20 with a door\nsomewhere. \n\n3 Modes: left wall, right wall, no wall\n3 Actions: left, right, declare victory\n1 Blank observation? \nReward at the door\n\n\n***********************************************\n'''\n\n\n\n\ndef buildTransitions():\n\tdelA = [[0 for i in range(0,3)] for j in range(0,3)]\n\tmodes = [0]*3; \n\n\t#Mode 0: left wall\n\tmodes[0] = GM(); \n\tmodes[0].addNewG(-18,2,3); \n\t#Act 0: left\n\tdelA[0][0] = 0; \n\n\t#Act 1: right\n\tdelA[0][1] = 1; \n\n\t#Act 2: stay\n\tdelA[0][2] = 0; \n\n\n\n\t#Mode 1: Right Wall\n\tmodes[1] = GM(); \n\tmodes[1].addNewG(18,2,3); \n\t#Act 0: left\n\tdelA[1][0] = -1; \n\n\t#Act 1: right\n\tdelA[1][1] = 0; \n\n\t#Act 2: stay\n\tdelA[1][2] = 0; \n\n\n\t#Mode 2: Corridor\n\tmodes[2] = GM(); \n\tfor i in range(-16,17):\n\t\tmodes[2].addNewG(i,2,1); \n\t#Act 0: left\n\tdelA[2][0] = -1; \n\n\t#Act 1: right\n\tdelA[2][1] = 1; \n\n\t#Act 2: stay\n\tdelA[2][2] = 0;\n\n\n\tdelAVar = 0.01; \n\n\tweight = [-20,-10,0]; \n\tbias = [50,30,0]; \n\tsoftClass = 0;\n\tlow = 0; \n\thigh = 5; \n\tres = 100; \n\n\n\n\t#Define Likelihood Model\n\tmodes = Softmax(weight,bias);\n\t#modes.plot1D(); \n\t'''\n\t#Test and Verify\n\t[a0,b0] = modes[0].plot(vis=False,low=-20,high=20); \n\t[a1,b1] = modes[1].plot(vis=False,low=-20,high=20); \n\t[a2,b2] = modes[2].plot(vis=False,low=-20,high=20); \n\n\tsuma = [0]*len(b0); \n\tfor i in range(0,len(b0)):\n\t\tsuma[i]+=b0[i]; \n\t\tsuma[i]+=b1[i]; \n\t\tsuma[i]+=b2[i]; \n\n\tplt.plot(a0,b0); \n\tplt.plot(a1,b1); \n\tplt.plot(a2,b2); \n\tplt.plot(a0,suma); \n\tplt.show(); \n\t'''\n\n\treturn delA,modes,delAVar;\n\ndef buildObs():\n\t\n\tpz = [0]*3;\n\n\tfor i in range(0,3):\n\t\tpz[i] = GM(); \n\n\tfor i in range(-5,6):\n\t\tif(i*4 <= 0):\n\t\t\tpz[0].addNewG(i*4,4,.2); \n\t\telif(i*4 >= 8):\n\t\t\tpz[1].addNewG(i*4,4,.2); \n\t\telse:\n\t\t\tpz[2].addNewG(i*4,4,.2); \n\n\t#for i in range(0,3):\n\t\t#pz[i].plot(low=-20,high=20); \n\t\n\n\t'''\n\tweight = [-30,-20,-10,0]; \n\tbias = [60,50,30,0]; \n\tsoftClass = 0;\n\tlow = 0; \n\thigh = 5; \n\tres = 100; \n\n\t#Define Likelihood Model\n\tpz = Softmax(weight,bias);\n\n\t#pz.plot1D(); \n\t'''\n\n\treturn pz; \n\n\ndef buildRewards():\n\tr = [0]*3; \n\tfor i in range(0,3):\n\t\tr[i] = GM(); \n\n\t#door location\n\tdloc = 4; \n\n\t#left\n\tfor i in range(-5,6):\n\t\tr[0].addNewG(i*4,4,.2); \n\t\tr[1].addNewG(i*4,4,.2); \n\t\t#a = 0; \n\tr[2].addNewG(dloc,0.25,15); \n\n\t'''\n\tfor i in range(0,3):\n\t\tr[i].plot(low=-20,high=20); \n\t'''\n\n\treturn r; \n\n\ndef beliefUpdate(modes,delA,delAVar,pz,bels,a,o,cond = -1):\n\t\n\t#Initialize\n\tbtmp = GM(); \n\n\tfor d in bels.Gs:\n\t\tfor h in modes:\n\t\t\tfor f in h.Gs:\n\t\t\t\tfor l in pz[o].Gs:\n\t\t\t\t\tC1 = 1/(1/f.var + 1/d.var);\n\t\t\t\t\tc1 = C1*((1/f.var)*f.mean + (1/d.var)*d.mean); \n\n\t\t\t\t\tC2 = C1 + delAVar; \n\t\t\t\t\tc2 = c1+delA[modes.index(h)][a]; \n\n\t\t\t\t\tweight = d.weight*f.weight*l.weight*mvn.pdf(l.mean,c2,l.var+C2); \n\n\t\t\t\t\tvar = 1/((1/l.var)+(1/C2)); \n\t\t\t\t\tmean = var*((1/l.var)*l.mean + (1/C2)*c2); \n\n\t\t\t\t\tg = Gaussian(mean,var,weight); \n\t\t\t\t\tbtmp.addG(g); \n\n\n\tbtmp.normalizeWeights(); \n\n\n\tif(cond != -1):\n\t\tbtmp = btmp.kmeansCondensationN(k=cond,lowInit = -20,highInit=20); \n\t\t#btmp.condense(cond); \n\n\tfor g in btmp:\n\t\twhile(isinstance(g.var,list)):\n\t\t\tg.var = g.var[0]; \n\n\tbtmp.display(); \n\n\treturn btmp; \n\ndef continuousDot(a,b):\n\tsuma = 0; \n\n\tif(isinstance(a,np.ndarray)):\n\t\ta = a.tolist(); \n\t\ta = a[0]; \n\n\tif(isinstance(a,list)):\n\t\ta = a[0];\n\n\ta.clean(); \n\tb.clean(); \n\n\tfor k in range(0,a.size):\n\t\tfor l in range(0,b.size):\n\t\t\tsuma += a.Gs[k].weight*b.Gs[l].weight*mvn.pdf(b.Gs[l].mean,a.Gs[k].mean, np.matrix(a.Gs[k].var)+np.matrix(b.Gs[l].var)); \n\treturn suma; \n\ndef backup(als,modes,delA,delAVar,pz,r,maxMix,b):\n\t\n\tnewAls = [[[0 for i in range(0,len(pz))] for j in range(0,len(delA[0]))] for k in range(0,len(als))]; \n\n\tfor i in range(0,len(als)):\n\t\tfor j in range(0,len(delA[0])):\n\t\t\tfor k in range(0,len(pz)):\n\t\t\t\tnewAls[i][j][k] = GM(); \n\t\t\t\t\n\n\t\t\t\tfor h in range(0,len(modes.weights)):\n\t\t\t\t\t#print(als[i].getVars()); \n\t\t\t\t\ttmp1 = modes.runVB(als[i],h); \n\t\t\t\t\tfor l in range(0,pz[k].size):\n\t\t\t\t\t\tfor p in range(0,tmp1.size):\n\t\t\t\t\t\t\tmixp = tmp1.Gs[p]; \n\t\t\t\t\t\t\tmixl = pz[k].Gs[l]; \n\n\t\t\t\t\t\t\tweight1 = mixp.weight*mixl.weight; \n\t\t\t\t\t\t\tweight = weight1*mvn.pdf(mixp.mean,mixl.mean,mixp.var+mixl.var); \n\n\t\t\t\t\t\t\tc2 = (mixp.var**-1 + mixl.var**-1)**-1; \n\t\t\t\t\t\t\tc1 = c2*(mixp.var**-1 * mixp.mean + mixl.var**-1 * mixl.mean); \n\n\t\t\t\t\t\t\tmean = c1-delA[h][j]; \n\t\t\t\t\t\t\tvar = c2+delAVar; \n\t\t\t\t\t\t\t\n\n\t\t\t\t\t\t\tnewAls[i][j][k].addG(Gaussian(mean,var,weight)); \n\n\n\n\n\tbestVal = -10000000000; \n\tbestAct= 0; \n\tbestGM = []; \n\n\tfor a in range(0,len(delA[0])):\n\t\tsuma = GM(); \n\t\tfor o in range(0,len(pz)):\n\t\t\tsuma.addGM(newAls[np.argmax([continuousDot(newAls[j][a][o],b) for j in range(0,len(newAls))])][a][o]); \n\t\tsuma.scalerMultiply(0.9); \n\t\tsuma.addGM(r[a]); \n\n\t\tfor g in suma.Gs:\n\t\t\tif(isinstance(g.mean,list)):\n\t\t\t\tg.mean = g.mean[0]; \n\t\t\tif(isinstance(g.var,list)):\n\t\t\t\tg.var = g.var[0][0]; \n\n\n\t\t#suma = suma.kmeansCondensationN(k=maxMix,lowInit = -20,highInit=20); \n\n\t\ttmp = continuousDot(suma,b);\n\t\t#print(a,tmp); \n\t\tif(tmp > bestVal):\n\t\t\tbestAct = a; \n\t\t\tbestGM = copy.deepcopy(suma); \n\t\t\tbestVal = tmp; \n\n\tbestGM.action = bestAct; \n\n\treturn bestGM; \n\n\ndef solve(B,modes,delA,delAVar,pz,r,loops = 100):\n\n\tGamma = copy.deepcopy(r[2]); \n\tGamma.scalerMultiply(1/.1); \n\tGamma = [Gamma]; \n\n\tmaxMix = 1; \n\n\tfor counter in range(0,loops):\n\t\tprint(\"Iteration: \" + str(counter+1));\n\t\tbestAlphas = [GM()]*len(B); \n\t\tValue = [0]*len(B);\n\t\tGammaNew = []; \n\n\t\tBTilde = copy.deepcopy(B); \n\n\t\tfor b in B:\n\t\t\tbestAlphas[B.index(b)] = Gamma[np.argmax([continuousDot(Gamma[j],b) for j in range(0,len(Gamma))])];\n\t\t\tValue[B.index(b)] = continuousDot(bestAlphas[B.index(b)],b);\n\n\t\tfor b in BTilde:\n\t\t\t#b = random.choice(BTilde); \n\t\t\t#BTilde.remove(b); \n\n\t\t\tbIndex = 0; \n\t\t\tfor i in B:\n\t\t\t\tif(b.fullComp(i)):\n\t\t\t\t\tbIndex = B.index(i); \n\t\t\t\t\tbreak; \n\n\n\t\t\tal = backup(Gamma,modes,delA,delAVar,pz,r,maxMix,b)\n\t\t\ttmpVal = continuousDot(al,b); \n\n\t\t\tif(tmpVal < Value[bIndex]):\n\t\t\t\tal = bestAlphas[bIndex]; \n\t\t\telse:\n\t\t\t\tbestAlphas[bIndex] = al; \n\n\t\t\t\n\t\t\tfor bprime in BTilde:\n\t\t\t\tif(continuousDot(al,bprime) >= Value[bIndex]):\n\t\t\t\t\tBTilde.remove(bprime); \n\t\t\t\n\n\t\t\t#make sure the alpha doesn't already exist\n\t\t\taddFlag = True; \n\t\t\tfor i in range(0,len(GammaNew)):\n\t\t\t\tif(al.fullComp(GammaNew[i])):\n\t\t\t\t\taddFlag = False; \n\t\t\tif(addFlag and tmpVal > Value[bIndex]):\n\t\t\t\tGammaNew.append(al); \n \n\t\t\n\n\t\t'''\n\t\tfor g in Gamma:\n\t\t\tg.plot(); \n\t\t'''\n\t\t\n\n\t\tprint(\"Number of Alphas: \" + str(len(GammaNew))); \n\t\tav = 0; \n\t\tfor i in range(0,len(GammaNew)):\n\t\t\tav += GammaNew[i].size; \n\t\tav = av/len(GammaNew); \n\t\tprint(\"Average number of mixands: \" + str(av));\n\n\t\tfor i in range(0,len(GammaNew)):\n\t\t\t#GammaNew[i].condense(max_num_mixands=finalMix);\n\t\t\tGammaNew[i] = GammaNew[i].kmeansCondensationN(k = maxMix,lowInit = -20,highInit = 20); \n\n\t\tav = 0; \n\t\tfor i in range(0,len(GammaNew)):\n\t\t\tav += GammaNew[i].size; \n\t\tav = av/len(GammaNew); \n\n\t\tprint(\"Reduced number of mixands: \" + str(av)); \n\t\tprint(\"Actions: \" + str([GammaNew[i].action for i in range(0,len(GammaNew))])); \n\t\tprint(\"\");\n\t\t\n\n\t\tGamma = copy.deepcopy(GammaNew);\n\t\tfor g in Gamma:\n\t\t\tfor gs in g.Gs:\n\t\t\t\tif(isinstance(gs.var,list)):\n\t\t\t\t\tgs.var = gs.var[0][0]; \n\n\n\treturn Gamma; \n\ndef getAction(b,Gamma):\n\tact = Gamma[np.argmax([continuousDot(j,b) for j in Gamma])].action;\n\treturn act; \n\n\n#Build models\n[delA,modes,delAVar] = buildTransitions(); \npz = buildObs();\nr = buildRewards(); \n \n\n#Make belief\nb = GM(); \nb.addNewG(-15,1,1); \n\nact = 2; \nobs = 2; \nmaxMix = 10; \n\n\nB = []; \n'''\nB.append(b); \nb = GM(); \nb.addNewG(4,1,1); \nB.append(b); \nb = GM(); \nb.addNewG(15,1,1); \nB.append(b); \n'''\n'''\nfor i in range(-5,6):\n\tb = GM(); \n\tb.addG(Gaussian(i*4,0.1,1)); \n\t#b.addNewG(i*4,1,1); \n\tB.append(b); \n'''\nb = GM(); \nb.addG(Gaussian(-17,0.1,1)); \nB.append(b); \nb = GM(); \nb.addG(Gaussian(17,0.1,1)); \nB.append(b);\nb = GM(); \nb.addG(Gaussian(4,0.1,1)); \nB.append(b);\nb = GM(); \nb.addG(Gaussian(3,0.1,1)); \nB.append(b);\nb = GM(); \nb.addG(Gaussian(5,0.1,1)); \nB.append(b);\nb = GM(); \nb.addG(Gaussian(0,0.1,1)); \nB.append(b);\n\n\n'''\nGamma = solve(B,modes,delA,delAVar,pz,r,loops=5); \n\nfor i in Gamma:\n\t#i.normalizeWeights(); \n\ti.display(); \n\ti.plot(low=-20,high=20); \n\nf = open('switchPolicy1DSoft_2.npy',\"w\"); \nnp.save(f,Gamma); \nf.close();\n'''\n\n\nGamma = np.load('switchPolicy1DSoft_1.npy');\n\n\n'''\nfor i in Gamma:\n\tprint(i.action); \n\ti.plot(low=-20,high=20); \n'''\n\n\nxs = [i for i in range(-20,20)]; \n\ngs = [0]*len(xs); \nfor i in range(0,len(xs)):\n\tgs[i] = GM(); \n\tgs[i].addG(Gaussian(i-20,2,1)); \nacts = [-1]*len(xs); \nfor i in range(0,len(xs)):\n\tacts[i] = getAction(gs[i],Gamma); \n\nprint(acts); \n\nplt.plot(xs,acts);\nplt.show(); \n\n\n'''\nal1 = [GM()]; \nal1 = copy.deepcopy(r[2]); \nal1.scalerMultiply(1/(.1)); \nal1 = [al1]; \n\nal2 = backup(al1,modes,delA,delAVar,pz,r,maxMix,b)\n\nal2.plot(low=-20,high=20); \n'''\n\n'''\nb.plot(low = -20,high=20); \nb = beliefUpdate(modes,delA,delAVar,pz,b,act,obs,5); \nb.plot(low = -20,high=20); \n'''\n\n","sub_path":"Investigations/Invest9_Switchingmodes/switchTestingSoftmax.py","file_name":"switchTestingSoftmax.py","file_ext":"py","file_size_in_byte":9405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"104021742","text":"from messages import *\nimport config\n\nclass PaxosProposerProtocol:\n\tdef __init__(self,agent,msg):\n\t\tself.agent = agent\n\t\tself.acceptedResponses = {} ## Responses obtained from process for the value proposed by proposer\n\t\tself.sequenceNum = 0\n\t\tself.initMsg = msg\n\n\tdef sendProposedValueToAllAcceptors(self,clientMsg):\n\t\t## Sending the proposed value to all the acceptors by \n\t\t## Creating the corresponding message and putting them in the server Queue\n\t\tballotNumInst = BallotNum(self.agent.pid,self.sequenceNum)\n\t\tfor recv_id in config.connections_made :\n\t\t\t##print \"Protocol : proposer sending proposed values to acceptors\"\n\t\t\tproposedValueMessage = sendProposedValueToAcceptors(clientMsg,ballotNumInst,clientMsg.value,config.currLogEntry,self.agent.pid,recv_id)\n\t\t\tself.agent.proposerToServerQueueLock.acquire()\n\t\t\tconfig.proposerToServerQueue.put(proposedValueMessage)\n\t\t\tself.agent.proposerToServerQueueLock.release()\n\n\n\tdef sendConfigurationMessageToAllAcceptors(self,newId,clientMsg):\n\t\t## Doing it exactly like the normal messages\n\t\tballotNumInst = BallotNum(self.agent.pid,self.sequenceNum)\n\t\tfor recv_id in config.connections_made :\n\t\t\t##print \"Protocol : proposer sending configuration to acceptors\"\n\t\t\tproposedConfigurationMessage = configurationMessageToAcceptors(clientMsg,config.currLogEntry,newId,recv_id,self.agent.pid)\n\t\t\tself.agent.proposerToServerQueueLock.acquire()\n\t\t\tconfig.proposerToServerQueue.put(proposedConfigurationMessage)\n\t\t\tself.agent.proposerToServerQueueLock.release()\n\n\n\tdef accepted_value_from_acceptor(self,msg):\n\t\tself.acceptedResponses[msg.senderId] = msg.value\n\n\tdef sendProposedLeaderToAllAcceptors(self):\n\t\tself.sequenceNum += 1\n\t\tballotNumInst = BallotNum(self.agent.pid,self.sequenceNum)\n\t\tfor recv_id in config.connections_made:\n\t\t\t##print \"Proposer proposing itself to be the leader\"\n\t\t\tself.agent.proposerToServerQueueLock.acquire()\n\t\t\tproposedLeaderMessage = sendProposedLeaderToAcceptors(self.agent.pid,recv_id,ballotNumInst,config.currLogEntry)\n\t\t\tconfig.proposerToServerQueue.put(proposedLeaderMessage) \n\t\t\tself.agent.proposerToServerQueueLock.release()\n\t\t\t##print \"Log Value : \" + str(config.currLogEntry)\n\n\n\nclass PaxosAcceptorProtocol:\n\tdef __init__(self,agent):\n\t\tself.agent = agent\n\t\tself.highestBallotAccepted = BallotNum(self.agent.pid,-1)\n\t\tself.acceptedVal= None\n\t\tself.responses = {}\n\n\tdef sendAcceptedValueToProposer(self,msg):\n\t\tif(msg.ballotNum >= self.highestBallotAccepted):\n\t\t\t##print \"Protocol :acceptor sending accepted valuee to leader\"\n\t\t\tself.highestBallotAccepted = msg.ballotNum\n\t\t\tif(self.acceptedVal == None):\n\t\t\t\t## Only when the accepted value before is none. This is required to disable rewriting log.\n\t\t\t\tself.acceptedVal = msg.value\n\t\t\t\tself.agent.acceptorToServerQueueLock.acquire()\n\t\t\t\t## leader Id needs to be changed from leader Election\n\t\t\t\tconfig.acceptorToServerQueue.put(sendAcceptedValueToLeader(msg.clientMsg,msg.ballotNum,msg.logEntry,self.acceptedVal,self.agent.pid,msg.leaderId))\n\t\t\t\tself.agent.acceptorToServerQueueLock.release()\n\t\t\t\t## sending accepted value to all the learners\n\t\t\t\tself.sendAcceptedValueToAllLearners(msg)\n\n\t\t\telse:\n\t\t\t\t## Send the NAK to the process since the value is already present in the log. Currently not required.\n\t\t\t\t## Since if the value is sent to majority of the acceptors then learners would have know about and entered into log\n\t\t\t\tpass\n\n\tdef sendAcceptedValueToAllLearners(self,msg):\n\t\tfor recv_id in config.connections_made:\n\t\t\t##print \"Protocol :acceptor sending accepted value to learner\"\n\t\t\tacceptedValueMessage = sendAcceptedValueToLearners(msg.clientMsg,msg.ballotNum,msg.logEntry,self.acceptedVal,self.agent.pid,msg.leaderId,recv_id)\n\t\t\tself.agent.acceptorToServerQueueLock.acquire()\n\t\t\tconfig.acceptorToServerQueue.put(acceptedValueMessage)\n\t\t\tself.agent.acceptorToServerQueueLock.release()\n\n\n\tdef sendAcceptedConfigurationToAllLearners(self,msg):\n\t\tfor recv_id in config.connections_made:\n\t\t\t##print \"Protocol :acceptor sending accepted configuration to learner\"\n\t\t\tacceptedConfigurationMessage = configurationMessageToLearners(msg.clientMsg,msg.logEntry,self.agent.pid,msg.newId,recv_id,msg.leaderId)\n\t\t\tself.agent.acceptorToServerQueueLock.acquire()\n\t\t\tconfig.acceptorToServerQueue.put(acceptedConfigurationMessage)\n\t\t\tself.agent.acceptorToServerQueueLock.release()\n\n\tdef sendAcceptedLeaderToProposer(self,msg):\n\t\t##print \"Message : Num Value :\" + str(msg.ballotNum.num) + \" Agent Id : \" + str(msg.ballotNum.id)\n\t\t##print \"Self : Num Value :\" + str(self.highestBallotAccepted.num) + \" Agent Id : \" + str(self.highestBallotAccepted.id)\n\t\tif(msg.ballotNum > self.highestBallotAccepted and self.acceptedVal == None):\n\t\t\t##print \"Protocol : acceptor sending to leader that it has accepted it to be leader\"\n\t\t\tself.highestBallotAccepted = msg.ballotNum\n\t\t\tself.agent.acceptorToServerQueueLock.acquire()\n\t\t\tconfig.acceptorToServerQueue.put(sendAcceptedLeaderToProposer(self.agent.pid,msg.leaderId,msg.ballotNum,msg.logEntry))\n\t\t\tself.agent.acceptorToServerQueueLock.release()\t\n\n\tdef recvdAcceptedLeaderToProposer(self,msg):\n\t\t## Store the responses obtained from other process w.r.t Ballot Number value because \n\t\t## incase of multiple Iteration Ballot number is only changed\n\t\tif msg.ballotNum.num not in self.responses:\n\t\t\tself.responses[msg.ballotNum.num] = {}\n\t\tself.responses[msg.ballotNum.num][msg.senderId] = 1\n\t\tself.hasMajority(msg)\n\t\n\tdef hasMajority(self,msg):\n\t\tmajority = len(config.connections_made)/2 + 1\n\t\tif (len(self.responses[msg.ballotNum.num]) >= majority):\n\t\t\t##print \"Current Process has been elected as the leader in Phase 1\"\n\t\t\tconfig.phase1Leader = self.agent.pid\n\t\t\n\t\t\n\t\t\t\n\n\nclass PaxosLearnerAcceptingValueProtocol:\n\tdef __init__(self,agent):\n\t\tself.agent = agent\n\t\tself.responses = {}\n\n\tdef hasMajority(self,msg):\n\t\tmajority = len(config.connections_made)/2 + 1\n\t\tif (len(self.responses) >= majority):\n\t\t\tconfig.log[msg.logEntry] = msg.value\n\t\t\t## storing the complete msg in another log\n\t\t\tconfig.msgLog[msg.logEntry] = msg\n\t\t\t## The log entry is set here because it is way of telling the proposer that log has entries till this entry if the process becomes a leader.\n\t\t\tconfig.currLogEntry = msg.logEntry\n\t\t\t## During the leader election, if there is a race,server getting majority in the second round is winner\n\t\t\tconfig.currLeader = msg.leaderId\n\t\t\t##print \"value written in log\" \n\t\t\t##print config.log\n\t\t\t## Check the message that is committed in the log is the one which you have sent to the Leader\n\t\t\t\n\t\t\tconfig.requestLeaderLock.acquire()\n\t\t\tif(len(config.requestSentToLeaderQueue) > 0):\n\t\t\t\tmsgSentToLeader = config.requestSentToLeaderQueue[0]\n\t\t\t\tif(msgSentToLeader.msgId == msg.clientMsg.msgId):\n\t\t\t\t\t##print \"Request sent to leader is committed, removing from the queue\"\n\t\t\t\t\tconfig.requestSentToLeaderQueue.pop()\n\t\t\tconfig.requestLeaderLock.release()\n\n\t\t\t\n\tdef updateResponse(self,msg):\n\t\t##print \"Protocol : learner has received response\"\n\t\tself.responses[msg.senderId] = msg.value\n\t\tself.hasMajority(msg)\n\t\t\t\n\n\t\t\t\n\n","sub_path":"protocol.py","file_name":"protocol.py","file_ext":"py","file_size_in_byte":6993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"38042533","text":"# https://github.com/plamere/spotipy/blob/master/spotipy/util.py\n# http://www.acmesystems.it/python_httpd\n\nfrom bottle import route, run, request\nimport spotipy\nimport sys, os\nimport spotifork\nimport appex\nfrom spotipy import oauth2\n\nPORT_NUMBER = 8080\nSPOTIPY_REDIRECT_URI = \"http://localhost:8080\"\nSCOPE = \"user-library-read,playlist-modify-public\"\nCACHE = \".spotipyoauthcache\"\n\nuser_config = spotifork.load_config()\nSPOTIPY_CLIENT_ID = user_config[\"client_id\"]\nSPOTIPY_CLIENT_SECRET = user_config[\"client_secret\"]\n\nsp_oauth = oauth2.SpotifyOAuth(\n\tSPOTIPY_CLIENT_ID,\n\tSPOTIPY_CLIENT_SECRET,\n\tSPOTIPY_REDIRECT_URI,\n\tscope=SCOPE,\n\tcache_path=CACHE, )\n\ndef mk_playlist():\n\taccess_token = \"\"\n\ttoken_info = sp_oauth.get_cached_token()\n\n\tif token_info:\n\t\tprint(\"Found cached token!\")\n\t\taccess_token = token_info[\"access_token\"]\n\tif access_token:\n\t\tsp = spotipy.Spotify(auth=access_token)\n\t\t#results = sp.current_user()\n\t\turl = appex.get_url()\n\t\tid = url.split('/')[-1].split('?')[0]\n\t\tprint(url, id)\n\t\tplaylist_id = f\"spotify:playlist:{id}\"\n\t\tusername = user_config[\"username\"]\n\t\tplaylist = sp.playlist(playlist_id)\n\t\tresults = spotifork.get_tracks(sp, playlist[\"id\"])\n\t\tspotifork.write_tracks(sp, username, playlist, results)\n\t\treturn True\n\treturn False\n\n@route(\"/\")\ndef index():\n\taccess_token = \"\"\n\n\ttoken_info = sp_oauth.get_cached_token()\n\n\tif token_info:\n\t\tprint(\"Found cached token!\")\n\t\taccess_token = token_info[\"access_token\"]\n\telse:\n\t\turl = request.url\n\t\tcode = sp_oauth.parse_response_code(url)\n\t\tif code:\n\t\t\ttoken_info = sp_oauth.get_access_token(code)\n\t\t\taccess_token = token_info[\"access_token\"]\n\n\tif access_token:\n\t\tsp = spotipy.Spotify(auth=access_token)\n\t\t#results = sp.current_user()\n\t\turl = appex.get_url()\n\t\tid = url.split('/')[-1].split('?')[0]\n\t\tprint(url, id)\n\t\tplaylist_id = f\"spotify:playlist:{id}\"\n\t\tusername = user_config[\"username\"]\n\t\tplaylist = sp.playlist(playlist_id)\n\t\tresults = spotifork.get_tracks(sp, playlist[\"id\"])\n\t\tspotifork.write_tracks(sp, username, playlist, results)\n\t\t#sys.stderr.close()\n\t\treturn results\n\n\telse:\n\t\treturn htmlForLoginButton()\n\n\ndef htmlForLoginButton():\n\tauth_url = getSPOauthURI()\n\thtmlLoginButton = \"Login to Spotify\"\n\treturn htmlLoginButton\n\n\ndef getSPOauthURI():\n\tauth_url = sp_oauth.get_authorize_url()\n\treturn auth_url\n\nif not mk_playlist():\n\trun(host=\"\", port=8080)\nos._exit(0)\n","sub_path":"spotipy_oauth_demo.py","file_name":"spotipy_oauth_demo.py","file_ext":"py","file_size_in_byte":2373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"87106598","text":"import numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sympy.solvers import solve\nfrom sympy import Symbol\nfrom matplotlib import patches\nimport matplotlib.patches as mpatches\nimport scipy.io as sio\n\n# plotting configuration\nratio = 1.5\nfigure_len, figure_width = 15*ratio, 12*ratio\nfont_size_1, font_size_2 = 36*ratio, 36*ratio\nlegend_size = 18*ratio\nline_width, tick_len = 3*ratio, 10*ratio\nmarker_size = 15*ratio\nplot_line_width = 5*ratio\nhfont = {'fontname': 'Arial'}\n\npal = sns.color_palette(\"deep\")\n\n# simulation setup\ndt = 0.0001\nT = int(13/dt)\n\n# neuronal parameters\ntau_e, tau_i = 0.020, 0.010\nl_b_SSN = [True]\n\nU, U_max = 1, 6\ntau_x = 0.20\n\n# network parameters\nn_exc, n_inh = 200, 50\nn_groups = 2\n\nalpha_e, alpha_i = 2, 2\n\np = 1\np_fraction = 0.75\ng_bs = 1.35\n\nl_g_e = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n\nfor g_e in l_g_e:\n\n J_ee = 1.2\n J_ie = 1.0\n J_ei = 1.0\n J_ii = 1.0\n\n J_ee_2 = J_ee * 0.3\n J_ie_2 = J_ie * 0.4\n J_ei_2 = J_ei * 0.1\n J_ii_2 = J_ii * 0.1\n\n b_frozen_STP = False\n\n sns.set(style='ticks')\n b_save_connectivity_mat = True\n\n J = np.zeros((n_exc + n_inh, n_exc + n_inh))\n\n for i in range(n_groups):\n for j in range(n_groups):\n if i == j:\n J[int(n_exc / n_groups) * i: int(n_exc / n_groups) * (i + 1),\n int(n_exc / n_groups) * i: int(n_exc / n_groups) * (i + 1)] = J_ee / (\n int(n_exc / n_groups) - 1) # E to E connections within the same assembly\n J[n_exc + int(n_inh / n_groups) * i: n_exc + int(n_inh / n_groups) * (i + 1),\n int(n_exc / n_groups) * i: int(n_exc / n_groups) * (i + 1)] = J_ie / (\n int(n_exc / n_groups)) # E to I connections within the same assembly\n J[int(n_exc / n_groups) * i: int(n_exc / n_groups) * (i + 1),\n n_exc + int(n_inh / n_groups) * i: n_exc + int(n_inh / n_groups) * (i + 1)] = J_ei / (\n int(n_inh / n_groups)) # I to E connections within the same assembly\n J[n_exc + int(n_inh / n_groups) * i: n_exc + int(n_inh / n_groups) * (i + 1),\n n_exc + int(n_inh / n_groups) * i: n_exc + int(n_inh / n_groups) * (i + 1)] = J_ii / (\n int(n_inh / n_groups) - 1) # I to I connections within the same assembly\n else:\n J[int(n_exc / n_groups) * i: int(n_exc / n_groups) * (i + 1),\n int(n_exc / n_groups) * j: int(n_exc / n_groups) * (j + 1)] = J_ee_2 / (\n int(n_exc / n_groups) - 1) # E to E connections within the same assembly\n J[n_exc + int(n_inh / n_groups) * i: n_exc + int(n_inh / n_groups) * (i + 1),\n int(n_exc / n_groups) * j: int(n_exc / n_groups) * (j + 1)] = J_ie_2 / (\n int(n_exc / n_groups)) # E to I connections within the same assembly\n\n # keep I-E and I-I\n J[int(n_exc / n_groups) * i: int(n_exc / n_groups) * (i + 1),\n n_exc + int(n_inh / n_groups) * j: n_exc + int(n_inh / n_groups) * (j + 1)] = J_ei_2 / (\n int(n_inh / n_groups)) # I to E connections across assemblies\n J[n_exc + int(n_inh / n_groups) * i: n_exc + int(n_inh / n_groups) * (i + 1),\n n_exc + int(n_inh / n_groups) * j: n_exc + int(n_inh / n_groups) * (j + 1)] = J_ii_2 / (\n int(n_inh / n_groups)) # I to I connections across assemblies\n\n np.fill_diagonal(J, 0)\n\n r_e, r_i = np.zeros(n_exc), np.zeros(n_inh)\n z_e, z_i = np.zeros(n_exc), np.zeros(n_inh)\n l_r_e_1, l_r_e_1_2 , l_r_e_2, l_r_i_1, l_r_i_2 = [], [], [], [], []\n x = np.ones(int(n_exc))\n y = np.ones((n_exc, n_exc))\n g = np.zeros(n_exc + n_inh)\n\n for k in range(T):\n if 50000 < k < 70000:\n g[int(n_exc / n_groups)*0: int(n_exc / n_groups)*0+int(int(n_exc / n_groups) * p_fraction)] = g_e\n g[int(n_exc / n_groups)*0+int(int(n_exc / n_groups) * p_fraction): int(n_exc / n_groups)*0+int(int(n_exc / n_groups))] = g_bs\n g[int(n_exc / n_groups)*1: int(n_exc / n_groups)*1+int(int(n_exc / n_groups))] = g_bs\n elif 90000 < k < 110000:\n g[int(n_exc / n_groups)*0: int(n_exc / n_groups)*0+int(int(n_exc / n_groups))] = g_bs + (g_e - g_bs) * p\n g[int(n_exc / n_groups)*1: int(n_exc / n_groups)*1+int(int(n_exc / n_groups))] = g_bs + (g_e - g_bs) * (1-p)\n else:\n g[: int(n_exc)] = np.ones(n_exc) * g_bs\n g[int(n_exc):] = np.ones(int(n_inh)) * 2\n\n g = g * (g > 0)\n\n # SSN part\n z_e = np.dot(J[:n_exc, :n_exc], r_e) - np.dot(J[:n_exc, n_exc:], r_i) + g[:n_exc]\n z_i = np.dot(J[n_exc:, :n_exc], x*r_e) - np.dot(J[n_exc:, n_exc:], r_i) + g[n_exc:]\n\n z_e = z_e * (z_e > 0)\n z_i = z_i * (z_i > 0)\n\n r_e = r_e + (-r_e + np.power(z_e, alpha_e)) / tau_e * dt\n r_i = r_i + (-r_i + np.power(z_i, alpha_i)) / tau_i * dt\n\n # add noise\n r_e = r_e * (r_e > 0)\n r_i = r_i * (r_i > 0)\n\n x = x + ((U - x) / tau_x + U * (U_max - x) * r_e) * dt\n x = x * (x > 0)\n x[x > U_max] = U_max\n\n l_r_e_1.append(np.mean(r_e[int(n_exc / n_groups) * 0: int(int(n_exc / n_groups) * p_fraction)]))\n l_r_e_1_2.append(np.mean(r_e[int(int(n_exc / n_groups) * p_fraction): int(n_exc / n_groups) * (0 + 1)]))\n l_r_e_2.append(np.mean(r_e[int(n_exc / n_groups) * 1: int(n_exc / n_groups) * (1 + 1)]))\n l_r_i_1.append(np.mean(r_i[int(n_inh / n_groups) * 0: int(n_inh / n_groups) * (0 + 1)]))\n l_r_i_2.append(np.mean(r_i[int(n_inh / n_groups) * 1: int(n_inh / n_groups) * (1 + 1)]))\n\n l_r_e_1 = np.asarray(l_r_e_1)\n l_r_e_1_2 = np.asarray(l_r_e_1_2)\n l_r_e_2 = np.asarray(l_r_e_2)\n l_r_i_1 = np.asarray(l_r_i_1)\n l_r_i_2 = np.asarray(l_r_i_2)\n\n sio.savemat('data/Fig_5_Pattern_separation_activity_EI_STP_E12_gE_' + str(g_e) + '_U_max_' + str(U_max) + '.mat', mdict={'E12': l_r_e_1_2})\n sio.savemat('data/Fig_5_Pattern_separation_activity_EI_STP_E2_gE_' + str(g_e) + '_U_max_' + str(U_max) + '.mat', mdict={'E2': l_r_e_2})","sub_path":"src/Fig_5_Pattern_separation_EI_STP_changing_gE.py","file_name":"Fig_5_Pattern_separation_EI_STP_changing_gE.py","file_ext":"py","file_size_in_byte":6157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"597795589","text":"import tensorflow as tf\nfrom tensorflow.keras import initializers, optimizers, losses, layers, regularizers\n\n# general setting:\n# select model type\n#model_type = 'baseline'\nmodel_type = 'cascade'\n#model_type = 'parallel'\n\n# set number of classes\n# 3 for low/medium/high tones\n# 9 for each individual stimuli\nnum_classes = 9\n\nreuse_model = False # for DL models\ntesting = False # for all models\nlog_dir = '../cache/tensorboard-logdir/'\nmodel_dir = '../data/saved_models/'\nimg_dir = '../data/conf_matrix/' + model_type + '/'\ndata_dir = '../data/animals/015/'\n\n# architecture parameters:\nkernel_height_default = 3 # paper: 3\nkernel_width_default = 3 # paper: 3\nkernel_stride_default = 1\nkernel_dilation_default = 1\nconv_channel_num = 32\npadding_default = 'same'\nactivation_default = tf.nn.elu\nuse_bias_default = True\nbias_default = 0.1\nstddev_default = 0.1\nbias_initializer_default = initializers.constant(bias_default)\n\n# recommended initializer for neural network weights and filters according to https://keras.io/initializers/ (22.10.19)\nweights_initializer_default = initializers.TruncatedNormal(stddev=stddev_default)\n\nlambda_loss_amount = 0.005\nkernel_reg_default = regularizers.l2(l=lambda_loss_amount)\nbias_reg_default = regularizers.l2(l=lambda_loss_amount)\nact_reg_default = None\n\nkernel_constraint_default = None\nbias_constraint_default = None\n\ndropout_keep_rate = 0.5\n\n# training parameters\nlearning_rate = 1e-4\nopt_default = optimizers.Adam(learning_rate)\nloss_default = losses.SparseCategoricalCrossentropy()\ntraining_epochs = 2000\nmetric_frequency = 10\n\nviz_model = False\ndev_svm = False # set true when testing for param c\ntest_svm = False # set true when testing SVM\n\nif model_type == 'cascade':\n batch_size = 64\nelif model_type == 'parallel':\n batch_size = 128\nelif model_type == 'baseline':\n batch_size = 128\n","sub_path":"default_params.py","file_name":"default_params.py","file_ext":"py","file_size_in_byte":1839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"624857545","text":"\"\"\"empty message\n\nRevision ID: 9c28300c89db\nRevises: 468733527910\nCreate Date: 2017-12-10 09:08:06.435755\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '9c28300c89db'\ndown_revision = '468733527910'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('imposibilitadas',\n sa.Column('materia_id', sa.Integer(), nullable=False),\n sa.Column('encuesta_id', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['encuesta_id'], ['encuestas.id'], ),\n sa.ForeignKeyConstraint(['materia_id'], ['materias.id'], ),\n sa.PrimaryKeyConstraint('materia_id', 'encuesta_id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('imposibilitadas')\n # ### end Alembic commands ###\n","sub_path":"core/migrations/versions/9c28300c89db_.py","file_name":"9c28300c89db_.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"635111658","text":"# -*- coding: utf-8 -*-\nfrom pyquery import PyQuery as PQ\nfrom banks import BankParser, TYPE_OFFICE, TYPE_ATM, TYPE_EXCHANGE, TYPE_TERMINAL\nfrom model import Point, CHECK_OFFICIAL\nfrom normalizers.address import split_address_place\nfrom normalizers.phone import normalize_phones\nfrom normalizers.text import normalize_text, replace_br\nfrom normalizers.time import normalize_time\nfrom utils import get_url, warning_not_official_coordinates, strip\n\n\nclass TrustBankParser(BankParser):\n\n uid = 'trust'\n site = 'http://trustbank.by'\n official_offices = True\n official_exchanges = True\n official_atms = True\n official_terminals = True\n\n __parse_data_offices_url = 'http://www.trustbank.by/offices/'\n __parse_data_exchanges_url = 'http://www.trustbank.by/private/currency-exchange/'\n __parse_data_atms_url = 'http://www.trustbank.by/private/cards/ATM-network/'\n __parse_data_terminals_url = 'http://www.trustbank.by/private/cards/psts/'\n\n def get_offices(self):\n points = []\n offices_page = PQ(get_url(self.__parse_data_offices_url))\n for office_item in map(PQ, offices_page('.office a')):\n url = self.site + office_item.attr('linkoffice')\n page = PQ(get_url(url))\n point = self.__parse_office(page('#body'))\n if point:\n points.append(point)\n return points\n\n def __parse_office(self, item):\n point = Point()\n point.prov = self.uid\n point.type = TYPE_OFFICE\n point.name = normalize_text(item('h1').text())\n point.address, point.place = split_address_place(item('tr:eq(2) td:eq(1)').text())\n phones = []\n phone_html = replace_br(item('tr:eq(5) td:eq(1)').html(), ';;;')\n if phone_html:\n phones += map(strip, PQ(phone_html).text().split(';;;'))\n phone_html = replace_br(item('tr:eq(6) td:eq(1)').html(), ';;;')\n if phone_html:\n phones += map(strip, PQ(phone_html).text().split(';;;'))\n point.phones = normalize_phones(filter(lambda phone: phone.startswith((u'+', u'тел')), phones))\n point.time = normalize_time(item('tr:eq(8) td:eq(1)').text())\n point.check_information = CHECK_OFFICIAL\n warning_not_official_coordinates(point)\n return point\n\n def get_exchanges(self):\n points = []\n page = PQ(get_url(self.__parse_data_exchanges_url))\n for item in map(PQ, page('#body ul:eq(0) li')):\n point = self.__parse_exchange(item)\n if point:\n points.append(point)\n return points\n\n def __parse_exchange(self, item):\n point = Point()\n point.prov = self.uid\n point.type = TYPE_EXCHANGE\n sub_items = item.text().split(u'—')\n point.name = normalize_text(sub_items[0])\n point.address, point.place = split_address_place(sub_items[1])\n point.check_information = CHECK_OFFICIAL\n warning_not_official_coordinates(point)\n return point\n\n def get_atms(self):\n points = []\n page = PQ(get_url(self.__parse_data_atms_url))\n for item in map(PQ, page('#body .tbl tr:gt(0)')):\n point = self.__parse_atm(item)\n if point:\n points.append(point)\n return points\n\n def __parse_atm(self, item):\n point = Point()\n point.prov = self.uid\n point.type = TYPE_ATM\n point.address, point.place = split_address_place(item('td:eq(2)').text())\n point.place = normalize_text(item('td:eq(1)').text())\n point.currency = map(strip, item('td:eq(4)').text().split(','))\n point.time = normalize_time(item('td:eq(3)').text())\n point.check_information = CHECK_OFFICIAL\n warning_not_official_coordinates(point)\n return point\n\n def get_terminals(self):\n points = []\n page = PQ(get_url(self.__parse_data_terminals_url))\n for item in map(PQ, page('#body .tbl tr:gt(0)')):\n point = self.__parse_terminal(item)\n if point:\n points.append(point)\n return points\n\n def __parse_terminal(self, item):\n point = Point()\n point.prov = self.uid\n point.type = TYPE_TERMINAL\n point.address, point.place = split_address_place(item('td:eq(2)').text())\n point.place = normalize_text(item('td:eq(1)').text())\n point.currency = map(strip, item('td:eq(4)').text().split(','))\n if point.currency:\n point.deposit = True\n else:\n point.deposit = False\n point.time = normalize_time(item('td:eq(3)').text())\n point.check_information = CHECK_OFFICIAL\n warning_not_official_coordinates(point)\n return point","sub_path":"banks/trust.py","file_name":"trust.py","file_ext":"py","file_size_in_byte":4717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"616888151","text":"import json\nimport requests\nfrom discord.ext import commands\n\nclass Update:\n def __init__(self, client):\n self.client = client\n\n @commands.command()\n async def update(self, ctx):\n\n with open('twitch.json') as talk1:\n data1 = json.load(talk1)\n talk1.close()\n\n streamers = data1['streamers']\n twitch_client_id = data1['token']['Twitch_Client-ID']\n\n for streamer in streamers:\n\n stream = requests.get(\"https://api.twitch.tv/helix/streams?user_id={0}\".format(streamer), headers=twitch_client_id).json()\n\n if streamer == data1['streamers'][0]:\n live_notification = data1['discord']['live_notification']['streamer1']\n returndata_msgid = 'disc_msg_id_str1'\n print(\"Streamer 1\")\n elif streamer == data1['streamers'][1]:\n live_notification = data1['discord']['live_notification']['streamer2']\n returndata_msgid = 'disc_msg_id_str2'\n print(\"Streamer 1\")\n\n if live_notification == \"alreadysend\":\n print(\"i am here now\")\n channel = self.client.get_channel(int(data1['discord']['discord_channel']))\n livemessage = await channel.get_message(int(data1['discord']['live_notification'][\"{}\".format(returndata_msgid)]))\n print(livemessage)\n await livemessage.delete()\n\n await ctx.send(\"Updating bot and restarting...\")\n await self.client.close()\n\ndef setup(client):\n client.add_cog(Update(client))\n","sub_path":"cogs/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"15779072","text":"# # Numpy_Assignment_2::\n\n# ## Question:1\n\n# ### Convert a 1D array to a 2D array with 2 rows?\n\n# #### Desired output::\n\n# array([[0, 1, 2, 3, 4],\n# [5, 6, 7, 8, 9]])\n\n# In[4]:\n\n\nimport numpy as np\noneD_toD = np.arange(10).reshape(2,5)\n\n\n# ## Question:2\n\n# ### How to stack two arrays vertically?\n\n# #### Desired Output::\n'''array([[0, 1, 2, 3, 4],\n [5, 6, 7, 8, 9],\n [1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1]])\n '''\n# In[31]:\n\n\na = np.arange(10).reshape(2,5)\nb= np.ones((2,5),dtype=int)\nstack = np.vstack((a,b))\n\n\n# ## Question:3\n\n# ### How to stack two arrays horizontally?\n\n# #### Desired Output::\n'''array([[0, 1, 2, 3, 4, 1, 1, 1, 1, 1],\n [5, 6, 7, 8, 9, 1, 1, 1, 1, 1]])'''\n# In[27]:\n\n\na = np.arange(10).reshape(2,5)\nb= np.ones((2,5),dtype=int)\nnp.hstack((a,b))\n\n\n# ## Question:4\n\n# ### How to convert an array of arrays into a flat 1d array?\n\n# #### Desired Output::\n#array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n# In[36]:\n\n\narray_of_array = np.arange(20).reshape(4,5)\narray_of_array.flatten()\n\n\n# ## Question:5\n\n# ### How to Convert higher dimension into one dimension?\n\n# #### Desired Output::\n#array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])\n# In[38]:\n\n\narray_of_array = np.arange(15).reshape(3,5)\narray_of_array.ravel()\n\n\n# ## Question:6\n\n# ### Convert one dimension to higher dimension?\n\n# #### Desired Output::\n'''array([[ 0, 1, 2],\n[ 3, 4, 5],\n[ 6, 7, 8],\n[ 9, 10, 11],\n[12, 13, 14]])'''\n# In[58]:\n\n\ntwo_D=np.arange(15).reshape(5,3)\n\n\n# ## Question:7\n\n# ### Create 5x5 an array and find the square of an array?\n\n# In[62]:\n\n\na = np.arange(25).reshape(5,5)\nnp.square(a)\n\n\n# ## Question:8\n\n# ### Create 5x6 an array and find the mean?\n\n# In[64]:\n\n\na = np.arange(30).reshape(5,6)\nnp.mean(a)\n\n\n# ## Question:9\n\n# ### Find the standard deviation of the previous array in Q8?\n\n# In[65]:\n\n\nnp.std(a)\n\n\n# ## Question:10\n\n# ### Find the median of the previous array in Q8?\n\n# In[66]:\n\n\nnp.median(a)\n\n\n# ## Question:11\n\n# ### Find the transpose of the previous array in Q8?\n\n# In[68]:\n\n\nprint(a.T)\n\n\n# ## Question:12\n\n# ### Create a 4x4 an array and find the sum of diagonal elements?\n\n# In[75]:\n\n\narr = np.ones((4,4))\nnp.diagonal(arr).sum()\n\n\n# ## Question:13\n\n# ### Find the determinant of the previous array in Q12?\n\n# In[76]:\n\n\nnp.linalg.det(arr)\n\n\n# ## Question:14\n\n# ### Find the 5th and 95th percentile of an array?\n\n# In[80]:\n\n\nnp.percentile(arr,5)\nnp.percentile(arr,95)\n\n\n# ## Question:15\n\n# ### How to find if a given array has any null values?\n\n# In[85]:\n\n\nnp.isnan(arr)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"PIAIC79700_Assignment2.py","file_name":"PIAIC79700_Assignment2.py","file_ext":"py","file_size_in_byte":2536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"348562535","text":"import slack\nimport pandas as pd\nimport random\nimport requests\nfrom pylibgen import Library\n\ndf=pd.read_excel('data.xlsx',sheet_name='entity')\n\n#novel Dialog\ndef novel(Int_Ent_Sent,conn,user_name):\n title = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['novel_name'])]\n author = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['writer'])]\n publisher = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['publisher'])]\n year = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['year'])]\n descr = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['descr'])]\n while (1):\n if title:\n #proceed\n l = Library()\n ids = l.search(title[0])\n if ids:\n for id in ids:\n b1 = l.lookup(id, fields=[\"*\"])\n for b in b1:\n slack.post_message(conn, random.choice([\"details of novel \"+b.__dict__['title']+\" are\"]))\n if author:\n slack.post_message(conn, random.choice([\"author : \" + str(b.__dict__['author']) ]))\n if publisher:\n slack.post_message(conn, random.choice([\"publisher : \" + str(b.__dict__['publisher'])]))\n if year:\n slack.post_message(conn, random.choice([\"year : \" + str(b.__dict__['year'])]))\n if descr:\n slack.post_message(conn, random.choice([\"descr : \" + str(b.__dict__['descr']) ]))\n break\n else:\n slack.post_message(conn,'Please enter the novel name correctly')\n title= [slack.get_message(conn)][0]\n\n#movie Dialog\ndef movie(Int_Ent_Sent,conn,user_name):\n title = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['movie_name'])]\n actors= [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['actors'])]\n awards = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['awards'])]\n country= [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['country'])]\n genre = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['genre'])]\n director = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['director'])]\n language = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['language'])]\n poster = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['poster'])]\n plot = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['plot'])]\n rate = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['rate'])]\n ratings= [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['ratings'])]\n release = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['release'])]\n runtime = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['runtime'])]\n writer = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['writer'])]\n website = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['website'])]\n while (1):\n\n omdb_api_key = '3b3c8518'\n details = requests.get('http://www.omdbapi.com/?t={0}&apikey={1}'.format(title[0] if title else '', omdb_api_key)).json()\n if details['Response']=='True':\n slack.post_message(conn, random.choice([\"details of movie \" + details['Title'] + \" are\"]))\n if actors:\n slack.post_message(conn, random.choice([\"actors : \" + str(details['Actors'])]))\n if awards:\n slack.post_message(conn, random.choice([\"awards : \" + str(details['Awards'])]))\n if country:\n slack.post_message(conn, random.choice([\"country : \" + str(details['Country'])]))\n if genre:\n slack.post_message(conn, random.choice([\"genre of movie is \" + str(details['Genre'])]))\n if director :\n slack.post_message(conn, random.choice([\"directed by \" + str(details['Director'])]))\n if language:\n slack.post_message(conn, random.choice([\"language : \" + str(details['Language'])]))\n if poster:\n slack.post_message(conn, random.choice([\"link to poster : \" + str(details['Poster'])]))\n if plot:\n slack.post_message(conn, random.choice([\"plot of movie : \" + str(details['Plot'])]))\n if rate:\n slack.post_message(conn, random.choice([\"rate : \" + str(details['Rated'])]))\n if ratings:\n for b in details['Ratings']:\n slack.post_message(conn,random.choice([\"rating at \" + str(b['Source']) + \" is \"+str(b['Value'])]))\n if release:\n slack.post_message(conn, random.choice([\"release date is \" + str(details['Released'])]))\n if runtime :\n slack.post_message(conn, random.choice([\"runtime of show: \" + str(details['Runtime'])]))\n if writer:\n slack.post_message(conn, random.choice([\"written by \" + str(details['Writer'])]))\n if website:\n slack.post_message(conn, random.choice([\"website link : \" + str(details['Website'])]))\n break\n else :\n slack.post_message(conn, 'Please enter the movie name correctly')\n title = [slack.get_message(conn)][0]\n\n#climate Dialog\ndef weather(Int_Ent_Sent,conn,user_name):\n #update acc to excel\n temp = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['temp'])]\n pressure = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['pressure'])]\n temp_min = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['temp_min'])]\n temp_max = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['temp_max'])]\n speed = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['speed'])]\n deg = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['direction'])]\n country = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['country'])]\n humidity = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['humidity'])]\n loc = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['location_names'])]\n coord = [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['coordinates'])]\n wea= [i.lower() for i in list(dict.fromkeys(Int_Ent_Sent['Entity'])) if i.lower() in list(df['weather'])]\n while (1):\n if loc:\n weather_reposonse = requests.get('http://api.openweathermap.org/data/2.5/weather?q='+str(loc[0])+'&APPID=0583a32030db119217dc0595d49acc33')\n climate = weather_reposonse.json()\n slack.post_message(conn, random.choice([\"climate at \"+str(loc[0])+\" is as follows \"]))\n if coord:\n slack.post_message(conn, random.choice([\"coordinates are \" + str(climate['coord']['lon']) + \" longitude and \" + str(climate['coord']['lat']) + \" latitude \"]))\n if wea:\n slack.post_message(conn,random.choice([\"weather at \"+str(loc[0])+\" is \" + str(climate['weather'][0]['description'])]))\n if temp:\n slack.post_message(conn, random.choice([\"temperature is \" + str(climate['main']['temp'])+\"Fahrenheit\"]))\n if pressure:\n slack.post_message(conn, random.choice([\"pressure is \" + str(climate['main']['pressure'])+\"hectopascals\"]))\n if humidity:\n slack.post_message(conn, random.choice([\"humidity is \" + str(climate['main']['humidity'])+\"%\"]))\n if temp_min:\n slack.post_message(conn, random.choice([\"minimum temperature is \" + str(climate['main']['temp_min'])+\"Fahrenheit\"]))\n if temp_max:\n slack.post_message(conn, random.choice([\"maximum temperature is \" + str(climate['main']['temp_max'])+\"Fahrenheit\"]))\n if speed:\n slack.post_message(conn, random.choice([\"speed of wind is \" + str(climate['wind']['speed'])+\"miles/hour\"]))\n if deg:\n slack.post_message(conn, random.choice([\"direction of wind is \" + str(climate['wind']['deg']+\" degrees\")]))\n if country:\n slack.post_message(conn, random.choice([\"written by \" + str(climate['country'])]))\n break\n else:\n slack.post_message(conn,'Please enter the location name correctly')\n loc= [slack.get_message(conn)][0]\n\n#Welcome Dialog\ndef Welcome(Int_Ent_Sent,conn,user_name):\n welcome_responses=[\"Hi \"+user_name+\"! How are you doing?\",\"Hello \"+user_name+\"! How can I help you?\",\"Good day \"+user_name+\"! What can I do for you today?\",\"Greetings \"+user_name+\"! How can I assist?\"]\n slack.post_message(conn,random.choice(welcome_responses))\n","sub_path":"dialogs.py","file_name":"dialogs.py","file_ext":"py","file_size_in_byte":9543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"364466114","text":"import re\nimport sqlite3\nfrom ast import literal_eval\nfrom urllib.parse import parse_qs\n\nimport dash_bootstrap_components as dbc\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport pandas as pd\nimport plotly.graph_objects as go\nfrom dash.dependencies import Input, Output\n\nfrom config import app\nfrom src.data_collector import BusinessDataSet, project_root\n\nbase_data = BusinessDataSet(category='restaurant', state='ON')\ncities_fix = {\n 'East Gwillimburry': 'East Gwillimbury',\n 'ETOBICOKE': 'Etobicoke',\n 'Etibicoke': 'Etobicoke',\n 'Etobiicoke': 'Etobicoke',\n 'King': 'King City',\n 'Oakridges': 'Oak Ridges',\n 'Oakvile': 'Oakville',\n 'Richmond Hil': 'Richmond Hill',\n 'Scarobrough': 'Scarborough',\n 'Thornhil': 'Thornhill',\n 'Tornto': 'Toronto',\n 'Whiitby': 'Whitby',\n 'Whtiby': 'Whitby',\n}\nbase_data.fix_values('city', cities_fix)\n\nconfig = {\n 'displaylogo': False,\n 'modeBarButtonsToRemove': ['zoom2d', 'zoomIn2d', 'zoomOut2d', 'autoScale2d', 'resetScale2d', 'toggleSpikelines']\n}\n\n\ndef create_citymapper_link(row):\n return f'https://citymapper.com/directions?endcoord={row.latitude}%2C{row.longitude}&' \\\n f\"endname={row['name'].replace(' ', '%20')}&\" \\\n f\"endaddress={row.address.replace(' ', '%20').replace(',', '%2C')}%2C%20{row.city}%2C%20{row.postal_code}\"\n\n\ndef create_hours_table(hours: dict):\n header_values = ['Day:', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\n table_header = [html.Thead(html.Tr([html.Th(_) for _ in header_values]))]\n\n row = [html.Td('Hours:')]\n for day in ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']:\n if day in hours:\n row.append(html.Td(hours[day].replace(':0', ':00')))\n else:\n row.append(html.Td('Closed'))\n row = html.Tr(row)\n\n table = dbc.Table(\n table_header + [html.Tbody(row)],\n bordered=True,\n hover=True,\n responsive=True,\n striped=True,\n )\n return table\n\n\ndef create_location_map(df):\n hover_template = '{}
    {}
    {}
    {}
    Rating: {:.1f}'\n\n df['hover'] = hover_template.format(df['name'], df.address, df.city, df.postal_code, df.stars)\n\n fig = go.Figure(go.Scattermapbox(\n lat=[df.latitude],\n lon=[df.longitude],\n mode='markers',\n hovertemplate=[df.hover],\n marker=go.scattermapbox.Marker(size=14, color='#9c1919', opacity=0.7),\n ))\n\n fig.update_layout(\n mapbox=dict(\n style=\"open-street-map\",\n zoom=15,\n center=go.layout.mapbox.Center(\n lat=df.latitude,\n lon=df.longitude,\n ),\n ),\n margin={\"r\": 0, \"t\": 0, \"l\": 0, \"b\": 0},\n height=400,\n )\n\n return fig\n\n\ndef get_review_data(business_id: str) -> pd.DataFrame:\n query = f\"SELECT * FROM REVIEWS WHERE REVIEWS.BUSINESS_ID = '{business_id}' LIMIT 200\"\n conn = None\n try:\n conn = sqlite3.connect(project_root / 'data/reviews.sqlite')\n print(\"Connection to SQLite DB successful\")\n except sqlite3.Error as e:\n print(f\"The error '{e}' occurred\")\n\n df = pd.read_sql(query, conn, parse_dates={'DATE': '%Y-%m-%d %H:%M:%S'})\n return df\n\n\ndef get_location_attributes(loc: pd.Series):\n pattern = re.compile(r'(?<=[a-z])(?=[A-Z])')\n\n def convert_attr_to_text(text: str):\n s = pattern.sub(' ', text)\n s = \"\".join(filter(lambda x: not x.isdigit(), s))\n return s\n\n def convert_true_to_tick(s):\n try: # if 'True' or '1' or dict etc\n s = literal_eval(s)\n except ValueError: # if just a regular string\n pass\n\n if s is True:\n return '\\u2705' # True to tick\n elif isinstance(s, int):\n return '$' * s # convert price value to number of $'s\n else:\n try:\n return s.title().replace('_', ' ')\n except AttributeError: # for False\n return s\n\n d_dicts = [_ for _ in loc.attributes.keys() if '{' in loc.attributes[_]]\n d_strs = [\n _ for _ in loc.attributes.keys() if\n ('{' not in loc.attributes[_] and loc.attributes[_].lower() not in ['False', u'none'])\n ]\n\n d_dicts = {convert_attr_to_text(_): literal_eval(loc.attributes[_]) for _ in d_dicts}\n d_strs = {convert_attr_to_text(_): convert_true_to_tick(loc.attributes[_]) for _ in d_strs}\n\n d_strs = {_: d_strs[_] for _ in d_strs if d_strs[_] not in [False, 'None', '']}\n\n return d_dicts, d_strs\n\n\ndef create_attributes_detail(s: dict, d: dict):\n body = list()\n for att in s:\n body.append(html.P(f'{att} - {s[att]}'))\n f_s = list()\n for item in d:\n f = d[item]\n trues = [_.title() for _ in f if f[_]]\n f_s.append({item: trues})\n body.append(html.P(f'{item.title()} - {\", \".join(trues)}'))\n return body[:10]\n\n\nlayout = dbc.Container([\n dbc.Row([\n dbc.Col([\n html.H2(id='deep-dive-header')\n ])\n ]),\n html.Br(),\n dbc.Row([\n dbc.Col([\n dcc.Graph(id='deep-dive-map', config=config)\n ], width=6),\n dbc.Col([\n html.H4('About'),\n dbc.Row([\n dbc.Col(id='deep-dive-attributes-table', width=6),\n dbc.Col(id='deep-dive-attributes-table-2', width=6),\n ])\n ], width=6),\n ]),\n html.Br(),\n dbc.Row([\n dbc.Col([\n dbc.Row([\n dbc.Button(\n 'Open in Citymapper',\n id='citymapper-link',\n color='success',\n className='mr-1',\n block=True,\n ),\n dbc.Button(\n 'Return to Home',\n id='deep-dive-home-link',\n color='primary',\n className='mr-1',\n block=True,\n href='/',\n ),\n ])\n ], width=3),\n dbc.Col(id='deep-dive-hours', width=9),\n ]),\n html.Br(),\n html.Br(),\n # dbc.Row([])\n])\n\n\n@app.callback(\n [\n Output('deep-dive-header', 'children'),\n Output('citymapper-link', 'href'),\n Output('deep-dive-map', 'figure'),\n Output('deep-dive-hours', 'children'),\n Output('deep-dive-attributes-table', 'children'),\n Output('deep-dive-attributes-table-2', 'children'),\n ],\n [\n Input('url', 'search')\n ]\n)\ndef update(url):\n if '?' not in url:\n selected = base_data.data.nlargest(1, 'rank_value').iloc[0]\n else:\n params = parse_qs(url)\n selected = base_data.data.loc[params.get('?id')].iloc[0]\n\n # todo:\n # top reviews\n # description\n # similar restaurants\n\n dicts, strs = get_location_attributes(selected)\n\n attributes = create_attributes_detail(strs, dicts)\n a1 = attributes[:10]\n a2 = attributes[10:]\n\n return selected['name'], create_citymapper_link(selected), create_location_map(selected), \\\n create_hours_table(selected.hours), a1, a2\n","sub_path":"src/pages/deep_dive.py","file_name":"deep_dive.py","file_ext":"py","file_size_in_byte":7144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"306753122","text":"import pandas as pd\r\nimport numpy as np\r\ntrain=pd.read_csv(\"C:/Users/parekhku/OneDrive - Merck Sharp & Dohme, Corp/Desktop/KP_Donotdelete/R/IMS/py/project/Amex/train.csv\")\r\ntrain.info()\r\ntrain.head()\r\ntrain.isna().sum()\r\ncampdata=pd.read_csv(\"C:/Users/parekhku/OneDrive - Merck Sharp & Dohme, Corp/Desktop/KP_Donotdelete/R/IMS/py/project/Amex/campaign_data.csv\")\r\ncampdata.info()\r\ncampdata.isna().sum()\r\ncampdata.head()\r\n\r\ncoupon=pd.read_csv(\"C:/Users/parekhku/OneDrive - Merck Sharp & Dohme, Corp/Desktop/KP_Donotdelete/R/IMS/py/project/Amex/coupon_item_mapping.csv\")\r\ncoupon.info()\r\ncoupon.isna().sum()\r\n\r\ncustdemo=pd.read_csv(\"C:/Users/parekhku/OneDrive - Merck Sharp & Dohme, Corp/Desktop/KP_Donotdelete/R/IMS/py/project/Amex/customer_demographics.csv\")\r\ncustdemo.info()\r\ncustdemo.isna().sum()\r\ncustdemo.no_of_children.unique()\r\ncustdemo.no_of_children[custdemo.no_of_children.isna()]=0\r\ncustdemo.isna().sum()\r\ncustdemo.marital_status[custdemo.marital_status.isna()]=\"NotGiven\"\r\ncustdemo.isna().sum()\r\ncustdemo.marital_status.unique()\r\n\r\ncusttran=pd.read_csv(\"C:/Users/parekhku/OneDrive - Merck Sharp & Dohme, Corp/Desktop/KP_Donotdelete/R/IMS/py/project/Amex/customer_transaction_data.csv\")\r\ncusttran.info()\r\ncusttran.head()\r\ncusttran.isna().sum()\r\n\r\nitemdata=pd.read_csv(\"C:/Users/parekhku/OneDrive - Merck Sharp & Dohme, Corp/Desktop/KP_Donotdelete/R/IMS/py/project/Amex/item_data.csv\")\r\nitemdata.info()\r\nitemdata.isna().sum()\r\n\r\ntest=pd.read_csv(\"C:/Users/parekhku/OneDrive - Merck Sharp & Dohme, Corp/Desktop/KP_Donotdelete/R/IMS/py/project/Amex/test.csv\")\r\ntest.info()\r\ntest.isna().sum()\r\n\r\nct=np.zeros((len(train))).astype(str)\r\nfor i in range(len(train)):\r\n ct[i]=campdata.campaign_type[np.where(train.campaign_id[i]==campdata.campaign_id)[0][0]]\r\n \r\nct1=pd.DataFrame(ct) \r\nct1.columns=[\"campaign_type\"]\r\ntrain1=pd.concat([train,ct1],axis=1)\r\ntrain1.head() #attached camp type \r\ntrain1.info()\r\n#coupid=np.zeros((len(custtran)))\r\n#for i in range(len(custtran)):\r\n# try:\r\n# coupid[i]=coupon.coupon_id[np.where(custtran.item_id[i]==coupon.item_id)[0][0]]\r\n# except:\r\n# coupid[i]=0\r\n \r\n#train.info() \r\n#x1=train.coupon_id[0]\r\n#y1=train.customer_id[0]\r\n#xx=custtran[custtran.customer_id==y1]\r\n#yy=coupon[coupon.coupon_id==x1]\r\n#\r\n#for i in range(len(yy)):\r\n# for j in range(len(xx)):\r\n# if yy.item_id.iloc[i]==xx.item_id.iloc[j]:\r\n# print(i,\"and\",j)\r\n \r\n \r\n\r\n \r\n\r\ntrain2=pd.merge(train1,custdemo , how='left', on='customer_id') \r\ntrain2.isna().sum() #there are NAs for which customers data not available\r\n\r\n\r\n\r\n\r\n\r\n\r\nct=np.zeros((len(test))).astype(str)\r\nfor i in range(len(test)):\r\n ct[i]=campdata.campaign_type[np.where(test.campaign_id[i]==campdata.campaign_id)[0][0]]\r\n \r\nct1=pd.DataFrame(ct) \r\nct1.columns=[\"campaign_type\"]\r\ntest1=pd.concat([test,ct1],axis=1)\r\ntest1.head() #attached camp type \r\ntest1.info()\r\n\r\ntest2=pd.merge(test1,custdemo , how='left', on='customer_id') \r\ntest2.isna().sum() #there are NAs for which customers data not available\r\n\r\n\r\n\r\n\r\ntrain3=pd.merge(custtran,itemdata, how='left', on='item_id') \r\ntrain3.info()\r\ntrain3.isna().sum() \r\n#train4=train3[train3.coupon_discount]\r\ndisc=[]\r\nfor i in np.sort((np.unique(train3.customer_id))):\r\n disc.append(np.sum(train3.coupon_discount[train3.customer_id==i]))\r\nimport matplotlib.pyplot as plt\r\nplt.plot(abs(np.array(disc)))\r\nnp.mean(disc)\r\nnp.median(disc)\r\nl=np.zeros((len(disc))).astype('str')\r\nfor i in range(len(disc)):\r\n if abs(disc[i])>abs(np.mean(disc)):\r\n l[i]=\"Likely\"\r\n else:\r\n l[i]=\"Unklikely\"\r\nl=pd.DataFrame(l,columns=[\"couponlikely\"])\r\nw=np.sort((np.unique(train3.customer_id))) \r\nw=pd.DataFrame(w,columns=[\"customer_id\"])\r\nlw=pd.concat([l,w],axis=1)\r\ntrain4=pd.merge(train2,lw, how='left', on='customer_id') \r\ntrain4.isna().sum()\r\ntrain4.info()\r\ntest4=pd.merge(test2,lw, how='left', on='customer_id') \r\ntest4.isna().sum()\r\ntest4.info()\r\n\r\n\r\n\r\n\r\ndisc1=[]\r\nfor i in np.sort((np.unique(train3.item_id))):\r\n disc1.append(np.sum(train3.coupon_discount[train3.item_id==i]))\r\n if(i%100==0):\r\n print(i)\r\n \r\nimport matplotlib.pyplot as plt\r\nplt.plot(abs(np.array(disc1)))\r\nnp.mean(disc1)\r\nnp.median(disc1)\r\nl1=np.zeros((len(disc1))).astype('str')\r\n\r\nfor i in range(len(disc1)):\r\n if abs(disc1[i])>0:#from graph chekced and found 0 tims avg disc as a limit\r\n l1[i]=\"likely\"\r\n else:\r\n l1[i]=\"unklikely\"\r\n if(i%100==0):\r\n print(i)\r\n \r\nl1=pd.DataFrame(l1,columns=[\"itemcouponlikely\"])\r\nw1=np.sort((np.unique(train3.item_id)))\r\nw1=pd.DataFrame(w1,columns=[\"item_id\"])\r\nlw1=pd.concat([l1,w1],axis=1)\r\n\r\ntrain5=pd.merge(coupon,lw1, how='left', on='item_id') \r\nlikelycouponid=train5.coupon_id[train5.itemcouponlikely==\"likely\"]\r\n\r\ntrain4[\"likelycouponid\"]=np.zeros(len(train4))\r\nfor i in range(len(train4)):\r\n if(train4.coupon_id[i] in likelycouponid):\r\n train4[\"likelycouponid\"][i]=1\r\n if(i%100==0):\r\n print(i)\r\ntrain4.info() \r\n\r\ntest4[\"likelycouponid\"]=np.zeros(len(test4))\r\nfor i in range(len(test4)):\r\n if(test4.coupon_id[i] in likelycouponid):\r\n test4[\"likelycouponid\"][i]=1\r\n if(i%100==0):\r\n print(i)\r\n \r\ntest4.info() \r\n\r\n\r\n\r\nx=pd.merge(train,coupon,how='inner',on='coupon_id')\r\nx.info()\r\nx.head()\r\nlength1=np.zeros((len(x.coupon_id.unique())))\r\na=0\r\nfor i in x.coupon_id.unique():\r\n length1[a]=len(x.item_id[x.coupon_id==i].unique())\r\n a+=1\r\n\r\nim=pd.concat([pd.DataFrame(x.coupon_id.unique()),pd.DataFrame(length1)],axis=1)\r\nim.columns=['coupon_id','numitemcoup']\r\ntrain_im=pd.merge(train,im,how='left',on='coupon_id')\r\n\r\n#totalitemincoup=np.zeros((len(train)))\r\n#for j in range(len(train)):\r\n# totalitemincoup[j]= length1[np.where(x.coupon_id.unique()==train.coupon_id[j])[0][0]]\r\n\r\ntrain.info()\r\n \r\ny=pd.merge(test,coupon,how='inner',on='coupon_id')\r\ny.info()\r\ny.head()\r\nlength1y=np.zeros((len(y.coupon_id.unique())))\r\na=0\r\nfor i in y.coupon_id.unique():\r\n length1y[a]=len(y.item_id[y.coupon_id==i].unique())\r\n a+=1\r\n\r\nim_test=pd.concat([pd.DataFrame(y.coupon_id.unique()),pd.DataFrame(length1y)],axis=1)\r\nim_test.columns=['coupon_id','numitemcoup']\r\ntest_im=pd.merge(test,im_test,how='left',on='coupon_id')\r\n\r\nxx=pd.merge(x,custtran,how='inner',on=['customer_id','item_id'])\r\n \r\n#totalitemincoup_y=np.zeros((len(test)))\r\n#for j in range(len(test)):\r\n# totalitemincoup_y[j]= length1[np.where(y.coupon_id.unique()==test.coupon_id[j])[0][0]]\r\n\r\n \r\n''' intermediate save the cleaned data \r\ntest4.to_csv(r'C:/Users/parekhku/OneDrive - Merck Sharp & Dohme, Corp/Desktop/KP_Donotdelete/R/IMS/py/project/Amex/test4.csv',index=False)\r\ntrain4.to_csv(r'C:/Users/parekhku/OneDrive - Merck Sharp & Dohme, Corp/Desktop/KP_Donotdelete/R/IMS/py/project/Amex/train4.csv',index=False)\r\nif session ends then take above files\r\ntest4=pd.read_csv('C:/Users/parekhku/OneDrive - Merck Sharp & Dohme, Corp/Desktop/KP_Donotdelete/R/IMS/py/project/Amex/test4.csv')\r\ntrain4=pd.read_csv('C:/Users/parekhku/OneDrive - Merck Sharp & Dohme, Corp/Desktop/KP_Donotdelete/R/IMS/py/project/Amex/train4.csv')\r\n\r\n'''\r\ntrain4=pd.concat([train4,train_im['numitemcoup']],axis=1)\r\ntest4=pd.concat([test4,test_im['numitemcoup']],axis=1)\r\n\r\ntrain_y=train4.redemption_status\r\ndel train4['redemption_status']\r\n\r\ntrain4.info() \r\ntrain4.isna().sum()\r\ntest4.info() \r\ntest4.isna().sum()\r\n\r\ntrain4_full=train4[train4.age_range.isna()==False]\r\n\r\ntest4_full=test4[test4.age_range.isna()==False]\r\n\r\ntrain_y_full=train_y[train4.age_range.isna()==False]\r\nlen(train4_full)==len(train_y_full)\r\n\r\ntrain4_half=train4[train4.age_range.isna()==True]\r\ntest4_half=test4[test4.age_range.isna()==True]\r\n\r\ntrain_y_half=train_y[train4.age_range.isna()==True]\r\nlen(train4_half)==len(train_y_half)\r\n\r\ntest4_full=test4[test4.age_range.isna()==False]\r\nlen(test4_full)\r\n\r\ntest4_half=test4[test4.age_range.isna()==True]\r\nlen(test4_half)\r\n\r\n\r\n\r\ntrain4_half.isna().sum()\r\ntest4_half.isna().sum()\r\n\r\n\r\ntrain4_half_1=pd.concat([train4_half.iloc[:,4],train4_half.iloc[:,11:]],axis=1)\r\ntrain4_half_1.info()\r\ntest4_half_1=pd.concat([test4_half.iloc[:,4],test4_half.iloc[:,11:]],axis=1)\r\ntest4_half_1.info()\r\n\r\ntrain4_half_1_obj=train4_half_1.iloc[:,:-1]\r\ntrain4_half_1_obj=train4_half_1_obj.astype('object')\r\ntrain4_half_1_obj=pd.get_dummies(train4_half_1_obj)\r\ntest4_half_1_obj=test4_half_1.iloc[:,:-1].astype('object')\r\ntest4_half_1_obj=pd.get_dummies(test4_half_1_obj)\r\n\r\ntrain4_half_1_obj.info()#6 columns\r\ntest4_half_1_obj.info()#6 columns\r\ntrain4_half_1_obj_new=pd.concat([train4_half_1_obj,train4_half_1.iloc[:,-1]],axis=1)\r\ntest4_half_1_obj_new=pd.concat([test4_half_1_obj,test4_half_1.iloc[:,-1]],axis=1)\r\n\r\n\r\ntrain4_full_1=train4_full.iloc[:,4:]\r\ntrain4_full_1.info()\r\ntest4_full_1=test4_full.iloc[:,4:]\r\ntest4_full_1.info()\r\n\r\n\r\ntrain4_full_1_obj=train4_full_1.iloc[:,:-1].astype('object')\r\ntrain4_full_1_obj.info()\r\ntest4_full_1_obj=test4_full_1.iloc[:,:-1].astype('object')\r\ntest4_full_1.info()\r\n\r\ntrain4_full_1_obj=pd.get_dummies(train4_full_1)\r\ntrain4_full_1_obj.info()#38 columns\r\ntest4_full_1_obj=pd.get_dummies(test4_full_1)\r\ntrain4_full_1_obj.info()#38 columns\r\n\r\ntrain4_full_1_obj_new=pd.concat([train4_full_1_obj,train4_full_1.iloc[:,-1]],axis=1)\r\ntest4_full_1_obj_new=pd.concat([test4_full_1_obj,test4_full_1.iloc[:,-1]],axis=1)\r\n\r\n\r\n#pd.DataFrame(length1,columns=[\"eligibleitem\"])\r\n\r\n#NN Starts\r\nimport tensorflow as tf\r\nfrom tensorflow.python.framework import ops\r\n\r\n'''\r\nHere's what's happening: When you specify the operations needed for a computation, you are telling TensorFlow how \r\nto construct a computation graph. The computation graph can have some placeholders whose values you will specify \r\nonly later. Finally, when you run the session, you are telling TensorFlow to execute the computation graph.\r\n'''\r\n\r\ndef create_placeholders(n_x, n_y):\r\n\r\n X = tf.placeholder(tf.float32,shape=(n_x,None),name=\"Placeholder_1\")\r\n Y = tf.placeholder(tf.float32,shape=(n_y,None),name=\"Placeholder_2\")\r\n \r\n return X, Y\r\n\r\ndef initialize_parameters(szip):\r\n \r\n# tf.set_random_seed(1) # so that your \"random\" numbers match ours\r\n \r\n W1 = tf.get_variable(\"W1\", [90,szip], initializer = tf.contrib.layers.xavier_initializer(seed = 1))\r\n b1 = tf.get_variable(\"b1\", [90,1], initializer = tf.zeros_initializer())\r\n W2= tf.get_variable(\"W2\", [45,90], initializer = tf.contrib.layers.xavier_initializer(seed = 1))\r\n b2 = tf.get_variable(\"b2\", [45,1], initializer = tf.zeros_initializer())\r\n W3 = tf.get_variable(\"W3\", [1,45], initializer = tf.contrib.layers.xavier_initializer(seed = 1))\r\n b3 = tf.get_variable(\"b3\", [1,1], initializer = tf.zeros_initializer())\r\n ### END CODE HERE ###\r\n \r\n parameters = {\"W1\": W1,\r\n \"b1\": b1,\r\n \"W2\": W2,\r\n \"b2\": b2,\r\n \"W3\": W3,\r\n \"b3\": b3}\r\n \r\n return parameters\r\n \r\n\r\n\r\ndef forward_propagation(X, parameters):\r\n W1 = parameters['W1']\r\n b1 = parameters['b1']\r\n W2 = parameters['W2']\r\n b2 = parameters['b2']\r\n W3 = parameters['W3']\r\n b3 = parameters['b3']\r\n \r\n ### START CODE HERE ### (approx. 5 lines) # Numpy Equivalents:\r\n Z1 = tf.add(tf.matmul(W1,X),b1) # Z1 = np.dot(W1, X) + b1\r\n A1 = tf.nn.relu(Z1) # A1 = relu(Z1)\r\n Z2 = tf.add(tf.matmul(W2,A1),b2) # Z2 = np.dot(W2, a1) + b2\r\n A2 = tf.nn.relu(Z2) # A2 = relu(Z2)\r\n Z3 = tf.add(tf.matmul(W3,A2),b3) # Z3 = np.dot(W3,Z2) + b3\r\n ### END CODE HERE ###\r\n \r\n return Z3\r\n\r\n \r\n \r\n\r\ndef compute_cost(Z3, Y):\r\n logits = tf.transpose(Z3)\r\n labels = tf.transpose(Y)\r\n cost = tf.nn.sigmoid_cross_entropy_with_logits(logits=logits,labels=labels)\r\n\r\n return cost \r\n\r\ndef random_mini_batches(X, Y, mini_batch_size = 512, seed = 0):\r\n import math\r\n np.random.seed(seed) # To make your \"random\" minibatches the same as ours\r\n m = X.T.shape[1] # number of training examples\r\n mini_batches = []\r\n \r\n # Step 1: Shuffle (X, Y)\r\n permutation = list(np.random.permutation(m))\r\n shuffled_X = X.T[:, permutation]\r\n w=Y.reshape(1,m)\r\n shuffled_Y = w[:, permutation].reshape(1,m)\r\n \r\n # Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case.\r\n num_complete_minibatches = math.floor(m/mini_batch_size) # number of mini batches of size mini_batch_size in your partitionning\r\n for k in range(0, num_complete_minibatches):\r\n mini_batch_X = shuffled_X[:, k * mini_batch_size: (k+1)*mini_batch_size]\r\n mini_batch_Y = shuffled_Y[:, k * mini_batch_size: (k+1)*mini_batch_size]\r\n mini_batch = (mini_batch_X, mini_batch_Y)\r\n mini_batches.append(mini_batch)\r\n \r\n # Handling the end case (last mini-batch < mini_batch_size)\r\n if m % mini_batch_size != 0:\r\n mini_batch_X = shuffled_X[:, num_complete_minibatches * mini_batch_size:]\r\n mini_batch_Y = shuffled_Y[:, num_complete_minibatches * mini_batch_size:]\r\n mini_batch = (mini_batch_X, mini_batch_Y)\r\n mini_batches.append(mini_batch)\r\n return mini_batches\r\n \r\n \r\n \r\n#Build entire model now\r\ndef model(sizeip,X_train, Y_train, X_test, Y_test, learning_rate = 0.0005,\r\n num_epochs = 1500, minibatch_size = 512, print_cost = True):\r\n \"\"\"\r\n Implements a three-layer tensorflow neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SOFTMAX.\r\n \r\n Arguments:\r\n X_train -- training set, of shape (input size = 12288, number of training examples = 1080)\r\n Y_train -- test set, of shape (output size = 6, number of training examples = 1080)\r\n X_test -- training set, of shape (input size = 12288, number of training examples = 120)\r\n Y_test -- test set, of shape (output size = 6, number of test examples = 120)\r\n learning_rate -- learning rate of the optimization\r\n num_epochs -- number of epochs of the optimization loop\r\n minibatch_size -- size of a minibatch\r\n print_cost -- True to print the cost every 100 epochs\r\n \r\n Returns:\r\n parameters -- parameters learnt by the model. They can then be used to predict.\r\n \"\"\"\r\n \r\n ops.reset_default_graph() # to be able to rerun the model without overwriting tf variables\r\n tf.set_random_seed(1) # to keep consistent results\r\n seed = 3 # to keep consistent results\r\n (n_x, m) = X_train.T.shape # (n_x: input size, m : number of examples in the train set)\r\n n_y = Y_train.shape[0] # n_y : output size\r\n costs = [] # To keep track of the cost\r\n # Create Placeholders of shape (n_x, n_y)\r\n X, Y = create_placeholders(sizeip, 1)\r\n\r\n # Initialize parameters\r\n parameters = initialize_parameters(sizeip)\r\n \r\n # Forward propagation: Build the forward propagation in the tensorflow graph\r\n Z3 = forward_propagation(X, parameters)\r\n \r\n # Cost function: Add cost function to tensorflow graph\r\n cost = compute_cost(Z3, Y)\r\n \r\n # Backpropagation: Define the tensorflow optimizer. Use an AdamOptimizer.\r\n optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost)\r\n #optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)\r\n \r\n # Initialize all the variables\r\n init = tf.global_variables_initializer()\r\n\r\n # Start the session to compute the tensorflow graph\r\n with tf.Session() as sess:\r\n \r\n # Run the initialization\r\n sess.run(init)\r\n \r\n # Do the training loop\r\n for epoch in range(num_epochs):\r\n\r\n epoch_cost = 0. # Defines a cost related to an epoch\r\n num_minibatches = int(m / minibatch_size) # number of minibatches of size minibatch_size in the train set\r\n seed = seed + 1\r\n minibatches = random_mini_batches(X_train, Y_train, minibatch_size, seed)\r\n\r\n for minibatch in minibatches:\r\n\r\n # Select a minibatch\r\n (minibatch_X, minibatch_Y) = minibatch\r\n \r\n # IMPORTANT: The line that runs the graph on a minibatch.\r\n # Run the session to execute the \"optimizer\" and the \"cost\", the feedict should contain a minibatch for (X,Y).\r\n _ , minibatch_cost = sess.run([optimizer, cost], feed_dict={X: minibatch_X, Y: minibatch_Y})\r\n \r\n epoch_cost += np.sum(minibatch_cost / num_minibatches)\r\n\r\n # Print the cost every epoch\r\n if print_cost == True and epoch % 100 == 0:\r\n print (\"Cost after epoch %i: %f\" % (epoch, np.sum(epoch_cost)))\r\n if print_cost == True and epoch % 5 == 0:\r\n costs.append(epoch_cost)\r\n \r\n # plot the cost\r\n plt.plot(np.squeeze(costs))\r\n plt.ylabel('cost')\r\n plt.xlabel('iterations (per tens)')\r\n plt.title(\"Learning rate =\" + str(learning_rate))\r\n plt.show()\r\n\r\n parameters = sess.run(parameters)\r\n print (\"Parameters have been trained!\")\r\n \r\n #predicted = tf.nn.sigmoid(Z3)\r\n #correct_pred = tf.equal(tf.round(predicted), Y)\r\n #accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\r\n #print('Test Accuracy:', sess.run([accuracy, tf.round(predicted)], feed_dict={X: X_test, Y: Y_test}))\r\n\r\n # Calculate the correct predictions\r\n #correct_prediction = tf.equal(tf.argmax(Z3), tf.argmax(Y))\r\n\r\n # Calculate accuracy on the test set\r\n #accuracy = tf.equal(tf.cast(correct_prediction, \"float\"))\r\n\r\n #print (\"Train Accuracy:\", accuracy.eval({X: X_train, Y: Y_train}))\r\n #print (\"Test Accuracy:\", accuracy.eval({X: X_test, Y: Y_test}))\r\n \r\n return parameters \r\n\r\n\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nX_train, X_test, y_train, y_test = train_test_split(train4_full_1_obj_new,train_y_full, test_size=0.0001)\r\n\r\nparameters = model(len(train4_full_1_obj_new.columns),np.array(X_train), np.array(y_train), np.array(X_test), np.array(y_test))\r\n\r\ndef sigmoid(x):\r\n return(1/(1+np.exp(-x)))\r\n\r\nz1=np.matmul(parameters[\"W1\"],np.array(X_train.T))+parameters[\"b1\"]\r\na1=np.maximum(z1,0)\r\nz2=np.matmul(parameters[\"W2\"],a1)+parameters[\"b2\"]\r\na2=np.maximum(z2,0)\r\nz3=np.matmul(parameters[\"W3\"],a2)+parameters[\"b3\"]\r\nans=sigmoid(z3) \r\n\r\nlen1=ans.shape[1]\r\n\r\nresultant=np.zeros(len1)\r\nfor i in range(len1):\r\n if ans[:,i]>0.02:\r\n resultant[i]=1\r\n else:\r\n resultant[i]=0\r\n\r\nnp.unique(resultant, return_counts=True)\r\n\r\nnp.unique(np.array(y_test), return_counts=True)\r\n \r\nfrom sklearn.metrics import confusion_matrix\r\n#from sklearn.metrics import classification_report, confusion_matrix\r\nprint(confusion_matrix(y_train, resultant))\r\n#from sklearn.metrics import auc\r\n#y = np.array([1, 1, 2, 2])\r\n#pred = np.array([0.1, 0.4, 0.35, 0.8])\r\n#fpr, tpr, thresholds = metrics.roc_curve(y, pred, pos_label=2)\r\n#metrics.auc(fpr, tpr)\r\n#predict for test full\r\nz1=np.matmul(parameters[\"W1\"],np.array(test4_full_1_obj_new.T))+parameters[\"b1\"]\r\na1=np.maximum(z1,0)\r\nz2=np.matmul(parameters[\"W2\"],a1)+parameters[\"b2\"]\r\na2=np.maximum(z2,0)\r\nz3=np.matmul(parameters[\"W3\"],a2)+parameters[\"b3\"]\r\nans_full=sigmoid(z3) \r\n\r\nlen11=ans_full.shape[1]\r\nresultant_test_full=np.zeros(len11)\r\nfor i in range(len11):\r\n if ans_full[:,i]>0.002: #Play\r\n resultant_test_full[i]=1\r\n else:\r\n resultant_test_full[i]=0\r\n\r\n\r\ndf2=pd.concat([test4_full.id,pd.DataFrame(resultant_test_full,columns=['redemption_status'],index=test4_full.index)],axis=1)\r\n\r\n\r\n#NN for half\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(train4_half_1_obj_new,train_y_half, test_size=0.0001)\r\n\r\nparameters1 = model(len(train4_half_1_obj_new.columns),np.array(X_train), np.array(y_train), np.array(X_test), np.array(y_test))\r\ndef sigmoid(x):\r\n return(1/(1+np.exp(-x)))\r\n\r\n\r\n\r\nz1=np.matmul(parameters1[\"W1\"],np.array(X_train.T))+parameters1[\"b1\"]\r\na1=np.maximum(z1,0)\r\nz2=np.matmul(parameters1[\"W2\"],a1)+parameters1[\"b2\"]\r\na2=np.maximum(z2,0)\r\nz3=np.matmul(parameters1[\"W3\"],a2)+parameters1[\"b3\"]\r\nans=sigmoid(z3) \r\n\r\nlen1=ans.shape[1]\r\n\r\nresultant1=np.zeros(len1)\r\nfor i in range(len1):\r\n if ans[:,i]>0.01:\r\n resultant1[i]=1\r\n else:\r\n resultant1[i]=0\r\n\r\nfrom sklearn.metrics import confusion_matrix\r\n#from sklearn.metrics import classification_report, confusion_matrix\r\nprint(confusion_matrix(y_train, resultant1))\r\n\r\n#predict for half\r\nz1=np.matmul(parameters1[\"W1\"],np.array(test4_half_1_obj_new.T))+parameters1[\"b1\"]\r\na1=np.maximum(z1,0)\r\nz2=np.matmul(parameters1[\"W2\"],a1)+parameters1[\"b2\"]\r\na2=np.maximum(z2,0)\r\nz3=np.matmul(parameters1[\"W3\"],a2)+parameters1[\"b3\"]\r\nans_test_half=sigmoid(z3) \r\n\r\nlen1=ans_test_half.shape[1]\r\nresultant_test_half=np.zeros(len1)\r\nfor i in range(len1):\r\n if ans[:,i]>0.001: #Play\r\n resultant_test_half[i]=1\r\n else:\r\n resultant_test_half[i]=0\r\n \r\n#pd.DataFrame(resultant_test_half,columns=['redemption_status'],index=False)\r\ndf1=pd.concat([test4_half.id,pd.DataFrame(resultant_test_half,columns=['redemption_status'],index=test4_half.index)],axis=1)\r\n\r\nfinal_pred=pd.concat([df1,df2],axis=0)\r\nfinal_pred_sorted=final_pred.sort_index()\r\nfinal_pred_sorted.to_csv(r'C:/Users/parekhku/OneDrive - Merck Sharp & Dohme, Corp/Desktop/KP_Donotdelete/R/IMS/py/project/Amex/final_pred.csv',index=False)\r\n\r\n\r\n#Random Forest : CART\r\ntrain4_full_1_obj.info()\r\ntrain4_half_1_obj.info()\r\ntrain_y_full\r\ntrain_y_half\r\n\r\nfrom sklearn.ensemble import RandomForestClassifier\r\n\r\n# build a classifier\r\nrf = RandomForestClassifier(n_estimators=1500,class_weight={0:.15, 1:0.99})\r\n\r\n#Train the model using the training sets\r\nrf.fit(train4_full_1_obj_new, train_y_full)\r\n\r\n#Predict the response for test dataset\r\ny_pred_full = rf.predict(train4_full_1_obj_new)\r\nfrom sklearn.metrics import confusion_matrix\r\nprint(confusion_matrix(y_pred_full, train_y_full))\r\n\r\nfinalpred_full=rf.predict(test4_full_1_obj_new)\r\n\r\nrf1 = RandomForestClassifier(n_estimators=1500,class_weight={0:.001, 1:0.99})\r\n#Train the model using the training sets\r\nrf1.fit(train4_half_1_obj_new, train_y_half)\r\n\r\n#Predict the response for test dataset\r\ny_pred_half = rf1.predict(train4_half_1_obj_new)\r\n\r\nfrom sklearn.metrics import confusion_matrix\r\nprint(confusion_matrix(y_pred_half, train_y_half))\r\n\r\n\r\nfinalpred_half=rf1.predict(test4_half_1_obj_new)\r\nfinalpred_half=pd.concat([test4_half.id,pd.DataFrame(finalpred_half,columns=['redemption_status'],index=test4_half.index)],axis=1)\r\nfinalpred_full=pd.concat([test4_full.id,pd.DataFrame(finalpred_full,columns=['redemption_status'],index=test4_full.index)],axis=1)\r\n\r\nfinal_pred=pd.concat([finalpred_half,finalpred_full],axis=0)\r\nfinal_pred_sorted=final_pred.sort_index()\r\nfinal_pred_sorted.to_csv(r'C:/Users/parekhku/OneDrive - Merck Sharp & Dohme, Corp/Desktop/KP_Donotdelete/R/IMS/py/project/Amex/final_pred.csv',index=False)\r\n#\r\n#x=pd.merge(train,coupon,how='inner',on='coupon_id')\r\n#x.info()\r\n#x.head()\r\n#length1=np.zeros((len(x.coupon_id.unique())))\r\n#a=0\r\n#for i in x.coupon_id.unique():\r\n# length1[a]=len(x.item_id[x.coupon_id==i].unique())\r\n# a+=1\r\n# \r\n# \r\n#y=pd.merge(test,coupon,how='inner',on='coupon_id')\r\n#y.info()\r\n#y.head()\r\n#length1y=np.zeros((len(y.coupon_id.unique())))\r\n#a=0\r\n#for i in y.coupon_id.unique():\r\n# length1y[a]=len(y.item_id[y.coupon_id==i].unique())\r\n# a+=1","sub_path":"AMEX_Analytics_Vidhya/Amex.py","file_name":"Amex.py","file_ext":"py","file_size_in_byte":23858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"348676431","text":"from django.core.files.uploadedfile import SimpleUploadedFile\nfrom django.test import TestCase, RequestFactory\nfrom django.urls import reverse\n\nfrom appointment.models.prescription import Prescription\nfrom appointment.tests.test_models import create_dummy_place, create_dummy_hospital, create_dummy_disease\nfrom appointment.views import home\n\n\nclass HomeTest(TestCase):\n def test_get_request(self):\n factory = RequestFactory()\n request = factory.get('')\n response = home(request)\n self.assertEqual(response.status_code, 200)\n\n def test_place_prepopulated(self):\n p = create_dummy_place()\n\n factory = RequestFactory()\n data = {'place': p.name,\n 'disease_or_hospital': 'wrong'}\n request = factory.post('', data)\n\n response = home(request)\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, p.name)\n\n def test_d_o_h_prepopulated(self):\n h = create_dummy_hospital()\n\n factory = RequestFactory()\n data = {'place': 'wrong',\n 'disease_or_hospital': h.name}\n request = factory.post('', data)\n\n response = home(request)\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, h.name)\n\n def test_redirect(self):\n p = create_dummy_place()\n h = create_dummy_hospital()\n d = create_dummy_disease()\n factory = RequestFactory()\n data = {'disease_or_hospital': h.name,\n 'place': p.name,\n 'isHospital': 'True'}\n request = factory.post('', data)\n\n response = home(request)\n self.assertEqual(response.status_code, 302)\n\n data = {'disease_or_hospital': d.name,\n 'place': p.name,\n 'isHospital': 'False'}\n request = factory.post('', data)\n\n response = home(request)\n self.assertEqual(response.status_code, 302)\n\n\nclass AjaxPlaceSearchTest(TestCase):\n def test_place_search_non_ajax_request(self):\n response = self.client.get(reverse('appointment:place_search'))\n self.assertEqual(response.status_code, 400)\n\n def test_place_search(self):\n p = create_dummy_place()\n response = self.client.get(reverse('appointment:place_search'),\n {'term': 'd', },\n HTTP_X_REQUESTED_WITH='XMLHttpRequest'\n )\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, p.name)\n\n\nclass AjaxDOHSearchTest(TestCase):\n def test_doh_search_non_ajax_request(self):\n response = self.client.get(reverse('appointment:disease_or_hospital_search'))\n self.assertEqual(response.status_code, 400)\n\n def test_place_search(self):\n h = create_dummy_hospital()\n response = self.client.get(reverse('appointment:disease_or_hospital_search'),\n {'term': 'd', },\n HTTP_X_REQUESTED_WITH='XMLHttpRequest'\n )\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, h.name)\n\n\nclass CreateTest(TestCase):\n def test_file_upload_and_report_creation(self):\n f1 = SimpleUploadedFile(\"demo.jpg\", b\"file_content\", )\n f2 = SimpleUploadedFile(\"demo2.jpg\", b\"file_content\", )\n\n p = create_dummy_place()\n h = create_dummy_hospital()\n\n response = self.client.post(reverse('appointment:create',\n args=(p.id, h.id, 1)),\n {'full_name': 'dummy dummy',\n 'email': 'dummy@example.com',\n 'gender': 'male',\n 'age': 1,\n 'phone': '111',\n 'details': 'details',\n 'preferred_doctor_or_hospital': 'dummy',\n 'file': [f1, f2]})\n\n self.assertEqual(response.status_code, 302)\n\n\n self.assertEqual(Prescription.objects.all().count(), 2)\n Prescription.objects.all().delete()\n","sub_path":"appointment/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":4255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"620832054","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 24 02:01:19 2020\n\n@author: mszta\n\"\"\"\n\nimport numpy as np\nimport numpy.matlib\nimport matplotlib.pyplot as plt\nimport math\nimport time\n\nt = time.time()\n\nH = 50\n\ntheta = .679\nbeta = .988\ndelta = .013\nkappa = 5.24\nnu = 2.0\n\nk_lo = 0.01 #lower bound for capital\nk_up = 50 #upper bound for capital\nS = 300 # number or discrete states between (and including) k_lo and k_up\nconv = 1e-6 # convergence criterion %sqrt(eps)\n\n# Steady state\nk_ss = ((1/beta-1+delta)/(1-theta))**(-1/theta)\nc_ss = k_ss**(1-theta)-delta*k_ss\n\n# Grid for states (capital)\nks = np.linspace(k_lo, k_up, num = S)\ngs = np.arange(0,S,1).tolist()\n\n# Period utility\nreward = np.matlib.repmat(-float(10**100),S,S)\nrewardH = np.zeros(S)\nvalue = np.zeros(S)\ncont = np.zeros(S)\ncons = np.zeros(S)\nkp = np.zeros(S)\nprogress = 1 \nit = 1\n\nfor j in gs:\n for i in gs:\n cij = (1-delta)*ks[j]+ks[j]**(1-theta)-ks[i]\n if cij >= 0: #consumption must be non-negative\n reward[i,j] = math.log(cij)-kappa/(1+1/nu)\n\nwhile progress > conv: #until value function sufficiently changes\n valueold = value\n vold = np.transpose(np.matlib.repmat(valueold, S, 1))\n m = reward+beta*vold\n value = list(np.max(np.array(m), axis=0))\n \n for k in gs:\n cont[k] = np.argmax(m[:,k])\n rewardH[k] = reward[np.int(cont[k])][k]\n\n for u in np.linspace(0,H,1):\n for y in gs:\n value[y] = rewardH[y]+beta*value[np.int(cont[y])]\n \n progress = max(abs(np.subtract(value,valueold))) \n it = it + 1\n \nfor n in gs:\n idx = np.int(cont[n]) \n kp[n] = ks[idx]\n cons[n] = ks[n]**(1-theta)-kp[n]+(1-delta)*ks[n]\n\nelapsed = time.time() - t\nprint(\"Ex1f runtime:\", elapsed)\nprint(\"Ex1f no. iterations:\", it)\n\nplt.plot(ks,value)\nplt.xlabel('Capital')\nplt.ylabel('Value')\nplt.title('Value function plot 1f')\nplt.savefig('Value function plot 1f.png')\nplt.show()\n\nplt.plot(ks,np.ones(S))\nplt.xlabel('Capital')\nplt.ylabel('Labour')\nplt.title('Labour policy function plot 1f')\nplt.savefig('Labour policy function plot 1f.png')\nplt.show()\n\nplt.plot(ks,cons)\nplt.xlabel('Capital')\nplt.ylabel('Consumption')\nplt.title('Consumption policy function plot 1f')\nplt.savefig('Consumption policy function plot 1f.png')\nplt.show()\n\nplt.plot(ks,kp)\nplt.xlabel('Capital')\nplt.ylabel('Capital policy function')\nplt.title('Capital policy function plot 1f')\nplt.savefig('Capital policy function plot 1f.png')\nplt.show()\n\n\n","sub_path":"PS3/Codes/Exercise 1/Ex1g.py","file_name":"Ex1g.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"205542246","text":"\n\"\"\"\n\t... kemal-i intizam ile bu kadar hassas duyguları ve hissiyatları ve gayet muntazam bu manevi latifeleri ve\nbatınî hasseleri bu cismimde derc etmekle beraber, gayet sanatlı bu cihazatı ve cevarihi ve hayat-ı insaniyece gayet\nlüzumlu ve mükemmel bu kadar aletleri bu vücudumda kemal-i intizamla yaratmış.\n\"\"\"\nimport time\nimport gor_class\t\t\t# BUNUN İÇİNDE BAZI MODÜLLER IMPORT EDİLİYO. O YÜZDEN INIT MANASI FARZ-I AYN\nimport numpy as np\nfrom imutils.video import VideoStream\nimport RPi.GPIO as GPIO\nGPIO.setwarnings(False) \n#~ from matplotlib import pyplot as plt\n#~ import imutils\nimport argparse\nimport cv2\t# bunu gor_class'ta zaten import ettiğimizden burada tekrar import etmek süreyi uzatır mı diye düşünmüştüm\n# ama elhamdülillah, tecrübe ettiğim gibi uzatmıyo, çünkü zaten imported\n# import pyximport; pyximport.install() # it works only on pure Python modules. imiş\n#~ import pickle\nresult = 40\n#~ with open('result.obj','wb') as dist:\n\t#~ pickle.dump(result,dist)\nimport control\nwith open('balloon_config_file_webcam.cnf') as dosya:\n\tveri_web = dosya.readlines()\nknown_pix_oto_web = int(float(veri_web[6][14:-1]))\nwith open('balloon_config_file_picam.cnf') as dosya:\n\tveri_pi = dosya.readlines()\nknown_pix_oto_pi = int(float(veri_pi[6][14:-1]))\n\n# construct the argument parse and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-g\", \"--gui\", type=int, default=1,\n\thelp=\"whether or not gui is used. If you don't want to use gui, enter -1\")\nap.add_argument(\"-i\", \"--image\", type=int, default=1,\n\thelp=\"whether or not image is used. If you don't want to use image, enter -1\")\nap.add_argument(\"-b\", \"--both\", type=int, default=1,\n\thelp=\"whether or not both image and gui are used. If you don't want to use any of them, enter -1\")\nargs = vars(ap.parse_args())\n\n#~ GPIO.setup(channel, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n #~ bir alt satır normalde yorum satırı değildiie\nGPIO.setmode(GPIO.BOARD)\n\nGPIO_sensor_1_2 = 24 # front-right sensor\nGPIO_sensor_3_4 = 21 # front-left sensor\n\nGPIO.setup(GPIO_sensor_1_2, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\nGPIO.setup(GPIO_sensor_3_4, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n\n# buraya kadar 2.8 saniye sürdü\n \n# initialize the video stream and allow the camera sensor to warmup\n#~ picam = VideoStream(usePiCamera=args[\"picamera\"] < 0).start()\n\n#~ https://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html\n#~ grab ve retrieve denenebilir coşkun daha hızlı demiş heralde multicamera varsa\n\n#~ picam = VideoStream(usePiCamera=True,resolution=(480, 368)).start() # aç # dikkat PiCameraResolutionRounded diyebilir\npicam = VideoStream(src=0).start() # (1280, 960) yazınca (640, 480) verdi yani yaklaşık 3 mp\nwebcam = VideoStream(src=1).start() # aç # resolution default olarak (320,240) (horiz,vert) default 160,120\n# allow the camera to warmup\ntime.sleep(0.1)\n#~ picam = cv2.VideoCapture(1)\n#~ webcam = cv2.VideoCapture(0)\n\n#~ time.sleep(2.0) # bu kritik mi acaba bilmiyorum\n\t\n###################################################\n\t\n#20.04 yenileme \n#GPIO port allocation for sensors (can be changed)\n# interrupt 4 sensor için oldu\n#a direction variable can be allocated\n# to compare the real alarm.(gittiğimiz yönün aksinde sinyaln gelirse onu kale almayacaz\n# çünkü motor u aniden çok zorlarız)\n#bu degişkeni main de tutucağız.\n\n\n#~ motorOutputPin2 = 38 # 32 33 35 (board) 12 13 19 (bcm)\n#~ motorOutputPin1 = 29 \n\n#~ pwm_yaz_sol = GPIO.PWM(motorOutputPin1, 500) # PWM has timing resolution of 1 us according to:\n#~ pwm_yaz_sag = GPIO.PWM(motorOutputPin2, 500) # https://www.electronicwings.com/raspberry-pi/raspberry-pi-pwm-generation-using-python-and-c\n# şimdi software pwm'i kullanıyoruz.\n# bize eğer 1us (1000 Hz)'den daha yüksek bir resolution lazımsa hardware PWM'i kullanmak lazım. Onu araştırmadım.\n\n#~ pwm_yaz_sol.start(pwmleft)\n#~ pwm_yaz_sag.start(pwmright)\n\n\n#~ pwm_yaz_sol.ChangeDutyCycle(pwmleft), pwm_yaz_sag.ChangeDutyCycle(pwmright)\nflag = 0\n\ndef sensor3_4(habib):\n\tglobal flag\n\tflag = 1\t\n\tprint(flag)\n\n\tif(control.direction==1):\n\t\t\n\t\tGPIO.output(control.in1, GPIO.HIGH)\n\t\tGPIO.output(control.in2, GPIO.LOW)\n\t\tGPIO.output(control.in3, GPIO.HIGH)\n\t\tGPIO.output(control.in4, GPIO.LOW)\t\n\t\t\t\n\t\tpwmright_interrupt = 0\n\t\tpwmleft_interrupt = 0\n\t\tcontrol.pwm_yaz_sol.ChangeDutyCycle(pwmleft_interrupt)\n\t\tcontrol.pwm_yaz_sag.ChangeDutyCycle(pwmright_interrupt)\n\n\t\tprint (\" pwmleft \" , pwmleft_interrupt)\n\t\tprint (\" pwmright \" , pwmright_interrupt)\t\n\t\t#~ time.sleep(5)\t\n\t\t\t\n\t\twhile (GPIO.input(GPIO_sensor_3_4) == GPIO.HIGH):\n\t\t\ttime.sleep(0.1)\n\t\tflag = 0\t\n\tprint('SONRA: ',flag)\n\t\t\t\ndef sensor1_2(habib):\n\tglobal flag\n\tflag = 1\t\n\tprint(flag)\n\tif(control.direction==2):\n\t\t\n\t\tGPIO.output(control.in1, GPIO.HIGH)\n\t\tGPIO.output(control.in2, GPIO.LOW)\n\t\tGPIO.output(control.in3, GPIO.LOW)\n\t\tGPIO.output(control.in4, GPIO.HIGH)\t\n\t\t\t\n\t\tpwmright_interrupt = 0\n\t\tpwmleft_interrupt = 0\n\t\tcontrol.pwm_yaz_sol.ChangeDutyCycle(pwmleft_interrupt)\n\t\tcontrol.pwm_yaz_sag.ChangeDutyCycle(pwmright_interrupt)\n\n\t\tprint (\" pwmleft \" , pwmleft_interrupt)\n\t\tprint (\" pwmright \" , pwmright_interrupt)\t\n\t\t#~ time.sleep(5)\n\t\t\t\n\t\twhile (GPIO.input(GPIO_sensor_1_2) == GPIO.HIGH):\n\t\t\ttime.sleep(0.2)\n\t\tflag = 0\t\n\tprint('SONRA: ',flag)\n\nGPIO.add_event_detect(GPIO_sensor_1_2, GPIO.RISING, callback=sensor1_2)\nGPIO.add_event_detect(GPIO_sensor_3_4, GPIO.RISING, callback=sensor3_4)\n\nif args[\"gui\"] == 1 and args[\"both\"] == 1:\n\tfrom tkinter import StringVar,Label,Tk\n\tROOT = Tk()\n\tdeg_aci \t\t\t\t= StringVar()\n\tdeg_distance_to_center \t= StringVar()\n\tdeg_actual_distance \t= StringVar()\n\tdeg_volt_sag \t\t\t= StringVar()\n\tdeg_volt_sol \t\t\t= StringVar()\n\tdeg_sure \t\t\t\t= StringVar()\n\tLABEL_aci \t\t\t\t = Label(ROOT, textvariable=deg_aci \t\t\t\t,font=(\"Times\", 25,'bold'), anchor=\"w\",width=30)\n\tLABEL_distance_to_center = Label(ROOT, textvariable=deg_distance_to_center \t,font=(\"Times\", 25,'bold'), anchor=\"w\",width=30)\n\tLABEL_actual_distance \t = Label(ROOT, textvariable=deg_actual_distance \t,font=(\"Times\", 25,'bold'), anchor=\"w\",width=30)\n\tLABEL_volt_sag \t\t\t = Label(ROOT, textvariable=deg_volt_sag \t\t\t,font=(\"Times\", 25,'bold'), anchor=\"w\",width=30)\n\tLABEL_volt_sol \t\t\t = Label(ROOT, textvariable=deg_volt_sol \t\t\t,font=(\"Times\", 25,'bold'), anchor=\"w\",width=30)\n\tLABEL_sure \t\t\t \t = Label(ROOT, textvariable=deg_sure \t\t\t\t,font=(\"Times\", 25,'bold'), anchor=\"w\",width=30)\ndef webcam_func(webcam):\n\t#~ ret,webcam_resim = cap.read() # kapa\n\twebcam_resim = webcam.read() # aç\n\tglobal webcam_picture\n\twebcam_picture = gor_class.Goruntu(webcam_resim,'balloon_config_file_webcam.cnf',known_pix=240,known_dis=60,wrt_ground=55) # 1 ms falan\n\tglobal webcam_mask\n\twebcam_mask = webcam_picture.build_mask()\n\t#~ webcam_mask = imutils.rotate(webcam_mask,angle=180)\n\tkimse_yok_mu_webcam = webcam_picture.find_center(webcam_mask)\n\twebcam_picture.find_small_y_axis(fov_horizontal=49)\t\t\n\twebcam_picture.find_vertical_angle(fov_vertical=37)\t\n\twebcam_picture.find_distance_to_center()\n\treturn kimse_yok_mu_webcam\ndef picam_func(picam):\n\t#~ picam_resim = im_frame.array # kapa\n\tpicam_resim = picam.read() # aç\n\tglobal picam_picture\n\tpicam_picture = gor_class.Goruntu(picam_resim,'balloon_config_file_picam.cnf',known_pix=240,known_dis=60,wrt_ground=55) # 1 ms falan\n\tglobal picam_mask\n\tpicam_mask = picam_picture.build_mask()\n\tkimse_yok_mu_picam = picam_picture.find_center(picam_mask)\n\tpicam_picture.find_small_y_axis(fov_horizontal=49) \t\n\tpicam_picture.find_vertical_angle(fov_vertical=37)\t\n\tpicam_picture.find_distance_to_center()\n\treturn kimse_yok_mu_picam\nif args[\"gui\"] == 1 and args[\"both\"] == 1:\n\tLABEL_aci.pack()\t\t\t\t\n\tLABEL_distance_to_center.pack()\n\tLABEL_actual_distance.pack()\n\tLABEL_volt_sag.pack()\n\tLABEL_volt_sol.pack()\n\tLABEL_sure.pack()\n#~ fpss_toplam = 0\n#~ countt = 0\nper = 50\nkimse_yok_mu = 1\nelapsedTime = 0.1 \t# it is required to define an initial value\ncam_control = 0\nsayy = 0\nartik_yok = 0\nwhile True: # aç\n\ttry:\n#~ for im_frame in cap.capture_continuous(rawCapture, format=\"bgr\", use_video_port=True): # kapa\n\t\tif flag == 1:\n\t\t\t#~ GPIO.output(control.in1, GPIO.LOW)\n\t\t\t#~ GPIO.output(control.in2, GPIO.LOW)\n\t\t\t#~ GPIO.output(control.in3, GPIO.LOW)\n\t\t\t#~ GPIO.output(control.in4, GPIO.LOW)\t\n\t\t\tpwmright_interrupt = 0\n\t\t\tpwmleft_interrupt = 0\n\t\t\tcontrol.pwm_yaz_sol.ChangeDutyCycle(pwmleft_interrupt)\n\t\t\tcontrol.pwm_yaz_sag.ChangeDutyCycle(pwmright_interrupt)\n\t\telse:\n\n\t\t\tac_time = time.time() # actual time read\n\t\t\tif args[\"gui\"] == 1 and args[\"both\"] == 1:\n\t\t\t\tROOT.update()\n\t\t\t#~ resim = imutils.resize(resim, width=400) # bunu uncomment etmek istiyosan imutils'i import et\n\t\t\t#~ resim = cv2.flip(resim,1) \n\t\t\t#~ cv2.destroywindow('windowun_ismi')\n\t\t\t# 0 yapinca dikey, 1 yapınca yatay flip ediyo. Ama şuanki haliyle zaten hiç gerek yok. Bi de imutils'in kendi flip'i daha efficient olsa gerek\n\t\t\t#~ kimse_yok_mu = 0\n\t\t\tif cv2.waitKey(5) & 0xFF == ord('q'): # q ile çık programdan\n\t\t\t\tbreak\n\t\t\tif cam_control == 1 or picam_func(picam) == 1: # bir önceki frame'de webcam görmüşse veya şimdi picam görmediyse\n\t\t\t\tif webcam_func(webcam) == 1:\n\t\t\t\t\tkimse_yok_mu = 1\n\t\t\t\t\tcam_control = 0\n\t\t\t\t\tif kimse_yok_mu == 1:\n\t\t\t\t\t\tprint('yok diyo!! ',sayy)\n\t\t\t\t\tsayy += 1\n\t\t\t\t\tif artik_yok == 1:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tcontrol.dongu(yok_mu = 1)\n\t\t\t\t\tartik_yok = 1\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\tkimse_yok_mu = 0\n\t\t\t\t\tpicture = webcam_picture\n\t\t\t\t\tmask = webcam_mask\n\t\t\t\t\tcam_control = 1\n\t\t\t\t\ttersmi_duzmu = 0\n\t\t\t\t\tartik_yok = 0\n\t\t\t\t\t#~ print(10*'\\n')\n\t\t\telse:\n\t\t\t\tkimse_yok_mu = 0\n\t\t\t\tpicture = picam_picture\n\t\t\t\tmask = picam_mask\n\t\t\t\tcam_control = 0\n\t\t\t\ttersmi_duzmu = 1\n\t\t\t\tartik_yok = 0\n\t\t\t\n\t\t\tactual_distance = picture.projection_of_distance_to_actual_place_of_balloon\n\t\t\taci = picture.angle # in radians\n\t\t\tif tersmi_duzmu == 1:\n\t\t\t\taci = -aci\n\t\t\tdistance_to_center = picture.projection_of_distance_to_center\n\t\t\tgoster_angle = aci*180/3.14\n\t\t\t\n\t\t\tpwmleft,pwmright = control.dongu(aci, actual_distance,kimse_yok_mu,tersmi_duzmu)\n\t\t\t# dongu() q returnlu olması ve burdan değerleri \n\t\t\t# almamızın tek sebebi sonucu ekranda görme isteği. yani kaldırılabilir\n\t\t\tif args[\"both\"] == 1 and args[\"gui\"] == 1:\n\t\t\t\tdeg_aci.set('angle:\\t\\t'+str(round(goster_angle,2))+' degrees')\n\t\t\t\tdeg_distance_to_center.set('distance_to_center:'+str(round(distance_to_center,2))+' cm')\n\t\t\t\tdeg_actual_distance.set('actual_distance:\\t'+str(round(actual_distance,2))+' cm')\n\t\t\t\tdeg_volt_sag.set('PWM_right:\\t'+str(round(pwmright,2))+'%')\n\t\t\t\tdeg_volt_sol.set('PWM_left:\\t'+str(round(pwmleft,2))+'%')\n\t\t\t\tdeg_sure.set('# Frames/second:\\t'+str(round(1/elapsedTime,2))+' fps')\n\t\t\tif args[\"both\"] == 1 and args[\"image\"] == 1:\n\t\t\t\tmask75 = picture.rescale_frame(mask, percent=per)\n\t\t\t\t#~ th375 = picture.rescale_frame(picture.th3, percent=per)\n\t\t\t\tframe75 = picture.rescale_frame(picture.resim, percent=per)\n\t\t\t\tmask75_3_channel = cv2.cvtColor(mask75, cv2.COLOR_GRAY2BGR) \n\t\t\t\t# COLOR_GRAY2BGR ile gray'i renkli yapmıyo, 3 channel'lı yapıyo sadece, concatanate yapabilmek için\n\t\t\t\t# print('shape: ',mask75.shape,'and',frame75.shape)\n\t\t\t\tikisi= np.concatenate((mask75_3_channel,frame75), axis=0)\n\t\t\t\t#~ plt.hist(picture.resim.ravel(),256)\n\t\t\t\t#~ plt.title('histogram')\n\t\t\t\tcv2.imshow('Out', ikisi)\n\t\t\telapsedTime = time.time() - ac_time\n\texcept KeyboardInterrupt:\n\t\tcv2.destroyAllWindows()\n\t\twebcam.stop()\n\t\tpicam.stop()\t\n\t\tGPIO.cleanup()\ncv2.destroyAllWindows()\nwebcam.stop() # aç\n#~ webcam.release() # kapa\n#~ picam.release() # kapa\npicam.stop()\t\nGPIO.cleanup()\n#~ raspistill -o image.jpg # picamera ile terminalden foto çekmek için\n#~ fswebcam -d /dev/video0 -r 1920x1080 -S 0 -F 1 image10.jpg\t# webcam ile terminalden foto çekmek için\n#~ /opt/vc/bin/vcgencmd measure_temp\t# rpi'nin core sıcaklığı\n#~ nano ~/.bashrc yazarak dosyanın sonuna bi satır ekledim. default cd değişti\n\n\n\n\n#yapılacak=distance'da geçmiş datayı tutup şimdiki ile kıyaslayıp çok farklıysa ignore\n","sub_path":"video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":11917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"56158321","text":"import random\nimport itertools\nimport numpy as np\nfrom scipy.stats import entropy\nimport probability_distributions\nimport nudge_non_causal as nudge\nimport evolutionary_algorithms as ea\n\nTEST = True\n\ndef get_cond_output_with_max_distance(\n input_shape, number_of_output_states, goal_distance, \n evolutionary_parameters, input_dists, \n number_of_input_distributions=None):\n \"\"\" \n Create a conditional output distribution which gives as different \n as possible marginal for the different input distributions\n\n Parameters:\n ----------\n input_shape: a list, the number of states of the inut variables\n number_of_states_output: integer\n input_distributions: a list of nd-arrays or None\n Every array representing a probability distribution\n number_of_input_distributions: integer\n The number of input distributions to generate using a Dirichlet\n distribution with all parameters equal to 1.\n evolutionary_parameters: dict with the keys\n number_of_generations: integer \n population_size: integer\n number_of_children: integer, \n if generational larger than or equal to population size \n generational: Boolean, whether to replace the old generation \n mutation_size: positive float\n change_mutation_size: positive float\n parent_selection_mode: \"rank_exponential\" or None (for random selection)\n \n \"\"\"\n if input_dists is None:\n number_of_input_states = reduce(lambda x,y: x*y, input_shape)\n input_dists = [np.random.dirichlet([1]*number_of_input_states)\n for _ in range(number_of_input_distributions)]\n input_dists = [np.reshape(dist, input_shape) for dist in input_dists]\n\n #create initial population\n conditional_outputs = create_conditonal_distributions(\n evolutionary_parameters[\"population_size\"], number_of_output_states,\n len(input_shape)\n )\n mutation_size = evolutionary_parameters[\"mutation_size\"]\n change_mutation_size = evolutionary_parameters[\"change_mutation_size\"]\n conditional_outputs = [\n ConditionalOutput(cond_output, mutation_size, change_mutation_size)\n for cond_output in conditional_outputs\n ]\n #for dist in conditional_outputs:\n # found_sum = np.sum(dist.cond_output)\n # expected_sum = reduce(lambda x,y: x*y, dist.cond_output.shape[:-1])\n # if abs(found_sum-expected_sum) > 10**(-7):\n # raise ValueError()\n\n for conditional_output in conditional_outputs:\n conditional_output.evaluate(goal_distance, input_dists)\n \n initial_distance = ea.sort_individuals(conditional_outputs)[-1].score\n\n #evolve the population\n find_conditional_output = FindConditionalOutput(\n conditional_outputs, goal_distance, \n evolutionary_parameters[\"number_of_generations\"], \n evolutionary_parameters[\"number_of_children\"], \n evolutionary_parameters[\"parent_selection_mode\"]\n )\n find_conditional_output.evolve(\n evolutionary_parameters[\"generational\"], \n input_dists\n )\n\n final_distance = find_conditional_output.get_best_individual()\n print(\"initial distance {}, distance after evolution {}\".format(\n initial_distance, final_distance.score\n )) \n return find_conditional_output.individuals[0]\n\nclass ConditionalOutput():\n \"\"\"\n Attributes:\n ----------\n cond_output: nd-array, \n a conditional probability distribution (last axis are the conditional\n probabilities)\n mutation_size: a positive number\n change_mutation_size: a postive number\n score: a number\n\n \"\"\"\n def __init__(self, cond_output, start_mutation_size, change_mutation_size):\n \"\"\"create an individual for an individual algorithms\n\n Parameters:\n ----------\n cond_output: nd-array\n Representing a conditional output diistribtution (with the the\n output on the last axis)\n \n\n \"\"\"\n self.cond_output = cond_output\n self.mutation_size = start_mutation_size\n self.change_mutation_size = change_mutation_size\n self.score = None\n\n def mutate(self, timestep):\n \"\"\"\n Mutate the probability distribution\n\n \"\"\"\n #first update the mutation size\n #self.mutation_size += max(\n # np.random.uniform(-self.change_mutation_size, self.change_mutation_size), 0\n #)\n old_mutation_size = self.mutation_size \n proposed_change = np.random.uniform(-self.change_mutation_size, self.change_mutation_size)\n self.mutation_size = max(0, self.mutation_size + proposed_change)\n #print(\"{} {}\".format(self.change_mutation_size, proposed_change))\n #print(\"timestep {} old mutation size {} mutation_size {}\".format(timestep, old_mutation_size, self.mutation_size))\n\n input_shape = self.cond_output.shape[:-1]\n number_of_output_states = self.cond_output.shape[-1]\n lists_of_possible_states_per_variable = [\n range(states) for states in input_shape\n ]\n for state in itertools.product(*lists_of_possible_states_per_variable):\n mutation = nudge.find_noise_vector(number_of_output_states, \n self.mutation_size)\n self.cond_output[state] = nudge.nudge_states(\n mutation, self.cond_output[state]\n )\n\n if abs(np.sum(self.cond_output[state])-1) > 10**-7:\n raise ValueError()\n\n def evaluate(self, goal_distance, input_dists=None, \n number_of_input_dists=None):\n \"\"\"\n\n Parameters:\n ----------\n goal_distance:\n input_dists:\n number_of_input_dists:\n\n \"\"\"\n input_shape = list(self.cond_output.shape[:-1])\n if input_dists is None:\n input_dists = []\n for i in range(number_of_input_dists):\n input_dist = np.random.dirichlet(\n reduce(lambda x,y: x*y, input_shape)*[1]\n )\n input_dists.append(np.reshape(input_dist, input_shape))\n\n number_of_input_vars = len(input_dists[0].shape)\n outputs = []\n for input_dist in input_dists:\n joint = probability_distributions.compute_joint(\n input_dist, self.cond_output, set(range(0, number_of_input_vars, 1))\n )\n output = probability_distributions.ProbabilityArray(joint).marginalize(\n set([number_of_input_vars])\n )\n outputs.append(output)\n\n average_dist = np.mean(np.array(outputs), axis=0)\n distance = np.mean(\n [np.sum(np.absolute(output-average_dist)) for output in outputs]\n )\n self.score = abs(distance-goal_distance)\n\ndef create_conditonal_distributions(\n number_of_conditional_outputs, number_of_states, \n number_of_input_variables\n ):\n \"\"\"\n Create conditional output arrays \n\n Parameters:\n ----------\n number_of_conditional_outputs: an integer\n number_of_states: an integer\n number_of_input_variables: an integer\n\n Returns:\n -------\n a list of nd-arrays representing conditonal outputs \n\n \"\"\"\n conditional_outputs = []\n for _ in range(number_of_conditional_outputs):\n cond_shape = [number_of_states]*(number_of_input_variables+1)\n cond_output = [\n probability_distributions.compute_joint_uniform_random((number_of_states,))\n for i in range(number_of_states**(number_of_input_variables))\n ]\n cond_output = np.reshape(np.array(cond_output), cond_shape)\n conditional_outputs.append(cond_output)\n\n return conditional_outputs\n\nclass FindConditionalOutput():\n \"\"\" \n A class that uses evolutionary algorithms to find a distribution \n with a certain entropy\n\n Attributes:\n ----------\n individuals: list of IndividualDistribution objects\n goal_distance: a number\n number_of_generations: an integer\n number_of_children: an integer\n parent_selection_mode: Either \"rank_exponential\" or None\n\n \"\"\"\n def __init__(self, individuals, goal_distance, number_of_generations,\n number_of_children, parent_selection_mode):\n \"\"\"Create a FindConditionalOutput object\"\"\"\n self.individuals = individuals\n self.goal_distance = goal_distance\n self.number_of_generations = number_of_generations\n self.number_of_children = number_of_children\n self.parent_selection_mode = parent_selection_mode\n\n def get_best_individual(self):\n return ea.sort_individuals(self.individuals)[0]\n\n def evolve(self, generational, input_dists):\n \"\"\"\n Evolve the population\n \n Parameters:\n ----------\n generational: Boolean\n Whether to discard the old individuals at every new timestep\n number_of_input_distributions: an integer\n\n \"\"\"\n for timestep in range(self.number_of_generations):\n if TEST:\n print(\"timestep {}, worst {}, best {}\".format(\n timestep, self.individuals[-1].score, self.individuals[0].score\n ))\n parents = ea.select_parents(\n self.individuals, self.number_of_children*2,\n self.parent_selection_mode\n )\n children = self.create_children(parents, self.number_of_children, timestep)\n for child in children:\n child.evaluate(self.goal_distance, input_dists)\n\n self.individuals = ea.select_new_population(\n self.individuals, children, len(self.individuals), \n generational\n )\n\n def create_children(self, parents, number_of_children, timestep):\n \"\"\"\n Create new individuals.\n\n Parameters:\n ----------\n parents: a list of individual objects\n number_of_children: an integer\n\n \"\"\"\n children = []\n for i in range(number_of_children):\n children.append(self.recombine(\n parents[i], parents[number_of_children+i]\n ))\n for child in children:\n child.mutate(timestep)\n\n return children\n\n def recombine(self, parent1, parent2):\n \"\"\"recombine two individuals to create a new individual\n \n Parameters:\n ----------\n parent1: Individual object\n parent2: Individual object\n timestamp: a number\n\n Returns: Individual object\n\n \"\"\"\n gene_choice = np.random.choice([1,2])\n mutation_size_choice = np.random.choice([1,2])\n if gene_choice == 1:\n genes = np.copy(parent1.cond_output)\n else:\n genes = np.copy(parent2.cond_output)\n\n if mutation_size_choice == 1:\n mutation_size = parent1.mutation_size\n change_mutation_size = parent1.change_mutation_size\n #change_mutation_size = parent2.mutation_size\n else:\n mutation_size = parent2.mutation_size\n change_mutation_size = parent2.change_mutation_size\n #change_mutation_size = parent2.mutation_size\n \n return ConditionalOutput(genes, mutation_size, change_mutation_size)\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"function_generation.py","file_name":"function_generation.py","file_ext":"py","file_size_in_byte":11341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"61695190","text":"import helper\nimport re\nfrom theano import function, config, shared, tensor, sandbox\nimport numpy\nimport time\n\n# 读入数据\ndir = './data/寒门首辅.txt'\ntext = helper.load_text(dir)\n\n# 设置一下要用多少个字来训练,方便调试。这里先用100000字进行训练\nnum_words_for_training = 100000\ntext = text[:num_words_for_training]\n\nlines_of_text = text.split('\\n')\nlines_of_text = lines_of_text[14:]\nlines_of_text = [lines for lines in lines_of_text if len(lines) > 0]\n# print(lines_of_text[:20])\nlines_of_text = [lines.strip() for lines in lines_of_text]\n\n# 生成一个正则,负责找『[]』包含的内容\npattern = re.compile(r'\\[.*\\]')\n# 将所有指定内容替换成空\nlines_of_text = [pattern.sub(\"\", lines) for lines in lines_of_text]\n# print(lines_of_text[:20])\n# 将上面的正则换成负责找『<>』包含的内容\npattern = re.compile(r'<.*>')\n\n# 将所有指定内容替换成空\nlines_of_text = [pattern.sub(\"\", lines) for lines in lines_of_text]\n\n# 下一步,把每句话最后的『……』换成『。』。\n# 将上面的正则换成负责找『......』包含的内容\npattern = re.compile(r'\\.+')\n\n# 将所有指定内容替换成空\nlines_of_text = [pattern.sub(\"。\", lines) for lines in lines_of_text]\n\n# 将上面的正则换成负责找行中的空格\npattern = re.compile(r' +')\n\n# 将所有指定内容替换成空\nlines_of_text = [pattern.sub(\",\", lines) for lines in lines_of_text]\n\n\n# 将上面的正则换成负责找句尾『\\\\r』的内容\npattern = re.compile(r'\\\\r')\n\n# 将所有指定内容替换成空\nlines_of_text = [pattern.sub(\"\", lines) for lines in lines_of_text]\n\n\n# 创建文字对应数字和数字对应文字的两个字典\ndef create_lookup_tables(input_data):\n\n vocab = set(input_data) #一个无序不重复元素集\n\n\n # 文字到数字的映射\n vocab_to_int = {word: idx for idx, word in enumerate(vocab)}\n\n # 数字到文字的映射\n int_to_vocab = dict(enumerate(vocab))\n\n return vocab_to_int, int_to_vocab\n\n# 创建一个符号查询表,把逗号,句号等符号与一个标志一一对应,用于将『我。』和『我』这样的类似情况区分开来,排除标点符号的影响。\ndef token_lookup():\n\n symbols = set(['。', ',', '“', \"”\", ';', '!', '?', '(', ')', '——', '\\n'])\n\n tokens = [\"P\", \"C\", \"Q\", \"T\", \"S\", \"E\", \"M\", \"I\", \"O\", \"D\", \"R\"]\n\n return dict(zip(symbols, tokens))\n\n# 预处理一下数据,并保存到磁盘,以便下次直接读取 ================================================================================================================\nhelper.preprocess_and_save_data(''.join(lines_of_text), token_lookup, create_lookup_tables)\n\nint_text, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess()\n\n# 训练循环次数\nnum_epochs = 200\n\n# batch大小\nbatch_size = 256\n\n# lstm层中包含的unit个数\nrnn_size = 512\n\n# embedding layer的大小\nembed_dim = 512\n\n# 训练步长\nseq_length = 30\n\n# 学习率\nlearning_rate = 0.003\n\n# 每多少步打印一次训练信息\nshow_every_n_batches = 30\n\n# 保存session状态的位置\nsave_dir = './save'\n","sub_path":"Chinese-novel-generation-master/testTheano.py","file_name":"testTheano.py","file_ext":"py","file_size_in_byte":3137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"130410019","text":"import sys\nimport pathlib as pb\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.utils import spectral_norm\n\nDIR_PATH = pb.Path(__file__).resolve().parent\nsys.path.append(str(DIR_PATH))\nimport custom_ops\n\n\n\nclass SoftThresholding(nn.Module):\n def __init__(self):\n super().__init__()\n self.lambd = nn.Parameter(torch.ones(1))\n \n def forward(self, u):\n return custom_ops.soft_thresholding(u, self.lambd)\n\n\nclass SpectralConv2d(nn.Module):\n def __init__(self, *args, **kwargs):\n super().__init__()\n self.module = spectral_norm(nn.Conv2d(*args, **kwargs))\n \n def forward(self, x):\n return self.module(x)\n \n \nclass AdaIN(nn.Module):\n def __init__(self, in_channels, out_channels=None, eps=1e-5):\n super().__init__()\n if out_channels is None:\n out_channels = in_channels\n self.beta = spectral_norm(nn.Linear(in_channels, out_channels))\n self.gamma = spectral_norm(nn.Linear(in_channels, out_channels))\n self.eps = eps\n \n def forward(self, x, y):\n beta = self.beta(y)\n gamma = self.gamma(y)\n x = (x - x.mean(dim=(1, 2, 3), keepdim=True)) \\\n * torch.rsqrt(x.std(dim=(1, 2, 3), keepdim=True) + 1e-5)\n return x * gamma[:, :, None, None] + beta[:, :, None, None]\n \n \nclass NoiseApplier(nn.Module):\n def __init__(self, channels):\n super().__init__()\n self.scale = nn.Parameter(torch.empty(channels), requires_grad=True)\n torch.nn.init.xavier_normal_(self.scale.data)\n\n def forward(self, x, noise=None):\n b, _, h, w = x.shape\n dtype, device = x.dtype, x.device\n \n if noise is None:\n # Explicit noise in the argument is needed for proper validation\n noise = torch.randn((b, 1, h, w), dtype=dtype, device=device)\n \n return x + self.scale.view(1, -1, 1, 1) * noise\n \n \nclass StylishUNet(nn.Module):\n def __init__(\n self\n , num_classes=1\n , min_channels=32\n , max_channels=512\n , num_down_blocks=4\n \n , use_texture_injection=False\n , use_noise_injection=False\n ):\n\n assert num_down_blocks > 1\n assert max_channels // (2 ** num_down_blocks) == min_channels\n\n super().__init__()\n self.num_classes = num_classes\n self.num_down_blocks = num_down_blocks\n self.min_side = 2 ** self.num_down_blocks\n\n # Initial feature extractor from RGB image\n self.init_block = nn.Conv2d(3, min_channels, kernel_size=1)\n\n self.encoder_blocks = nn.ModuleList()\n self.encoder_down_blocks = nn.ModuleList()\n self.decoder_blocks = nn.ModuleList()\n self.decoder_up_blocks = nn.ModuleList()\n self.soft_thresholders = nn.ModuleList()\n \n if use_noise_injection:\n self.encoder_noise_applier_blocks = nn.ModuleList()\n self.decoder_noise_applier_blocks = nn.ModuleList()\n if use_texture_injection:\n self.encoder_adain_blocks = nn.ModuleList()\n self.decoder_adain_blocks = nn.ModuleList()\n \n for b in range(1, num_down_blocks + 1):\n ## Encoder part\n in_channels = min_channels if b == 1 else out_channels\n out_channels = max_channels // 2 ** (num_down_blocks - b)\n\n encoder_block = self._construct_block(in_channels)\n self.encoder_blocks.append(encoder_block)\n\n encoder_down_block = self._construct_down_block(in_channels, out_channels)\n self.encoder_down_blocks.append(encoder_down_block)\n \n self.soft_thresholders.append(SoftThresholding())\n\n if out_channels != max_channels:\n decoder_block = self._construct_block(\n out_channels\n , in_channels=out_channels * 2\n , prepend_with_dropout=True\n )\n else:\n # Bottleneck\n decoder_block = self._construct_block(out_channels)\n self.decoder_blocks.insert(0, decoder_block)\n\n decoder_up_block = self._construct_up_block(out_channels, in_channels)\n self.decoder_up_blocks.insert(0, decoder_up_block)\n \n if use_noise_injection:\n self.encoder_noise_applier_blocks.insert(0, NoiseApplier(in_channels))\n self.decoder_noise_applier_blocks.insert(0, NoiseApplier(out_channels))\n if use_texture_injection:\n self.encoder_adain_blocks.insert(0, AdaIN(in_channels))\n self.decoder_adain_blocks.insert(0, AdaIN(out_channels))\n\n self.final_block = self._construct_block(\n min_channels\n , in_channels=min_channels * 2\n , prepend_with_dropout=True\n )\n \n if use_noise_injection:\n self.decoder_noise_applier_blocks.append(NoiseApplier(min_channels))\n if use_texture_injection:\n self.decoder_adain_blocks.append(AdaIN(min_channels))\n\n self.conv_out = nn.Conv2d(min_channels, num_classes, kernel_size=1)\n\n def forward(self, inputs, textures=None, noise=None):\n *_, h, w = inputs.shape\n valid_h = self._find_closest_to(h, divisible_by=self.min_side)\n valid_w = self._find_closest_to(w, divisible_by=self.min_side)\n x = F.interpolate(inputs, size=(valid_h, valid_w), mode='bilinear')\n\n x = self.init_block(x)\n\n down_features = []\n for i, (e, ed) in enumerate(zip(self.encoder_blocks, self.encoder_down_blocks)):\n x = e(x)\n \n if hasattr(self, 'encoder_noise_applier_blocks'):\n x = self.encoder_noise_applier_blocks[i](x, noise)\n if hasattr(self, 'encoder_adain_blocks'):\n x = self.encoder_adain_blocks[i](x, textures)\n \n down_features.insert(0, x.clone())\n x = ed(x)\n\n for i, (d, du) in enumerate(zip(self.decoder_blocks, self.decoder_up_blocks)):\n if i < 0:\n # Bottleneck\n x = d(x)\n else:\n x = torch.cat([\n x\n , self.soft_thresholders[i](down_features[i])\n ], dim=1)\n x = d(x)\n \n if hasattr(self, 'decoder_noise_applier_blocks'):\n x = self.decoder_noise_applier_blocks[i](x, noise)\n if hasattr(self, 'decoder_adain_blocks'):\n x = self.decoder_adain_blocks[i](x, textures)\n \n x = du(x)\n\n x = torch.cat([\n x\n , self.soft_thresholders[0](down_features[0])\n ], dim=1)\n x = self.final_block(x)\n \n if hasattr(self, 'decoder_noise_applier_blocks'):\n x = self.decoder_noise_applier_blocks[-1](x, noise)\n if hasattr(self, 'decoder_adain_blocks'):\n x = self.decoder_adain_blocks[-1](x, textures)\n \n x = self.conv_out(x)\n x = F.interpolate(x, size=(h, w), mode='bilinear')\n logits = x\n\n assert logits.shape == (inputs.shape[0], self.num_classes, inputs.shape[2], inputs.shape[3]), 'Wrong shape of the logits'\n \n return logits\n\n def _construct_block(self, channels, in_channels=None, prepend_with_dropout=False):\n block_layers = [\n SpectralConv2d(channels, channels, kernel_size=3, padding=1, bias=False)\n , nn.BatchNorm2d(channels)\n , nn.LeakyReLU(inplace=True)\n , SpectralConv2d(channels, channels, kernel_size=3, padding=1, bias=False)\n , nn.BatchNorm2d(channels)\n , nn.LeakyReLU(inplace=True)\n ]\n\n if in_channels is not None:\n # To fuse concatenated tensor\n block_layers.insert(0, nn.Conv2d(in_channels, channels, kernel_size=1))\n\n if prepend_with_dropout:\n block_layers.insert(0, nn.Dropout2d(0.5))\n\n return nn.Sequential(*block_layers)\n\n def _construct_down_block(self, in_channels, out_channels):\n block_layers = [\n nn.MaxPool2d(2)\n , SpectralConv2d(in_channels, out_channels, kernel_size=1)\n ]\n return nn.Sequential(*block_layers)\n\n def _construct_up_block(self, in_channels, out_channels):\n return nn.ConvTranspose2d(in_channels, out_channels, kernel_size=3, stride=2, padding=1, output_padding=1)\n\n @classmethod\n def _find_closest_to(cls, num, divisible_by):\n if num % divisible_by == 0:\n closest = num\n else:\n lesser = num - (num % divisible_by)\n bigger = (num + divisible_by) - (num % divisible_by)\n closest = lesser if abs(num - lesser) < abs(num - bigger) else bigger\n return closest\n\n\nclass DataConsistedStylishUNet(StylishUNet):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n \n def forward(self, x, known_freq, mask, textures=None, noise=None):\n data_consistency = custom_ops.data_consistency(x, known_freq, mask)\n x = torch.cat([x, data_consistency], dim=1)\n return super().forward(x, textures, noise)\n","sub_path":"src/custom_layers.py","file_name":"custom_layers.py","file_ext":"py","file_size_in_byte":9242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"402381984","text":"\"\"\"Generic steps for accessing aws buckets\"\"\"\nimport json\nimport logging\n\nfrom behave import given, use_step_matcher, when\nfrom behave.runner import Context\nimport boto3\n\nLOGGER = logging.getLogger(__name__)\n\n# Enable the regex step matcher for behave in this class\nuse_step_matcher(\"re\")\n\n\n@given(\n \"the (?PJSON|json|tarball) request data from the (?P[-\\d\\w_]+) S3 bucket at the path (?P[-\\d\\w/._]+)\"\n)\ndef retrieve_s3_payload(\n ctx: Context, request_type: str, bucket: str, key_path: str\n) -> None:\n \"\"\"Retrieve JSON data from an aws s3 bucket and set as the request data\n\n Args:\n ctx: The behave context\n request_type: The type of data to send\n bucket: The s3 bucket containing the JSON request data\n key_path: The path to the data in aws\n\n \"\"\"\n LOGGER.debug(f\"Attempting to retrieve data from {bucket}/{key_path}\")\n s3 = boto3.client(\"s3\")\n payload = s3.get_object(Bucket=bucket, Key=key_path)\n LOGGER.debug(f\"Successfully retrieved data from {bucket}/{key_path}\")\n if request_type in (\"JSON\", \"json\"):\n ctx.request_data = json.loads(payload[\"Body\"].read().decode())\n else:\n ctx.request_data = payload[\"Body\"].read()\n\n\n@when(\n \"the JSON request data is sent to the (?P[-\\d\\w_]+) S3 bucket at the path (?P[-\\d\\w/._]+)\"\n)\ndef send_s3_payload(ctx: Context, bucket: str, key_path: str) -> None:\n \"\"\"Send JSON data to an aws s3 bucket\n\n Args:\n ctx: The behave context\n bucket: The s3 bucket containing the\n key_path: The path to the data in aws\n\n \"\"\"\n LOGGER.debug(f\"Attempting to send data to {bucket}/{key_path}\")\n s3 = boto3.client(\"s3\")\n ctx.response = s3.put_object(Body=ctx.request_data, Bucket=bucket, Key=key_path)\n LOGGER.debug(f\"Successfully sent data to {bucket}/{key_path}\")\n","sub_path":"src/ns_behave/step_library/generic_behave_steps/generic_aws_steps.py","file_name":"generic_aws_steps.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"114228331","text":"class TreeNode(object):\n def __init__(self, key, val, left=None, right=None, parent=None):\n self.key = key\n self.payload = val\n self.leftChild = left\n self.rightChild = right\n self.parent = parent\n\n def hasLeftChild(self):\n return self.leftChild\n\n def hasRightChild(self):\n return self.rightChild\n\n def isLeftChild(self):\n return self.parent and self.parent.leftChild == self\n\n def isRightChild(self):\n return self.parent and self.parent.rightChild == self\n\n def isRoot(self):\n return not self.parent\n\n def isLeaf(self):\n return not(self.leftChild or self.rightChild)\n\n def hasAnyChildren(self):\n return self.leftChild or self.rightChild\n\n def hasBothChildren(self):\n return self.leftChild and self.rightChild\n\n def replaceNodeData(self, key, value, lc, rc):\n self.key = key\n self.payload = value\n self.leftChild = lc\n self.rightChild = rc\n if self.hasLeftChild():\n self.leftChild.parent = self\n if self.hasRightChild():\n self.rightChild.parent = self\n\n\nclass BinarySearchTree(TreeNode):\n def __init__(self):\n # self.root is refrence to TreeNode, which is root\n # of primary TreeNode\n self.root = None\n self.size = 0\n\n def size(self):\n return self.size\n\n def __len__(self):\n return self.size\n\n def __iter__(self):\n return self.root.__iter__()\n\n def put(self, key, val):\n # checks if there is root\n # if there is a root, lets transverse along tree\n if self.root:\n self._put(key, val, self.root)\n else:\n # else if there is not root, lets set a root\n # which is a TreeNode instance\n self.root = BinarySearchTree()\n self.root.key = key\n self.root.value = val\n self.size = self.size + 1\n\n def _put(self, key, val, currentNode):\n\n if key < currentNode.key:\n if currentNode.hasLeftChild():\n self._put(key, val, currentNode.leftChild)\n else:\n\n #currentNode.leftChild = BinarySearchTree(\n # key, val, parent=currentNode)\n currentNode.leftChild = BinarySearchTree()\n currentNode.leftChild.key = key\n currentNode.leftChild.val = val\n currentNode.leftChild.parent = currentNode\n import pdb;pdb.set_trace()\n else:\n if currentNode.hasRightChild():\n self._put(key, val, currentNode.rightChild)\n else:\n #currentNode.rightChild = BinarySearchTree(\n # key, val, parent=currentNode)\n currentNode.rightChild = BinarySearchTree()\n currentNode.rightChild.key = key\n currentNode.rightChild.val = val\n currentNode.rightChild.parent = currentNode\n import pdb;pdb.set_trace()\n\n def __setitem__(self, k, v):\n self.put(k, v)\n\n def get(self, key):\n if self.root:\n res = self._get(key, self.root)\n if res:\n return res.payload\n else:\n return None\n else:\n return None\n\n def _get(self, key, currentNode):\n if not currentNode:\n return None\n if key == currentNode.key:\n return currentNode\n if key < currentNode.key:\n return self._get(key, currentNode.leftChild)\n else:\n return self._get(key, currentNode.rightChild)\n\n def __getitem__(self, key):\n # this method allows to access instance[index]\n # format.\n return self.get(key)\n\n def __contains__(self, key):\n \"\"\"\n __contains__ overloads the 'in' operator\n allows us to do something simliar to\n if 'Northfield' in myZipTree:\n print(\"oom ya ya\")\n \"\"\"\n if self._get(key, self.root):\n return True\n else:\n return False\n\n def delete(self, key):\n if self.size > 1:\n nodeToRemove = self._get(key, self.root)\n if nodeToRemove:\n self.remove(nodeToRemove)\n self.size = self.size - 1\n else:\n raise KeyError('Error, key was not found')\n elif self.size == 1 and self.root.key == key:\n self.root = None\n self.size = self.size - 1\n else:\n raise KeyError('Error, key was not found')\n\n def __delitem__(self, key):\n self.delete(key)\n\n def remove(self, currentNode):\n if currentNode.isLeaf():\n # current Leaf has only one child\n if currentNode == currentNode.parent.leftChild:\n currentNode.parent.leftChild = None\n else:\n currentNode.parent.rightChild = None\n\n elif currentNode.hasBothChildren():\n # interior\n succ = currentNode.findSuccessor()\n succ.spliceOut()\n currentNode.key = succ.key\n currentNode.payload = succ.payload\n\n else:\n # The node to be deleted has only one child.\n if currentNode.hasLeftChild():\n if currentNode.isLeftChild():\n currentNode.leftChild.parent = currentNode.parent\n currentNode.parent.leftChild = currentNode.leftChild\n elif currentNode.isRightChild():\n currentNode.rightChild.parent = currentNode.parent\n currentNode.parent.rightChild = currentNode.rightChild\n else:\n # this is a root node, replace it's data with it's\n # left children\n self.replaceNodeData(\n currentNode.leftChild.key,\n currentNode.leftChild.value,\n currentNode.leftChild,\n currentNode.rightChild\n )\n else:\n if currentNode.isLeftChild():\n currentNode.leftChild.parent = currentNode.parent\n currentNode.parent.leftChild = currentNode.leftChild\n elif currentNode.isRightChild():\n currentNode.rightChild.parent = currentNode.parent\n currentNode.parent.rightChild = currentNode.rightChild\n else:\n # this is a root node, replace it's data with it's\n # left children\n self.replaceNodeData(\n currentNode.leftChild.key,\n currentNode.leftChild.value,\n currentNode.leftChild,\n currentNode.rightChild\n )\n\n def __iter__(self):\n if self:\n if self.hasLeftChild():\n for elem in self.leftChiLd:\n yield elem\n yield self.key\n if self.hasRightChild():\n for elem in self.rightChild:\n yield elem\n\n def findSuccessor(self):\n succ = None\n if self.hasRightChild():\n succ = self.rightChild.findMin()\n else:\n if self.parent:\n if self.hasLeftChild():\n succ = self.parent\n else:\n self.parent.rightChild = None\n succ = self.parent.findSuccessor()\n self.parent.rightChild = self\n return self\n\n def findMin(self):\n if self.hasLeftChild():\n return self.leftChild.findMin()\n else:\n return self\n\n def spliceOut(self):\n if self.isLeaf():\n if self.isLeftChild():\n self.parent.leftChild = None\n else:\n self.parent.rightChild = None\n elif self.hasAnyChildren():\n if self.hasLeftChild():\n if self.isLeftChild():\n self.parent.leftChild = self.leftChild\n else:\n self.parent.rightChild = self.leftChild\n self.leftChild.parent = self.parent\n else:\n if self.isLeftChild():\n self.parent.leftChild = self.rightChild\n else:\n self.parent.rightChild = self.rightChild\n self.rightChild.parent = self.parent\n\n\n\nmytree = BinarySearchTree()\nmytree[17] = \"17\"\nmytree[5] = \"5\"\nmytree[35] = \"35\"\nmytree[2] = \"2\"\nmytree[11] = \"11\"\nmytree[9] = \"9\"\nmytree[16] = \"16\"\nmytree[7] = \"7\"\nmytree[29] = \"29\"\nmytree[38] = \"38\"\n\ndel(mytree[5])\nprint(mytree[5])\nprint(mytree[7])\nprint(mytree.size)\n","sub_path":"binarySearchTreeMod.py","file_name":"binarySearchTreeMod.py","file_ext":"py","file_size_in_byte":8737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"197977858","text":"from openerp import models, fields, api\n\nclass dym_report_penjualansdb_sm(models.Model):\n _inherit = 'dealer.sale.order'\n \n def _report_xls_penjualansdb_fields(self, cr, uid, context=None):\n return [\n 'no',\\\n 'branch_status',\\\n 'area',\\\n 'branch_code',\\\n 'branch_name',\\\n 'invoice_number',\\\n 'invoice_date',\\\n 'last_update_time',\\\n 'invoice_status',\\\n 'no_registrasi',\\\n 'spk_name',\\\n 'name',\\\n 'date_order',\\\n 'state',\\\n 'state_ksu',\\\n 'state_picking',\\\n 'oos_number',\\\n 'is_cod',\\\n 'sls_pay',\\\n 'vcust_id',\\\n 'finco_code',\\\n 'finco_branch',\\\n 'no_po',\\\n 'tgl_po',\\\n 'jp_po',\\\n 'cust_code',\\\n 'cust_name',\\\n 'cabang_partner',\\\n 'alamat_cust_name',\\\n 'kota_cust_name',\\\n 'no_hp_cust_beli',\\\n 'cust_stnk_code',\\\n 'cust_stnk_name',\\\n 'alamat_cust_stnk_name',\\\n 'kota_cust_stnk_name',\\\n 'jns_kota_cust_stnk_name',\\\n 'kec_cust_stnk_name',\\\n 'kel_cust_stnk_name',\\\n 'no_hp_cust_stnk',\\\n 'cust_corp',\\\n 'nik_sales_name',\\\n 'sales_name',\\\n 'job_name',\\\n 'nik_sales_koor_name',\\\n 'sales_koor_name',\\\n 'spv_nik',\\\n 'spv_name',\\\n 'partner_komisi_id',\\\n 'partner_komisi_name',\\\n 'hutang_komisi_id',\\\n 'amount_hutang_komisi',\\\n 'pph_komisi',\\\n 'lot_name',\\\n 'lot_chassis',\\\n 'product_name',\\\n 'product_desc',\\\n 'pav_code',\\\n 'categ_name',\\\n 'categ2_name',\\\n 'prod_series',\\\n 'tahun_rakit',\\\n 'ps_ahm',\\\n 'ps_md',\\\n 'ps_finco',\\\n 'ps_dealer',\\\n 'ps_other',\\\n 'ps_total',\\\n 'price_unit',\\\n 'sales',\\\n 'disc_total',\\\n 'discount_po',\\\n 'discount_extern_ps',\\\n 'discount_intern_ps',\\\n 'disc_quo_incl_tax_no',\\\n 'price_bbn',\\\n 'piutang_total',\\\n 'dsb_name',\\\n 'dsbl_diskon_ahm',\\\n 'dsbl_diskon_md',\\\n 'dsbl_diskon_dealer',\\\n 'dsbl_diskon_finco',\\\n 'dsbl_diskon_others',\\\n 'dsbl_total_diskon',\\\n 'beban_cabang',\\\n 'price_subtotal',\\\n 'PPN',\\\n 'total',\\\n 'force_cogs',\\\n 'gp_dpp_minus_hpp',\\\n 'gp_unit',\\\n 'price_bbn_beli',\\\n 'gp_bbn',\\\n 'gp_total',\\\n 'dpp_insentif_finco',\\\n 'tambahan_bbn',\\\n 'product_qty',\\\n 'qty_pic',\\\n 'qty_retur',\\\n 'net_sales',\\\n 'proposal_id',\\\n 'proposal_address',\\\n 'npwp_cust',\\\n 'pkp',\\\n 'tax_type',\\\n 'faktur_pajak',\\\n 'or_name',\\\n 'ar_days',\\\n 'tgl_lunas',\\\n 'md_code',\\\n ]","sub_path":"dym_report_penjualansdb/models/dym_report_penjualansdb_dso.py","file_name":"dym_report_penjualansdb_dso.py","file_ext":"py","file_size_in_byte":3306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"17753396","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\n\nfrom flatland.envs.observations import TreeObsForRailEnv, GlobalObsForRailEnv\nfrom flatland.envs.predictions import ShortestPathPredictorForRailEnv\nfrom flatland.envs.rail_env import RailEnv\nfrom flatland.envs.rail_generators import rail_from_grid_transition_map, rail_from_file, complex_rail_generator, \\\n random_rail_generator, empty_rail_generator\nfrom flatland.envs.schedule_generators import random_schedule_generator, complex_schedule_generator, \\\n schedule_from_file\nfrom flatland.utils.simple_rail import make_simple_rail\n\n\ndef test_empty_rail_generator():\n np.random.seed(0)\n n_agents = 1\n x_dim = 5\n y_dim = 10\n\n # Check that a random level at with correct parameters is generated\n env = RailEnv(width=x_dim, height=y_dim, rail_generator=empty_rail_generator(), number_of_agents=n_agents)\n env.reset()\n # Check the dimensions\n assert env.rail.grid.shape == (y_dim, x_dim)\n # Check that no grid was generated\n assert np.count_nonzero(env.rail.grid) == 0\n # Check that no agents where placed\n assert env.get_num_agents() == 0\n\n\ndef test_random_rail_generator():\n np.random.seed(0)\n n_agents = 1\n x_dim = 5\n y_dim = 10\n\n # Check that a random level at with correct parameters is generated\n env = RailEnv(width=x_dim, height=y_dim, rail_generator=random_rail_generator(), number_of_agents=n_agents)\n env.reset()\n assert env.rail.grid.shape == (y_dim, x_dim)\n assert env.get_num_agents() == n_agents\n\n\ndef test_complex_rail_generator():\n n_agents = 10\n n_start = 2\n x_dim = 10\n y_dim = 10\n min_dist = 4\n\n # Check that agent number is changed to fit generated level\n env = RailEnv(width=x_dim, height=y_dim,\n rail_generator=complex_rail_generator(nr_start_goal=n_start, nr_extra=0, min_dist=min_dist),\n schedule_generator=complex_schedule_generator(), number_of_agents=n_agents)\n env.reset()\n assert env.get_num_agents() == 2\n assert env.rail.grid.shape == (y_dim, x_dim)\n\n min_dist = 2 * x_dim\n\n # Check that no agents are generated when level cannot be generated\n env = RailEnv(width=x_dim, height=y_dim,\n rail_generator=complex_rail_generator(nr_start_goal=n_start, nr_extra=0, min_dist=min_dist),\n schedule_generator=complex_schedule_generator(), number_of_agents=n_agents)\n env.reset()\n assert env.get_num_agents() == 0\n assert env.rail.grid.shape == (y_dim, x_dim)\n\n # Check that everything stays the same when correct parameters are given\n min_dist = 2\n n_start = 5\n n_agents = 5\n\n env = RailEnv(width=x_dim, height=y_dim,\n rail_generator=complex_rail_generator(nr_start_goal=n_start, nr_extra=0, min_dist=min_dist),\n schedule_generator=complex_schedule_generator(), number_of_agents=n_agents)\n env.reset()\n assert env.get_num_agents() == n_agents\n assert env.rail.grid.shape == (y_dim, x_dim)\n\n\ndef test_rail_from_grid_transition_map():\n rail, rail_map = make_simple_rail()\n n_agents = 3\n env = RailEnv(width=rail_map.shape[1], height=rail_map.shape[0], rail_generator=rail_from_grid_transition_map(rail),\n schedule_generator=random_schedule_generator(), number_of_agents=n_agents)\n env.reset(False, False, True)\n nr_rail_elements = np.count_nonzero(env.rail.grid)\n\n # Check if the number of non-empty rail cells is ok\n assert nr_rail_elements == 16\n\n # Check that agents are placed on a rail\n for a in env.agents:\n assert env.rail.grid[a.position] != 0\n\n assert env.get_num_agents() == n_agents\n\n\ndef tests_rail_from_file():\n file_name = \"test_with_distance_map.pkl\"\n\n # Test to save and load file with distance map.\n\n rail, rail_map = make_simple_rail()\n\n env = RailEnv(width=rail_map.shape[1], height=rail_map.shape[0], rail_generator=rail_from_grid_transition_map(rail),\n schedule_generator=random_schedule_generator(), number_of_agents=3,\n obs_builder_object=TreeObsForRailEnv(max_depth=2, predictor=ShortestPathPredictorForRailEnv()))\n env.reset()\n env.save(file_name)\n dist_map_shape = np.shape(env.distance_map.get())\n rails_initial = env.rail.grid\n agents_initial = env.agents\n\n env = RailEnv(width=1, height=1, rail_generator=rail_from_file(file_name),\n schedule_generator=schedule_from_file(file_name), number_of_agents=1,\n obs_builder_object=TreeObsForRailEnv(max_depth=2, predictor=ShortestPathPredictorForRailEnv()))\n env.reset()\n rails_loaded = env.rail.grid\n agents_loaded = env.agents\n\n assert np.all(np.array_equal(rails_initial, rails_loaded))\n assert agents_initial == agents_loaded\n\n # Check that distance map was not recomputed\n assert np.shape(env.distance_map.get()) == dist_map_shape\n assert env.distance_map.get() is not None\n\n # Test to save and load file without distance map.\n\n file_name_2 = \"test_without_distance_map.pkl\"\n\n env2 = RailEnv(width=rail_map.shape[1], height=rail_map.shape[0],\n rail_generator=rail_from_grid_transition_map(rail), schedule_generator=random_schedule_generator(),\n number_of_agents=3, obs_builder_object=GlobalObsForRailEnv())\n env2.reset()\n env2.save(file_name_2)\n\n rails_initial_2 = env2.rail.grid\n agents_initial_2 = env2.agents\n\n env2 = RailEnv(width=1, height=1, rail_generator=rail_from_file(file_name_2),\n schedule_generator=schedule_from_file(file_name_2), number_of_agents=1,\n obs_builder_object=GlobalObsForRailEnv())\n env2.reset()\n rails_loaded_2 = env2.rail.grid\n agents_loaded_2 = env2.agents\n\n assert np.all(np.array_equal(rails_initial_2, rails_loaded_2))\n assert agents_initial_2 == agents_loaded_2\n assert not hasattr(env2.obs_builder, \"distance_map\")\n\n # Test to save with distance map and load without\n\n env3 = RailEnv(width=1, height=1, rail_generator=rail_from_file(file_name),\n schedule_generator=schedule_from_file(file_name), number_of_agents=1,\n obs_builder_object=GlobalObsForRailEnv())\n env3.reset()\n rails_loaded_3 = env3.rail.grid\n agents_loaded_3 = env3.agents\n\n assert np.all(np.array_equal(rails_initial, rails_loaded_3))\n assert agents_initial == agents_loaded_3\n assert not hasattr(env2.obs_builder, \"distance_map\")\n\n # Test to save without distance map and load with generating distance map\n\n env4 = RailEnv(width=1,\n height=1,\n rail_generator=rail_from_file(file_name_2),\n schedule_generator=schedule_from_file(file_name_2),\n number_of_agents=1,\n obs_builder_object=TreeObsForRailEnv(max_depth=2),\n )\n env4.reset()\n rails_loaded_4 = env4.rail.grid\n agents_loaded_4 = env4.agents\n\n # Check that no distance map was saved\n assert not hasattr(env2.obs_builder, \"distance_map\")\n assert np.all(np.array_equal(rails_initial_2, rails_loaded_4))\n assert agents_initial_2 == agents_loaded_4\n\n # Check that distance map was generated with correct shape\n assert env4.distance_map.get() is not None\n assert np.shape(env4.distance_map.get()) == dist_map_shape\n","sub_path":"tests/test_generators.py","file_name":"test_generators.py","file_ext":"py","file_size_in_byte":7360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"375698096","text":"import csv\nimport sqlite3\nimport datetime\n\n\nITEM_TYPES = {'Intro', 'Body', 'Conc', 'Drinks'}\nDB = 'development.sqlite'\nSHEETS = ['menus/001_basta.csv', 'menus/002_pullman.csv', 'menus/003_formosa.csv']\n\n\ndef insert_value(conn, sql, values):\n cur = conn.cursor()\n cur.execute(sql, values)\n return cur.lastrowid\n\n\ndef insert_menu_section_type(conn, menu_section_type):\n \"\"\"\n `menuSectionTypes` (\n `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n `name` VARCHAR(255)\n );\n name -> 'Menu Type'\n \"\"\"\n sql = \"insert into menuSectionTypes ('name') values (?)\" \n return insert_value(conn, sql, menu_section_type)\n\n\ndef insert_menu_section_priority(conn, menu_section_priority):\n \"\"\"\n `menuSectionPriorities` (\n `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n `value` INTEGER\n );\n value -> 'Menu Section Order'\n \"\"\"\n sql = \"insert into menuSectionPriorities ('value') values (?)\"\n return insert_value(conn, sql, menu_section_priority)\n\n\ndef insert_menu_section(conn, menu_section):\n \"\"\"\n `menuSections` (\n `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n `name` VARCHAR(255),\n `menu_section_priority_id` INTEGER REFERENCES `menuSectionPriorities`(`id`) ON DELETE CASCADE ON UPDATE CASCADE,\n `menu_section_type_id` INTEGER REFERENCES `menuSectionTypes`(`id`) ON DELETE CASCADE ON UPDATE CASCADE,\n `restaurant_id` INTEGER,\n `created_at` DATETIME NOT NULL,\n `updated_at` DATETIME NOT NULL,\n `menu_id` INTEGER REFERENCES `menus`(`id`) ON DELETE SET NULL ON UPDATE CASCADE\n );\n name -> 'Menu Section'\n restaurant_id -> 'restaurant_id'\n \"\"\"\n sql = \"insert into menuSections ('name', 'menu_section_priority_id', 'menu_section_type_id', 'restaurant_id', 'created_at', 'updated_at', 'menu_id') values (?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ?)\"\n return insert_value(conn, sql, menu_section)\n\n\ndef insert_menu(conn, menu):\n \"\"\"\n `menus` (\n `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n `created_at` DATETIME NOT NULL,\n `updated_at` DATETIME NOT NULL,\n `restaurant_id` INTEGER REFERENCES `restaurants`(`id`) ON DELETE SET NULL ON UPDATE CASCADE\n );\n \"\"\"\n sql = \"insert into menus ('created_at', 'updated_at', 'restaurant_id') values (CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ?)\"\n return insert_value(conn, sql, menu)\n\n\ndef insert_restaurant(conn, restaurant):\n \"\"\"\n `restaurants` (\n `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n `name` VARCHAR(255),\n `location` VARCHAR(255),\n `created_at` DATETIME NOT NULL,\n `updated_at` DATETIME NOT NULL\n );\n \"\"\"\n sql = \"insert into restaurants ('name', 'location', 'created_at', 'updated_at') values (?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)\"\n return insert_value(conn, sql, restaurant)\n\n\ndef insert_item(conn, item):\n \"\"\"\n `items` (\n `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n `name` VARCHAR(255),\n `menu_section_id` INTEGER REFERENCES `menuSections`(`id`) ON DELETE NO ACTION ON UPDATE CASCADE,\n `created_at` DATETIME NOT NULL,\n `updated_at` DATETIME NOT NULL\n );\n name -> 'Item Title'\n \"\"\"\n sql = \"insert into items ('name', 'menu_section_id', 'created_at', 'updated_at') values (?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)\"\n return insert_value(conn, sql, item)\n\n\ndef insert_item_generic(conn, item_generic):\n \"\"\"\n `itemGenerics` (\n `id` INTEGER PRIMARY KEY AUTOINCREMENT,\n `name` VARCHAR(255)\n );\n \"\"\"\n sql = \"insert into itemGenerics ('name') values (?)\" \n return insert_value(conn, sql, item_generic)\n\n\nfor sheet in SHEETS:\n with open(sheet, newline='') as csvfile:\n reader = csv.DictReader(csvfile)\n # Set isolation_level to None to enable automatic commits\n conn = sqlite3.connect(DB, isolation_level=None)\n\n records = []\n for row in reader:\n ###############################\n # Parse the Excel spreadsheet #\n ###############################\n restaurant_id = int(row['restaurant_id'])\n title = row['Item Title']\n description = row['Item Description']\n if description == 'null' or description == '':\n description = None\n price = row['Price']\n if price == 'null' or price == '':\n price = None\n else:\n price = float(price)\n menu_section = row['Menu Section']\n menu_section_order = int(row['Menu Section Order'])\n item_type = row['Item Type']\n if item_type not in ITEM_TYPES:\n raise Exception\n menu_type = row['Menu Type']\n\n records.append((restaurant_id, title, description, price, menu_section, menu_section_order, item_type, menu_type))\n\n ##############################\n # Insert the database values #\n ##############################\n menu_section_priority_id = insert_menu_section_priority(conn, (menu_section_order,))\n # print(f'Menu Section Priority ID: {menu_section_priority_id}')\n\n menu_section_type_id = insert_menu_section_type(conn, (menu_type,))\n # print(f'Menu Section Type ID: {menu_section_type_id}')\n\n menu_id = insert_menu(conn, (restaurant_id,))\n # print(f'Menu ID: {menu_id}')\n\n menu_section_id = insert_menu_section(conn, (\n menu_section, \n menu_section_priority_id,\n menu_section_type_id,\n restaurant_id,\n menu_id\n )\n )\n # print(f'Menu Section ID: {menu_section_id}')\n\n item_id = insert_item(conn, (title, menu_section_id))\n # print(f'Item ID: {item_id}')\n\n print(f'{len(records)} records from {sheet} correctly inserted')\n","sub_path":"db/csv_parser.py","file_name":"csv_parser.py","file_ext":"py","file_size_in_byte":5933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"544114048","text":"from flask import Flask\n\napp = Flask(__name__)\nhits = 0\n\n@app.route('/')\ndef hello():\n global hits\n hits += 1\n return 'Hello World! I have been seen {} times.'.format(hits)\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", debug=True)\n","sub_path":"flask_app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"333174092","text":"#! /usr/bin/env python\n# coding=utf-8\n\nfrom OpenGL.GL import *\nfrom OpenGL.GLUT import *\nfrom OpenGL.GLU import *\nfrom operator import attrgetter\nfrom math import acos\nimport sys\n\nfrom Delaunay import Delaunay\n\n#4th home work from Graphics Computer at UFRJ by Lyang Higa Cano\n\n'''Instruction\n Just click to collect points\n press b to bild the triangulation\n press c to start again\n'''\n\n# setting globals\n\n#x and y size screen\nDIMX = 640 \nDIMY = 480 \nINF = 999999\n\n#stop collecting points\nstop = False\npoints = [] \nch_points = []\ntriangles = []\n\n\nclass Point:\n\n def __init__(self,x,y):\n self.x = x\n self.y = y\n\n def __repr__(self):\n return \"point(%s,%s)\"%(str(self.x),str(self.y))\n\n def __add__(self,v):\n return Point(self.x+v.x, self.y+v.y)\n \n def __sub__(self,v):\n return Point(self.x-v.x, self.y-v.y)\n\n\nclass Vector:\n \n def __init__(self,p1,p2):\n self.p1 = p1\n self.p2 = p2\n\n def __repr__(self):\n return \"vector(%s,%s)\"%(str(self.p1),str(self.p2))\n\n def __mul__(self, v):\n return ( ((self.p2.x - self.p1.x ) * (v.p2.x - v.p1.x))+ ((self.p2.y - self.p1.y ) * (v.p2.y - v.p1.y)) )\n\n def euclian_norm(self):\n return float( (self.p1.x - self.p2.x)**(2) + (self.p1.y - self.p2.y)**(2) )**(0.5)\n\n def angle(self,v):\n a = self.euclian_norm()\n b = v.euclian_norm()\n if( ( (self.p2.x == self.p1.x) and (self.p2.y == self.p1.y) ) or ( (v.p2.x == v.p1.x) and (v.p2.y == v.p1.y)) ):\n return INF\n c = (self * v)/ ( a * b )\n c = float('%.3f'%(c))\n return acos(c)\n \n\nclass Convex_hull:\n\n pl = []\n\n def __init__(self,p_list):\n self.p_list = p_list\n\n def jarvis(self):\n p1 = min(self.p_list,key=attrgetter('y'))\n self.pl.append(p1)\n p0 = Point(0,0)\n p = Point(1,0) \n v0 = Vector(p0,p)\n p2 = self.next(v0)\n self.pl.append(p2)\n i = 0\n px = p0\n while(px!=p1):\n vx = Vector(self.pl[-2],self.pl[-1])\n px = self.next(vx)\n self.pl.append(px)\n return self.pl \n\n def next(self,v0):\n last_p = self.pl[-1]\n min_ang = INF\n p0 = Point(0,0)\n for p in self.p_list:\n v = Vector(last_p,p)\n a = v0.angle(v)\n if(a < min_ang and a!= 0 ):\n min_ang = a\n p0 = p\n return p0\n\n\ndef initFun():\n glClearColor(1.0,1.0,1.0,0.0)\n glColor3f(0.0,0.0, 0.0)\n glPointSize(4.0)\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n gluOrtho2D(0.0,DIMX,0.0,DIMY)\n \n\ndef displayFun():\n glClear(GL_COLOR_BUFFER_BIT)\n \n #Draw a new point when it's cliked\n glBegin(GL_POINTS)\n for p in points:\n glVertex2f(p.x,p.y) \n glEnd()\n\n #Draw the line between ch two points\n glBegin(GL_LINE_STRIP)\n for p in ch_points:\n glVertex2f(p.x,p.y)\n glEnd()\n\n #Draw the triangles\n glBegin(GL_LINE_STRIP)\n for t in triangles:\n glVertex2f(points[t[0]].x, points[t[0]].y)\n glVertex2f(points[t[1]].x, points[t[1]].y)\n glVertex2f(points[t[2]].x, points[t[2]].y) \n glEnd()\n\n\n glFlush()\n\ndef mouse(button, state, x, y):\n global points, stop\n\n if button == GLUT_LEFT_BUTTON and state == GLUT_DOWN and stop==False:\n #we should count y from top-down\n p = Point(x,DIMY - y)\n points.append(p) \n\n glutPostRedisplay()\n\n\ndef keyboard(key, x, y):\n global points,ch_points, stop, triangles\n\n key = key.decode(\"utf-8\")\n \n #clear the points\n if str(key) == 'c':\n points = []\n ch_points = []\n stop =False\n\n #build the convex hull\n if str(key) == 'b':\n stop = True\n convex_hull_bilder()\n #triangulation\n tri = Delaunay()\n for ponto in points:\n tri.addPoint(ponto)\n\n triangles = tri.tri()\n\n glutPostRedisplay()\n\ndef convex_hull_bilder():\n global points,ch_points\n ch = Convex_hull(points)\n ch.pl = []\n ch.jarvis()\n ch_points = ch.pl\n\n \nif __name__ == '__main__':\n glutInit()\n glutInitWindowSize(DIMX,DIMY)\n glutCreateWindow(\"Triangulation - Delanay\")\n glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA) \n glutMouseFunc(mouse)\n glutKeyboardFunc(keyboard)\n glutDisplayFunc(displayFun)\n initFun()\n glutMainLoop()","sub_path":"trabalho4/trabalho4.py","file_name":"trabalho4.py","file_ext":"py","file_size_in_byte":4377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"468121812","text":"import multiprocessing\nimport os\nimport sys\nfrom collections import defaultdict\nimport pickle\nimport time\nimport copy\nimport re\n\nimport numpy as np\nfrom sklearn.metrics import classification_report\nfrom src.clustering import clustering\n\nfrom src.build_data import group_data, slice_data, BATCH_SIZE, replace_pronoun\nfrom src.preprocess import SPEAKER_MAP\nFULL_OUTPUT = True\n\nclass Evaluator(object):\n def __init__(self, model, test_data_q):\n self.model = model\n self.test_data_q = test_data_q\n\n def fast_eval(self, test_data=False):\n Y_true = []\n Y_pred = []\n for data in self.test_data_q:\n if len(data) == 3:\n data = data[:2]\n for X, y in group_data(data, 40, BATCH_SIZE):\n pred = self.model.predict_on_batch(X)\n Y_true.append(y)\n Y_pred.append(pred)\n\n Y_true = np.concatenate(Y_true)\n Y_true = Y_true.flatten()\n Y_pred = np.concatenate(Y_pred)\n Y_pred = Y_pred.flatten()\n Y_pred = np.round(Y_pred).astype(int)\n\n return classification_report(Y_true, Y_pred, digits=3)\n\n def write_results(self, df, dest_path):\n n_files = len(self.test_data_q)\n print(\"# files: %d\" % n_files)\n for i, data in enumerate(self.test_data_q):\n if i == n_files:\n break\n X, y, index_map = data\n pred = []\n for X, y in group_data([X, y], 40, batch_size=BATCH_SIZE):\n pred.append(self.model.predict_on_batch(X))\n pred = np.concatenate(pred)\n pred = pred.flatten()\n\n pair_results = {}\n for key in index_map:\n pair_results[(key[1], key[2])] = pred[index_map[key]]\n locs, clusters, _ = clustering(pair_results)\n doc_id = key[0]\n length = len(df.loc[df.doc_id == doc_id])\n\n sys.stdout.write(\"Saving results %d / %d\\r\" % (i + 1, n_files))\n sys.stdout.flush()\n corefs = ['-' for i in range(length)]\n for loc, cluster in zip(locs, clusters):\n start, end = loc\n if corefs[start] == '-':\n corefs[start] = '(' + str(cluster)\n else:\n corefs[start] += '|(' + str(cluster)\n\n if corefs[end] == '-':\n corefs[end] = str(cluster) + ')'\n elif start == end:\n corefs[end] += ')'\n else:\n corefs[end] += '|' + str(cluster) + ')'\n with open(os.path.join(dest_path, doc_id.split('/')[-1]), 'w') as f:\n f.write('#begin document (%s);\\n' % doc_id)\n for coref in corefs:\n f.write(doc_id + '\\t' + coref +'\\n')\n f.write('\\n#end document\\n')\n print(\"Completed saving results!\")\n\n\nclass TriadEvaluator(object):\n def __init__(self, model, test_input_gen, file_batch=10):\n self.model = model\n self.test_input_gen = test_input_gen\n self.data_q_store = multiprocessing.Queue(maxsize=5)\n\n def fast_eval(self):\n \"\"\"Fast evaluation from a subset of test files\n Scores are based on pairs only\n \"\"\"\n # assert self.data_available\n Y_true = []\n Y_pred = []\n test_data_q = next(self.test_input_gen)\n for data in test_data_q:\n if len(data) == 3:\n data = data[:2]\n for X, y in slice_data(data, 100):\n if y.shape[-1] == 3:\n y = y[:, 1:]\n pred = self.model.predict(X) # (group_size, 3)\n Y_true.append(y)\n Y_pred.append(pred)\n\n Y_true = np.concatenate(Y_true)\n Y_true = Y_true.flatten()\n Y_pred = np.concatenate(Y_pred)\n Y_pred = Y_pred.flatten()\n Y_pred = np.round(Y_pred).astype(int)\n\n return classification_report(Y_true, Y_pred, digits=3)\n\n def write_results(self, df, dest_path, n_iterations, save_dendrograms=True, clustering_only=False, compute_linkage=False):\n \"\"\"Perform evaluation on all test data, write results\"\"\"\n # assert self.data_available\n print(\"# files: %d\" % n_iterations)\n\n all_pairs_true = []\n all_pairs_pred = []\n processed_docs = set([])\n doc_ids = df.doc_id.unique()\n i = n_iterations\n t = 3.6\n method = 'average'\n criterion = 'distance'\n\n while i > 0:\n if not clustering_only:\n test_data_q = next(self.test_input_gen)\n assert len(test_data_q) == 1 # only process one file\n if not test_data_q[0]:\n i -= 1\n continue\n X, y, index_map = test_data_q[0]\n if y.shape[-1] == 3:\n y = y[:, 1:]\n\n doc_id = list(index_map.keys())[0][0] # python3 does not support keys() as a list\n\n\n if doc_id in processed_docs:\n # print(\"%s already processed before!\" % doc_id)\n time.sleep(10)\n continue\n processed_docs.add(doc_id)\n pred = []\n for X, _ in slice_data([X, y], 50): # do this to avoid very large batches\n pred.append(self.model.predict(X))\n pred = np.concatenate(pred)\n pred = np.reshape(pred, [-1, 2]) # in case there are batches\n\n true = np.reshape(y, [-1, 2])\n\n pair_results = defaultdict(list)\n pair_true = {}\n for key in index_map:\n assert key[1][0] <= key[2][0] <= key[3][0]\n pair_results[(key[2], key[3])].append(pred[index_map[key]][0]) # result of (b, c)\n if key[1] != key[2]: # handle extra triads at beginning of file\n pair_results[(key[1], key[3])].append(pred[index_map[key]][1]) # result of (a, c)\n\n pair_true[(key[2], key[3])] = true[index_map[key]][0]\n pair_true[(key[1], key[3])] = true[index_map[key]][1]\n\n # save raw scores\n pickle.dump(pair_results, open(os.path.join(dest_path, 'raw_scores', doc_id.split('/')[-1]+'results.pkl'), 'wb'))\n\n doc_df = df.loc[df.doc_id == doc_id]\n doc_df = doc_df.reset_index()\n original_doc_df = copy.copy(doc_df)\n replace_pronoun(doc_df)\n speakers = [SPEAKER_MAP.get(s, '-') for s in doc_df.speaker.unique()]\n\n pair_results_mean = {}\n for key, value in pair_results.items():\n if doc_df.iloc[key[0][0]].word == doc_df.iloc[key[1][0]].word and doc_df.iloc[key[1][0]].word in speakers:\n mean_value = 1.0 # maximum value\n else:\n mean_value = TriadEvaluator.top_n_mean(value, 0)\n pair_results_mean[key] = mean_value\n all_pairs_pred.append(mean_value)\n all_pairs_true.append(pair_true[key])\n\n locs, clusters, linkage = clustering(pair_results_mean, binarize=False, t=t, method=method)\n _, clusters_true, linkage_true = clustering(pair_true, binarize=False, t=t, method=method)\n\n clusters = TriadEvaluator.remove_singletons(clusters)\n\n else: # clustering only\n from scipy.cluster.hierarchy import inconsistent, fcluster\n doc_id = doc_ids[i - 1]\n\n doc_df = df.loc[df.doc_id == doc_id]\n doc_df = doc_df.reset_index()\n original_doc_df = copy.copy(doc_df)\n replace_pronoun(doc_df)\n speakers = [SPEAKER_MAP.get(s, '-') for s in doc_df.speaker.unique()]\n\n if doc_id.split('/')[-1] in ('wsj_2390', 'wsj_2390-0', 'cnn_0008-8'):\n print(\"file not found:\", doc_id)\n i -= 1\n continue\n\n if compute_linkage:\n pair_results = pickle.load(open(os.path.join(dest_path, 'raw_scores', doc_id.split('/')[-1]+'results.pkl'), 'rb'))\n\n pair_results_mean = {}\n for key, value in pair_results.items():\n if doc_df.iloc[key[1][0]].word in (doc_df.iloc[key[0][0]].word, doc_df.iloc[key[0][1]].word) and doc_df.iloc[key[1][0]].word in speakers:\n mean_value = 1.0 # maximum value\n else:\n mean_value = TriadEvaluator.top_n_mean(value, 0)\n pair_results_mean[key] = mean_value\n\n pair_results_mean = TriadEvaluator.attach_proper_names(pair_results_mean, doc_df)\n locs, clusters, linkage = clustering(pair_results_mean, binarize=False, t=t, method=method)\n locs, clusters, linkage = TriadEvaluator.pick_antecedent(pair_results_mean, doc_df, locs, clusters, linkage, t, method)\n\n\n else:\n save_dendrograms = False\n linkage = np.load(os.path.join(dest_path, 'linkages', doc_id.split('/')[-1] + '.npy'))\n with open(os.path.join(dest_path, 'linkages', doc_id.split('/')[-1]+'-locs.pkl'), 'rb') as f:\n locs = pickle.load(f)\n\n clusters = fcluster(linkage, criterion=criterion, depth=2, R=None, t=t)\n\n\n clusters = TriadEvaluator.remove_singletons(clusters)\n\n if save_dendrograms:\n np.save(os.path.join(dest_path, 'linkages', doc_id.split('/')[-1] + '.npy'), linkage)\n with open(os.path.join(dest_path, 'linkages', doc_id.split('/')[-1] + '-locs.pkl'), 'wb') as f:\n pickle.dump(locs, f)\n if not compute_linkage:\n np.save(os.path.join(dest_path, 'true-linkages', doc_id.split('/')[-1] + '.npy'), linkage_true)\n\n length = len(doc_df)\n # print(\"Saving %s results...\" % doc_id)\n sys.stdout.write(\"Saving results %d / %d\\r\" % (n_iterations - i + 1, n_iterations))\n sys.stdout.flush()\n corefs = ['-' for _ in range(length)]\n for loc, cluster in zip(locs, clusters):\n\n if cluster == -1: # singletons\n continue\n\n start, end = loc\n if corefs[start] == '-':\n corefs[start] = '(' + str(cluster)\n else:\n corefs[start] += '|(' + str(cluster)\n\n if corefs[end] == '-':\n corefs[end] = str(cluster) + ')'\n elif start == end:\n corefs[end] += ')'\n else:\n corefs[end] += '|' + str(cluster) + ')'\n fn = doc_id.split('/')[-1]\n if FULL_OUTPUT:\n fn += '.corenlp_conll'\n file_id = doc_df.iloc[0].file_id\n part_n = doc_id.split('-')[-1]\n if len(part_n) == 1:\n part_n = '00' + part_n\n elif len(part_n) == 2:\n part_n = '0' + part_n\n else:\n print(part_n)\n raise ValueError\n with open(os.path.join(dest_path, 'responses', fn), 'w') as f:\n f.write('#begin document (%s); part %s\\n' % (file_id, part_n))\n for loc, coref in enumerate(corefs):\n if FULL_OUTPUT:\n columns = [str(s) for s in original_doc_df.iloc[loc].values[:-1]][2:]\n f.write('\\t'.join(columns) + '\\t' + coref +'\\n')\n else:\n word = doc_df.iloc[loc].word\n f.write(doc_id + '\\t' + word + '\\t' + coref + '\\n')\n f.write('\\n#end document\\n')\n\n i -= 1\n\n print(\"Completed saving results!\")\n if not clustering_only:\n print(\"Pairwise evaluation:\")\n print(\"True histogram\", np.histogram(all_pairs_true, bins=4))\n print(\"Prediction histogram\", np.histogram(all_pairs_pred, bins=4))\n print(classification_report(all_pairs_true, np.round(all_pairs_pred), digits=3))\n\n @staticmethod\n def last_n_values(values, n):\n if len(values) >= n:\n value = np.mean(values[-n:])\n else:\n value = np.mean(values)\n return value\n\n @staticmethod\n def top_n_mean(values, n):\n if n >= 1:\n values.sort(reverse=True)\n if len(values) >= n:\n values = values[:n]\n return np.mean(values)\n\n @staticmethod\n def median(values):\n values.sort(reverse=True)\n return values[len(values)/2]\n\n @staticmethod\n def nonlinear_mean(values):\n return np.mean(np.round(values))\n\n @staticmethod\n def bottom_n_mean(values, n):\n if n >= 1:\n values.sort()\n if len(values) >= n:\n values = values[:n]\n return np.mean(values)\n\n @staticmethod\n def remove_singletons(clusters):\n counter = defaultdict(int)\n for item in clusters:\n counter[item] += 1\n for i, item in enumerate(clusters):\n if counter[item] == 1:\n clusters[i] = -1 # use -1 as a special value for singletons\n return clusters\n\n @staticmethod\n def attach_singletons(linkage, t=3.5):\n\n n = len(linkage) + 1\n clusters = np.where(linkage[:, 2] > t)[0]\n mentions = np.where(linkage[:, 0] < n)[0]\n singletons = set(clusters).intersection(set(mentions))\n for singleton in singletons:\n linkage[singleton, 2] = t - 0.1\n print(\"singletons attached\", singletons)\n\n @staticmethod\n def remove_embeds(locs, clusters):\n n = len(locs)\n for i, loc0 in enumerate(locs):\n for j in range(i + 1, n):\n loc1 = locs[j]\n if loc0[0] == loc0[1] or loc1[0] == loc1[1]: # single words likely to be pronouns. preserve them.\n continue\n if clusters[i] == clusters[j]:\n if loc0[0] <= loc1[0] and loc0[1] >= loc1[1]:\n clusters[j] = -1 # -1 will not be written in result files\n elif loc0[0] >= loc1[0] and loc0[1] <= loc1[1]:\n clusters[i] = -1\n\n return clusters\n\n @staticmethod\n def pick_antecedent(pair_results, doc_df, locs, clusters, linkage, t, method, iters=0):\n pronouns = set(['he', 'she', 'it', 'they', 'his', 'her', 'their', 'him', 'them', 'hers', 'its', 'theirs'])\n\n def are_all_pronous(locs):\n for loc in locs:\n if loc[0] != loc[1] or doc_df.iloc[loc[0]].word.lower() not in pronouns:\n return False\n return True\n\n locs = [tuple(loc) for loc in locs] # convert list to tuple\n loc2cluster = dict(zip(locs, clusters))\n cluster2locs = defaultdict(list)\n for loc, cluster in loc2cluster.items():\n cluster2locs[cluster].append(loc)\n\n all_pair_results = {}\n for k, v in pair_results.items():\n if k[0][0] <= k[1][0]:\n all_pair_results[k] = v\n\n leading_pronouns = []\n for cluster, items in cluster2locs.items():\n if are_all_pronous(items):\n leading_pronouns.append(items[0])\n if not leading_pronouns:\n assert len(locs) == len(clusters)\n return locs, clusters, linkage\n\n for loc in leading_pronouns:\n pre_candidates = [(key, all_pair_results[key]) for key in all_pair_results if key[1] == loc \\\n and key[0][0] != key[1][0]]\n post_candidates = [(key, all_pair_results[key]) for key in all_pair_results if key[0] == loc \\\n and (key[1][0] != key[1][1] or doc_df.iloc[key[1][0]].word.lower() not in pronouns) \\\n and key[0][0] != key[1][0]]\n if len(pre_candidates) > 6:\n pre_candidates = sorted(pre_candidates)[-6:]\n if len(post_candidates) > 2:\n post_candidates = sorted(post_candidates)[:2]\n candidates = pre_candidates + post_candidates\n\n if not candidates:\n continue\n match = sorted(candidates, key=lambda x: x[1])[-1][0] # loc\n cluster = loc2cluster[loc]\n other_locs = cluster2locs[cluster]\n if loc == match[0]:\n antecedent = match[1]\n else:\n antecedent = match[0]\n if iters < 4:\n for item in other_locs:\n pair_results[item, antecedent] = 1.0\n pair_results[antecedent, item] = 1.0\n else:\n antecedent_cluster = loc2cluster[antecedent]\n antecedent_locs = cluster2locs[antecedent_cluster]\n for loc1 in other_locs:\n for loc2 in antecedent_locs:\n pair_results[loc1, loc2] = 1.0\n pair_results[loc2, loc1] = 1.0\n\n print('%d recursion(s) finished in' %(iters + 1), doc_df.iloc[0].doc_id)\n\n locs, clusters, linkage = clustering(pair_results, binarize=False, t=t, method=method)\n return TriadEvaluator.pick_antecedent(pair_results, doc_df, locs, clusters, linkage, t, method, iters=iters+1)\n\n @staticmethod\n def adjust_cluster_distances(all_pair_results, locs, clusters, t, doc_id):\n def recompute_linkage(locs1, locs2):\n accumulate = 0\n count = 0\n for loc1 in locs1:\n for loc2 in locs2:\n assert loc1 != loc2\n if (loc1, loc2) in all_pair_results:\n score = all_pair_results[(loc1, loc2)]\n elif (loc1, loc2) in all_pair_results:\n score = all_pair_results[(loc2, loc1)]\n else:\n continue\n accumulate += min(10, 1/score)\n count += 1\n if count == 0:\n return t + 0.2\n return accumulate / count\n\n original_clusters = copy.copy(clusters)\n locs = [tuple(loc) for loc in locs] # convert list to tuple\n loc2cluster = dict(zip(locs, clusters))\n cluster2locs = defaultdict(list)\n for loc, cluster in loc2cluster.items():\n cluster2locs[cluster].append(loc)\n\n clusters = list(cluster2locs.keys()) # so no duplicate\n n_clusters = len(clusters)\n for i in range(n_clusters - 1):\n for j in range(i + 1, n_clusters):\n if clusters[i] in cluster2locs and clusters[j] in cluster2locs:\n locs1 = cluster2locs[clusters[i]]\n locs2 = cluster2locs[clusters[j]]\n adjusted_distance = recompute_linkage(locs1, locs2)\n if adjusted_distance < t:\n for loc in locs2:\n loc2cluster[loc] = clusters[i]\n cluster2locs[clusters[i]] += cluster2locs[clusters[j]]\n del cluster2locs[clusters[j]]\n\n new_clusters = [loc2cluster[loc] for loc in locs]\n merged = len(set(original_clusters)) - len(set(new_clusters))\n if merged:\n print(\"%d out of %d clusters merged in %s\" % (merged + 1, len(set(original_clusters)), doc_id))\n\n return new_clusters\n\n @staticmethod\n def attach_proper_names(pair_results, doc_df):\n\n def connected_components(lists):\n neighbors = defaultdict(set)\n seen = set()\n for each in lists:\n for item in each:\n neighbors[item].update(each)\n\n def component(node, neighbors=neighbors, seen=seen, see=seen.add):\n nodes = set([node])\n next_node = nodes.pop\n while nodes:\n node = next_node()\n see(node)\n nodes |= neighbors[node] - seen\n yield node\n\n for node in neighbors:\n if node not in seen:\n yield sorted(component(node))\n\n all_pair_results = copy.copy(pair_results)\n all_locs = set([])\n for key in all_pair_results:\n all_locs.add(key[0])\n all_locs.add(key[1])\n\n for key0 in all_locs:\n for key1 in all_locs:\n if key0 == key1:\n continue\n if (key0, key1) in all_pair_results:\n all_pair_results[key1, key0] = all_pair_results[key0, key1]\n elif (key1, key0) in all_pair_results:\n all_pair_results[key0, key1] = all_pair_results[key1, key0]\n else:\n all_pair_results[key0, key1] = 0.0 # just to get the pairs\n all_pair_results[key1, key0] = 0.0\n\n identicals = defaultdict(set)\n for pair in all_pair_results:\n e1, e2 = pair\n if e1[1] - e1[0] > 1 or e2[1] - e2[0] > 1:\n continue\n\n if doc_df.iloc[e1[0]].word == doc_df.iloc[e2[0]].word and re.search('(PERSON)|(ORG)', doc_df.iloc[e1[0]].name_entities):\n if e1[1] - e1[0] == e2[1] - e2[0] == 1 or (e1[1] - e1[0] == e2[1] - e2[0] == 2 and doc_df.iloc[e1[1]].word == doc_df.iloc[e2[1]].word):\n all_pair_results[pair] = 1.0\n all_pair_results[pair[1], pair[0]] = 1.0\n words = ''\n for i in range(e1[1] - e1[0] + 1):\n words += doc_df.iloc[e1[i]].word\n identicals[words].update([e1, e2])\n elif e1[1] - e1[0] + e2[1] - e2[0] > 2 and 'POS' in (doc_df.iloc[e1[1]].pos, doc_df.iloc[e2[1]].pos):\n if e1[1] - e1[0] < e2[1] - e2[0]:\n e = e1\n else:\n e = e2\n words = ''\n for i in range(e[0], e[1] + 1):\n words += doc_df.iloc[i].word\n identicals[words].update([e1, e2])\n\n elif doc_df.iloc[e1[0]].word == doc_df.iloc[e2[0]].word and all_pair_results[pair] > 0.97:\n if e1[1] - e1[0] > e2[1] - e2[0]:\n e = e1\n else:\n e = e2\n words = ''\n for i in range(e[0], e[1] + 1):\n words += doc_df.iloc[i].word\n identicals[words].update([e1, e2])\n\n # print(identicals)\n groups = [tuple(sorted(list(v))) for k, v in identicals.items()]\n\n # reduced_groups = list(connected_components(groups))\n reduced_groups = connected_components(groups)\n for locs in reduced_groups:\n n = len(locs)\n for i in range(n - 1):\n for j in range(i + 1, n):\n # print(locs[i], locs[j], all_pair_results[locs[i], locs[j]])\n all_pair_results[locs[i], locs[j]] = 1.0\n all_pair_results[locs[j], locs[i]] = 1.0\n\n\n for key in all_pair_results:\n if all_pair_results[key] != 0.0:\n pair_results[key] = all_pair_results[key]\n\n return pair_results","sub_path":"src/evaluator.py","file_name":"evaluator.py","file_ext":"py","file_size_in_byte":23518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"240311479","text":"import csv\nimport mysql.connector\nimport glob as gb\n\n# 自分のローカルのMysqlへの接続 passwdには先ほど設定したrootのパスを入力\nconnect = mysql.connector.connect(\n user='root',\n password='furuhuru8',\n host='localhost',\n database='bikesensordb',\n charset='utf8'\n)\ncursor = connect.cursor()\n\n'''\n#テーブルの作成(今回項目列名は下記で読み込むCSVの項目別変数と同一のものを使用している)\ncursor.execute('CREATE TABLE raspberrypi_sensor (\\\n Time datetime PRIMARY KEY,\\\n Temperature double,\\\n CpuTemp double,\\\n Humidity double,\\\n Pressure double,\\\n R_Pitch double,\\\n R_Roll double,\\\n R_Yaw double,\\\n R_Acc_X double,\\\n R_Acc_Y double,\\\n R_Acc_Z double,\\\n R_Com_X double,\\\n R_Com_Y double,\\\n R_Com_Z double,\\\n North double);'\n)\n'''\n\n# csvファイルのパス指定\n# path= '../RaspberryPi/*.csv'\n# path = '../RaspberryPi/BatteryData/landYes/unfinished/*csv'\n# path = '../RaspberryPi/BatteryData/landNo/unfinished/*csv'\n# path = '../RaspberryPi/gpsData/unfinished/*csv'\n# path = '../RaspberryPi/WindData/unfinished/*csv'\npath = '../RaspberryPi/youmeData/unfinished/*csv'\nfilenames = sorted(gb.glob(path))\n# print(filenames)\n\n# 何のデータかの情報\n# type_status = 'normal' # 正常\n# type_status = 'battery_landyes' # 異常:バッテリー切れ、着陸あり\n# type_status = 'battery_landno' # 異常:バッテリー切れ、着陸なし\n# type_status = 'gps_accuracy' # 異常:GPS精度誤差(経路外小)\n# type_status = 'wind_accuracy' # 異常:風誤差(経路外大)\ntype_status = 'youme' # 異常:ゆめタウン(経路外極大)\n\nfor fn in filenames:\n with open(fn) as infile:\n count = 0\n for line in infile:\n if count > 0:\n # 読み込んだ行の項目を順にカンマ区切りで対応する変数へ文字列としてmapする。\n Time, Temperature, CpuTemp, Humidity, Pressure, Pitch, Roll, Yaw, Acc_X, Acc_Y, Acc_Z, Com_X, Com_Y, Com_Z, North = map(str, line.split(','))\n # print(fn, count, North)\n # 何のデータかのカラム\n Type = type_status\n # MySQLDBへの格納出力(insert)。上記で読み込んで保持している変数の値をformatで突っ込むので、valuesの{}側をエスケープ\\とシングルクオーテーション'で囲んでおく。\n cursor.execute('INSERT INTO raspberrypi_sensor \\\n values(\\'{}\\',{},{},{},{},{},{},{},{},{},{},{},{},{},{},\\'{}\\');'\n .format(Time, Temperature, CpuTemp, Humidity, Pressure, Pitch, Roll, Yaw, Acc_X, Acc_Y, Acc_Z, Com_X, Com_Y, Com_Z, North, Type))\n # コンソール出力\n print(u\"{} に取得したCSVファイルの {} 列目を処理中\".format(fn,count))\n count = count + 1\n # 項目名列は処理対象の行としてカウントしない\n count = count - 1\n print(u'{} は {} 件を処理しました'.format(fn, count))\n\n# DB操作の終了。\n# insert処置後のcommitも。\ncursor.close()\nconnect.commit()\nconnect.close()","sub_path":"R_db_writer.py","file_name":"R_db_writer.py","file_ext":"py","file_size_in_byte":3215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"624285660","text":"import os\n\nSCRIPT_PATH = os.path.dirname(os.path.realpath(__file__))\nPLAYBOOK_DIR = os.path.join(SCRIPT_PATH, '..', 'provision_profiles')\nROLES_DIR = os.path.join(PLAYBOOK_DIR, 'roles')\n\n\ndef get_roles():\n roles = []\n for folder in os.listdir(ROLES_DIR):\n if os.path.isdir('{}/{}'.format(ROLES_DIR, folder)):\n\n # Need to disable this role as 'includes' do not\n # work with syntax checks.\n if not folder == 'prometheus_node_exporter':\n roles.append(folder)\n return roles\n\n\ndef build_file(roles):\n playbook = \"- name: All roles\\n hosts: all\\n roles:\\n\"\n for role in roles:\n playbook += \" - {}\\n\".format(role)\n return playbook\n\n\ndef main():\n roles = get_roles()\n playbook = build_file(roles)\n with open('{}/all.yml'.format(PLAYBOOK_DIR), 'w') as f:\n f.write(playbook)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"bin/generate_tests_playbook.py","file_name":"generate_tests_playbook.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"523271857","text":"import unittest\nfrom Include.MatrixNP import *\nfrom Include.Tuple import *\n\nclass TestMatrix(unittest.TestCase):\n def test_Matrix_constructAndInspectFourByFourMatrix(self):\n self.list = [ 1, 2, 3, 4, 5.5, 6.5, 7.5, 8.5, 9, 10, 11, 12, 13.5, 14.5, 15.5, 16.5 ]\n self.M = Matrix4()\n\n self.index = 0\n for x in range(self.M.length):\n for y in range(self.M.length):\n self.M.m[x][y] = self.list[self.index]\n self.index += 1\n\n self.assertEqual(self.M.m[0][0], 1)\n self.assertEqual(self.M.m[0][3], 4)\n self.assertEqual(self.M.m[1][0], 5.5)\n self.assertEqual(self.M.m[1][2], 7.5)\n self.assertEqual(self.M.m[2][2], 11)\n self.assertEqual(self.M.m[3][0], 13.5)\n self.assertEqual(self.M.m[3][2], 15.5)\n\n def test_Matrix_representTwoByTwo(self):\n self.list = [-3, 5, 1, -2]\n self.M = Matrix2()\n\n self.index = 0\n for x in range(self.M.length):\n for y in range(self.M.length):\n self.M.m[x][y] = self.list[self.index]\n self.index += 1\n\n self.assertEqual(self.M.m[0][0], -3)\n self.assertEqual(self.M.m[0][1], 5)\n self.assertEqual(self.M.m[1][0], 1)\n self.assertEqual(self.M.m[1][1], -2)\n\n def test_Matrix_representThreeByThree(self):\n self.list = [-3, 5, 0, 1, -2, -7, 0, 1, 1]\n self.M = Matrix3()\n\n self.index = 0\n for x in range(self.M.length):\n for y in range(self.M.length):\n self.M.m[x][y] = self.list[self.index]\n self.index += 1\n\n self.assertEqual(self.M.m[0][0], -3)\n self.assertEqual(self.M.m[1][1], -2)\n self.assertEqual(self.M.m[2][2], 1)\n\n def test_Matrix_equalityWithIdenticalMatrices(self):\n self.list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2]\n self.A = Matrix4()\n self.B = Matrix4()\n\n self.index = 0\n for x in range(self.A.length):\n for y in range(self.A.length):\n self.A.m[x][y] = self.list[self.index]\n self.B.m[x][y] = self.list[self.index]\n self.index += 1\n\n self.assertEqual(self.A, self.B)\n\n def test_Matrix_equalityWithDifferentMatrices(self):\n self.list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2]\n self.list2 = [2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1]\n self.A = Matrix4()\n self.B = Matrix4()\n\n self.index = 0\n for x in range(self.A.length):\n for y in range(self.A.length):\n self.A.m[x][y] = self.list1[self.index]\n self.B.m[x][y] = self.list2[self.index]\n self.index += 1\n\n self.assertNotEqual(self.A, self.B)\n\n def test_Matrix_multiplyingTwoMatrices(self):\n self.list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 2]\n self.list2 = [-2, 1, 2, 3, 3, 2, 1, -1, 4, 3, 6, 5, 1, 2, 7, 8]\n self.resultList = [20, 22, 50, 48, 44, 54, 114, 108, 40, 58, 110, 102, 16, 26, 46, 42]\n\n self.A = Matrix4()\n self.B = Matrix4()\n\n self.index = 0\n for x in range(self.A.length):\n for y in range(self.A.length):\n self.A.m[x][y] = self.list1[self.index]\n self.B.m[x][y] = self.list2[self.index]\n self.index += 1\n self.index = 0\n self.result = self.A * self.B\n\n for x in range(self.result.length):\n for y in range(self.result.length):\n self.assertEqual(self.result.m[x][y], self.resultList[self.index])\n self.index += 1\n\n def test_Matrix_multiplyMatrixByTuple(self):\n self.list1 = [1, 2, 3, 4, 2, 4, 4, 2, 8, 6, 4, 1, 0, 0, 0, 1]\n self.A = Matrix4()\n self.T = Tuple(1, 2, 3, 1)\n\n self.index = 0\n for x in range(self.A.length):\n for y in range(self.A.length):\n self.A.m[x][y] = self.list1[self.index]\n self.index += 1\n\n self.result = self.A * self.T\n self.assertEqual(self.result, Tuple(18, 24, 33, 1))\n\n def test_Matrix_multiplyingMatrixByIdentityMatrix(self):\n self.list = [0, 1, 2, 4, 1, 2, 4, 8, 2, 4, 8, 16, 4, 8, 16, 32]\n self.A = Matrix4()\n\n self.index = 0\n for x in range(self.A.length):\n for y in range(self.A.length):\n self.A.m[x][y] = self.list[self.index]\n self.index += 1\n\n self.result = self.A * Matrix4.identity_matrix()\n self.assertEqual(self.result, self.A)\n\n def test_Matrix_multiplyingTupleByIdentityMatrix(self):\n a = Tuple(1, 2, 3, 4)\n self.result = Matrix4.identity_matrix() * a\n self.assertEqual(self.result, a)\n\n def test_Matrix_transposeAMatrix(self):\n self.list = [0, 9, 3, 0, 9, 8, 0, 8, 1, 8, 5, 3, 0, 0, 5, 8]\n self.resultList = [0, 9, 1, 0, 9, 8, 8, 0, 3, 0, 5, 5, 0, 8, 3, 8]\n self.A = Matrix4()\n self.B = Matrix4()\n\n self.index = 0\n for x in range(self.A.length):\n for y in range(self.A.length):\n self.A.m[x][y] = self.list[self.index]\n self.B.m[x][y] = self.resultList[self.index]\n self.index += 1\n\n self.result = self.A.transpose()\n self.assertEqual(self.result, self.B)\n\n def test_Matrix_transposeIdentityMatrix(self):\n self.A = Matrix4.identity_matrix().transpose()\n self.assertEqual(self.A, Matrix4.identity_matrix())\n\n def test_Matrix_calculateTheDeterminantOfATwoByTwoMatrix(self):\n self.list = [1, 5, -3, 2]\n self.A = Matrix2()\n\n self.index = 0\n for x in range(self.A.length):\n for y in range(self.A.length):\n self.A.m[x][y] = self.list[self.index]\n self.index += 1\n\n self.result = self.A.determinant()\n self.assertEqual(self.result, 17)\n\n def test_Matrix_createSubmatrixOfAThreeByThreeMatrix(self):\n self.list = [1, 5, 0, -3, 2, 7, 0, 6, -3]\n self.resultList = [-3, 2, 0, 6]\n self.A = Matrix3()\n self.B = Matrix2()\n\n self.index = 0\n for x in range(self.A.length):\n for y in range(self.A.length):\n self.A.m[x][y] = self.list[self.index]\n self.index += 1\n self.index = 0\n for x in range(self.B.length):\n for y in range(self.B.length):\n self.B.m[x][y] = self.resultList[self.index]\n self.index += 1\n\n self.result = self.A.submatrix(0, 2)\n self.assertEqual(self.result, self.B)\n\n def test_Matrix_createSubmatrixOfAFourByFourMatrix(self):\n self.list = [-6, 1, 1, 6, -8, 5, 8, 6, -1, 0, 8, 2, -7, 1, -1, 1]\n self.resultList = [-6, 1, 6, -8, 8, 6, -7, -1, 1]\n\n self.A = Matrix4()\n self.B = Matrix3()\n\n self.index = 0\n for x in range(self.A.length):\n for y in range(self.A.length):\n self.A.m[x][y] = self.list[self.index]\n self.index += 1\n self.index = 0\n for x in range(self.B.length):\n for y in range(self.B.length):\n self.B.m[x][y] = self.resultList[self.index]\n self.index += 1\n\n self.result = self.A.submatrix(2, 1)\n self.assertEqual(self.result, self.B)\n\n def test_Matrix_calculateAMinorOfAThreeByThreeMatrix(self):\n self.list = [3, 5, 0, 2, -1, -7, 6, -1, 5]\n self.A = Matrix3()\n\n self.index = 0\n for x in range(self.A.length):\n for y in range(self.A.length):\n self.A.m[x][y] = self.list[self.index]\n self.index += 1\n\n self.B = self.A.submatrix(1, 0)\n\n self.assertEqual(self.B.determinant(), 25)\n self.assertEqual(self.A.minor(1, 0), 25)\n\n def test_Matrix_calculateCofactorOfThreeByThreeMatrix(self):\n self.list = [3, 5, 0, 2, -1, -7, 6, -1, 5]\n self.A = Matrix3()\n\n self.index = 0\n for x in range(self.A.length):\n for y in range(self.A.length):\n self.A.m[x][y] = self.list[self.index]\n self.index += 1\n\n self.assertEqual(self.A.minor(0, 0), -12)\n self.assertEqual(self.A.cofactor(0, 0), -12)\n self.assertEqual(self.A.minor(1, 0), 25)\n self.assertEqual(self.A.cofactor(1, 0), -25)\n\n def test_Matrix_calculateTheDeterminantOfAThreeByThreeMatrix(self):\n self.list = [1, 2, 6, -5, 8, -4, 2, 6, 4]\n self.A = Matrix3()\n\n self.index = 0\n for x in range(self.A.length):\n for y in range(self.A.length):\n self.A.m[x][y] = self.list[self.index]\n self.index += 1\n\n self.assertEqual(self.A.cofactor(0, 0), 56)\n self.assertEqual(self.A.cofactor(0, 1), 12)\n self.assertEqual(self.A.minor(0, 2), -46)\n self.assertEqual(self.A.determinant(), -196)\n\n def test_Matrix_calculateTheDeterminantOfAFourByFourMatrix(self):\n self.list = [-2, -8, 3, 5, -3, 1, 7, 3, 1, 2, -9, 6, -6, 7, 7, -9]\n self.A = Matrix4()\n\n self.index = 0\n for x in range(self.A.length):\n for y in range(self.A.length):\n self.A.m[x][y] = self.list[self.index]\n self.index += 1\n\n self.assertEqual(self.A.cofactor(0, 0), 690)\n self.assertEqual(self.A.cofactor(0, 1), 447)\n self.assertEqual(self.A.cofactor(0, 2), 210)\n self.assertEqual(self.A.cofactor(0, 3), 51)\n self.assertEqual(self.A.determinant(), -4071)\n\n def test_Matrix_testInvertibleMatrixForInvertibility(self):\n self.list = [6, 4, 4, 4, 5, 5, 7, 6, 4, -9, 3, -7, 9, 1, 7, -6]\n self.A = Matrix4()\n\n self.index = 0\n for x in range(self.A.length):\n for y in range(self.A.length):\n self.A.m[x][y] = self.list[self.index]\n self.index += 1\n\n self.assertEqual(self.A.determinant(), -2120)\n self.assertEqual(self.A.invertible(), True)\n\n def test_Matrix_testNonInvertibleMatrixForInvertibility(self):\n self.list = [-4, 2, -2, -3, 9, 6, 2, 6, 0, -5, 1, -5, 0, 0, 0, 0]\n self.A = Matrix4()\n\n self.index = 0\n for x in range(self.A.length):\n for y in range(self.A.length):\n self.A.m[x][y] = self.list[self.index]\n self.index += 1\n\n self.assertEqual(self.A.determinant(), 0)\n self.assertEqual(self.A.invertible(), False)\n\n def test_Matrix_calculateInverseOfAMatrix(self):\n self.list = [-5, 2, 6, -8, 1, -5, 1, 8, 7, 7, -6, -7, 1, -3, 7, 4]\n self.resultList = [0.21805, 0.45113, 0.24060, -0.04511, -0.80827, -1.45677, -0.44361, 0.52068, -0.07895, -0.22368, -0.05263, 0.19737, -0.52256, -0.81391, -0.30075, 0.30639]\n self.A = Matrix4()\n self.result = Matrix4()\n\n self.index = 0\n for x in range(self.A.length):\n for y in range(self.A.length):\n self.A.m[x][y] = self.list[self.index]\n self.result.m[x][y] = self.resultList[self.index]\n self.index += 1\n self.B = self.A.invert()\n\n self.assertEqual(self.A.determinant(), 532)\n self.assertEqual(self.A.cofactor(2, 3), -160)\n self.assertAlmostEqual(self.B.m[3][2], -160/532)\n self.assertEqual(self.A.cofactor(3, 2), 105)\n self.assertAlmostEqual(self.B.m[2][3], 105/532)\n\n for x in range(self.A.length):\n for y in range(self.A.length):\n self.assertAlmostEqual(self.B.m[x][y], self.result.m[x][y], 5)\n\n def test_Matrix_calculateTheInverseOfAnotherMatrix(self):\n self.list = [8, -5, 9, 2, 7, 5, 6, 1, -6, 0, 9, 6, -3, 0, -9, -4]\n self.resultList = [-0.15385, -0.15385, -0.28205, -0.53846, -0.07692, 0.12308, 0.02564, 0.03077, 0.35897, 0.35897, 0.43590, 0.92308, -0.69231, -0.69231, -0.76923, -1.92308]\n self.A = Matrix4()\n self.result = Matrix4()\n\n self.index = 0\n for x in range(self.A.length):\n for y in range(self.A.length):\n self.A.m[x][y] = self.list[self.index]\n self.result.m[x][y] = self.resultList[self.index]\n self.index += 1\n self.B = self.A.invert()\n\n for x in range(self.A.length):\n for y in range(self.A.length):\n self.assertAlmostEqual(self.B.m[x][y], self.result.m[x][y], 5)\n\n def test_Matrix_calculateTheInverseOfAThirdMatrix(self):\n self.list = [9, 3, 0, 9, -5, -2, -6, -3, -4, 9, 6, 4, -7, 6, 6, 2]\n self.resultList = [-0.04074, -0.07778, 0.14444, -0.22222, -0.07778, 0.03333, 0.36667, -0.33333, -0.02901, -0.14630, -0.10926, 0.12963, 0.17778, 0.06667, -0.26667, 0.33333]\n self.A = Matrix4()\n self.result = Matrix4()\n\n self.index = 0\n for x in range(self.A.length):\n for y in range(self.A.length):\n self.A.m[x][y] = self.list[self.index]\n self.result.m[x][y] = self.resultList[self.index]\n self.index += 1\n self.B = self.A.invert()\n\n self.assertEqual(self.B, self.result)\n\n def test_Matrix_multiplyAProductByItsInverse(self):\n self.list1 = [3, -9, 7, 3, 3, -8, 2, -9, -4, 4, 4, 1, -6, 5, -1, 1]\n self.list2 = [8, 2, 2, 2, 3, -1, 7, 0, 7, 0, 5, 4, 6, -2, 0, 5]\n\n self.A = Matrix4()\n self.B = Matrix4()\n\n self.index = 0\n for x in range(self.A.length):\n for y in range(self.A.length):\n self.A.m[x][y] = self.list1[self.index]\n self.B.m[x][y] = self.list2[self.index]\n self.index += 1\n self.C = self.A * self.B\n\n self.result = self.C * self.B.invert()\n self.assertEqual(self.result, self.A)\n\nclass TestMatrixTransformations(unittest.TestCase):\n def test_Matrix_multiplyByATranslationMatrix(self):\n self.transform = Matrix4.identity_matrix().translate(5, -3, 2)\n self.p = point(-3, 4, 5)\n\n self.result = self.transform * self.p\n self.assertEqual(self.result, point(2, 1, 7))\n\n def test_Matrix_multiplyByTheInverseOfATranslationMatrix(self):\n self.transform = Matrix4.identity_matrix().translate(5, -3, 2)\n self.inv = self.transform.invert()\n self.p = point(-3, 4, 5)\n\n self.result = self.inv * self.p\n self.assertEqual(self.result, point(-8, 7, 3))\n\n def test_Matrix_translationDoesNotAffectVectors(self):\n self.transform = Matrix4.identity_matrix().translate(5, -3, 2)\n self.v = vector(-3, 4, 5)\n\n self.result = self.transform * self.v\n self.assertEqual(self.result, self.v)\n\n def test_Matrix_scalingMatrixAppliedToAPoint(self):\n self.transform = Matrix4.identity_matrix().scale(2, 3, 4)\n self.p = point(-4, 6, 8)\n\n self.result = self.transform * self.p\n self.assertEqual(self.result, point(-8, 18, 32))\n\n def test_Matrix_scalingMatrixAppliedToAVector(self):\n self.transform = Matrix4.identity_matrix().scale(2, 3, 4)\n self.v = vector(-4, 6, 8)\n\n self.result = self.transform * self.v\n self.assertEqual(self.result, vector(-8, 18, 32))\n\n def test_Matrix_multiplyByTheInverseOfAScalingMatrix(self):\n self.transform = Matrix4.identity_matrix().scale(2, 3, 4)\n self.inv = self.transform.invert()\n self.v = vector(-4, 6, 8)\n\n self.result = self.inv * self.v\n self.assertEqual(self.result, vector(-2, 2, 2))\n\n def test_Matrix_reflectionIsScalingByANegativeValue(self):\n self.transform = Matrix4.identity_matrix().scale(-1, 1, 1)\n self.p = point(2, 3, 4)\n\n self.result = self.transform * self.p\n self.assertEqual(self.result, point(-2, 3, 4))\n\n def test_Matrix_rotatingAPointAroundTheXAxis(self):\n self.p = point(0, 1, 0)\n self.half_quarter = Matrix4.identity_matrix().rotate_x(math.pi / 4)\n self.full_quarter = Matrix4.identity_matrix().rotate_x(math.pi / 2)\n\n self.assertEqual(self.half_quarter * self.p, point(0, math.sqrt(2)/2, math.sqrt(2)/2))\n self.assertEqual(self.full_quarter * self.p, point(0, 0, 1))\n\n def test_Matrix_theInverseOfAnXRotationRotatesInTheOppositeDirection(self):\n self.p = point(0, 1, 0)\n self.half_quarter = Matrix4.identity_matrix().rotate_x(math.pi / 4)\n\n self.inv = self.half_quarter.invert()\n self.assertEqual(self.inv * self.p, point(0, math.sqrt(2)/2, -math.sqrt(2)/2))\n\n def test_Matrix_rotatingAPointAroundTheYAxis(self):\n self.p = point(0, 0, 1)\n self.half_quarter = Matrix4.identity_matrix().rotate_y(math.pi / 4)\n self.full_quarter = Matrix4.identity_matrix().rotate_y(math.pi / 2)\n\n self.assertEqual(self.half_quarter * self.p, point(math.sqrt(2) / 2, 0, math.sqrt(2) / 2))\n self.assertEqual(self.full_quarter * self.p, point(1, 0, 0))\n\n def test_Matrix_rotatingAPointAroundTheZAxis(self):\n self.p = point(0, 1, 0)\n self.half_quarter = Matrix4.identity_matrix().rotate_z(math.pi / 4)\n self.full_quarter = Matrix4.identity_matrix().rotate_z(math.pi / 2)\n\n self.assertEqual(self.half_quarter * self.p, point(-math.sqrt(2) / 2, math.sqrt(2) / 2, 0))\n self.assertEqual(self.full_quarter * self.p, point(-1, 0, 0))\n\n def test_Matrix_shearingTransformationMovesXInProportionToY(self):\n self.transform = Matrix4.identity_matrix().shear(1, 0, 0, 0, 0, 0)\n self.p = point(2, 3, 4)\n self.assertEqual(self.transform * self.p, point(5, 3, 4))\n\n def test_Matrix_shearingTransformationMovesXInProportionToZ(self):\n self.transform = Matrix4.identity_matrix().shear(0, 1, 0, 0, 0, 0)\n self.p = point(2, 3, 4)\n self.assertEqual(self.transform * self.p, point(6, 3, 4))\n\n def test_Matrix_shearingTransformationMovesYInProportionToX(self):\n self.transform = Matrix4.identity_matrix().shear(0, 0, 1, 0, 0, 0)\n self.p = point(2, 3, 4)\n self.assertEqual(self.transform * self.p, point(2, 5, 4))\n\n def test_Matrix_shearingTransformationMovesYInProportionToZ(self):\n self.transform = Matrix4.identity_matrix().shear(0, 0, 0, 1, 0, 0)\n self.p = point(2, 3, 4)\n self.assertEqual(self.transform * self.p, point(2, 7, 4))\n\n def test_Matrix_shearingTransformationMovesZInProportionToX(self):\n self.transform = Matrix4.identity_matrix().shear(0, 0, 0, 0, 1, 0)\n self.p = point(2, 3, 4)\n self.assertEqual(self.transform * self.p, point(2, 3, 6))\n\n def test_Matrix_shearingTransformationMovesZInProportionToY(self):\n self.transform = Matrix4.identity_matrix().shear(0, 0, 0, 0, 0, 1)\n self.p = point(2, 3, 4)\n self.assertEqual(self.transform * self.p, point(2, 3, 7))\n\n def test_Matrix_individualTransformationsAreSuppliedInSequence(self):\n self.p = point(1, 0, 1)\n self.A = Matrix4.identity_matrix().rotate_x(math.pi / 2)\n self.B = Matrix4.identity_matrix().scale(5, 5, 5)\n self.C = Matrix4.identity_matrix().translate(10, 5, 7)\n\n self.p2 = self.A * self.p\n self.assertEqual(self.p2, point(1, -1, 0))\n\n self.p3 = self.B * self.p2\n self.assertEqual(self.p3, point(5, -5, 0))\n\n self.p4 = self.C * self.p3\n self.assertEqual(self.p4, point(15, 0, 7))\n\n def test_Matrix_chainedTransformationsMustBeAppliedInReverseOrder(self):\n self.p = point(1, 0, 1)\n self.A = Matrix4.identity_matrix().rotate_x(math.pi / 2)\n self.B = Matrix4.identity_matrix().scale(5, 5, 5)\n self.C = Matrix4.identity_matrix().translate(10, 5, 7)\n\n self.T = self.C * self.B * self.A\n self.assertEqual(self.T * self.p, point(15, 0, 7))\n\n def test_Matrix_chainedTransformationsInOneLine(self):\n self.transform = Matrix4.identity_matrix().rotate_x(math.pi / 2).scale(5, 5, 5).translate(10, 5, 7)\n self.p = point(1, 0, 1)\n\n self.assertEqual(self.transform * self.p, point(15, 0, 7))\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"venv/Tests/MatrixNPTest.py","file_name":"MatrixNPTest.py","file_ext":"py","file_size_in_byte":20007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"352295595","text":"from clarity_ext.domain.validation import ValidationType, UsageError\n\n\nclass ValidationService:\n\n def __init__(self, step_logger_service, logger=None):\n self.logger = logger\n self.step_logger_service = step_logger_service\n self.warning_count = 0\n self.error_count = 0\n\n def handle_validation(self, results):\n \"\"\"\n Pushes validation results to the logging framework\n \"\"\"\n if len(results) > 0:\n self._log_debug(\"Validation errors, len = {}\".format(len(results)))\n for result in results:\n self.handle_single_validation(result)\n # If any of the validation results were errors, raise an exception:\n if any(result for result in results if result.type == ValidationType.ERROR):\n raise UsageError(\"Errors during validation. See the step log for further details.\", results)\n\n def handle_single_validation(self, result):\n msg_row = \"{}\".format(result)\n self.step_logger_service.log(msg_row)\n self._log_debug(\"{}\".format(msg_row))\n\n if result.type == ValidationType.ERROR:\n self.error_count += 1\n if result.type == ValidationType.WARNING:\n self.warning_count += 1\n\n def _log_debug(self, msg):\n if self.logger is not None:\n self.logger.debug(msg)\n","sub_path":"clarity_ext/service/validation_service.py","file_name":"validation_service.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"606052118","text":"import pytest\nfrom tetrad_analysis import dataframe_functions as ddf\nimport os\nimport pandas as pd\nimport numpy as np\nfrom pathlib import Path\nfrom pandas import DataFrame\n\n\n#create sample excel document for performing tests\nSAMPLE_XLSX = Path(__file__).parent/ \"data\"/\"python_test_list.xlsx\"\nSAMPLE_DF_TAIL = pd.DataFrame(\n data={\n \"Plate\": [1,1,1],\n \"Tetrad\":[12,12,12],\n \"spore\":[\"12B\",\"12C\",\"12D\"],\n \"viability\":[1,1,1],\n \"NAT\": [0,1,0],\n \"HYG\": [0,1,0],\n \"URA\": [0,1,0],\n }\n )\nCOL = \"URA\" \n\n#test read_excel_file() to see if it reads the input correctly\ndef test_read_excel_file():\n \n expected_tail = SAMPLE_DF_TAIL.set_index(\"Plate\") \n result = ddf.read_excel_file(SAMPLE_XLSX) \n \n assert result.tail(3) == expected_tail\n \n\n \n \n#test sort_and_filter_by_col() to make sure it sorts input data by correct col and positive values \ndef test_sort_and_filter_by_col():\n \n expected_df = SAMPLE_DF_TAIL.set_index(\"Plate\")\n\n\n expected_df_sorted = expected_df.sort_values([\"URA\"], ascending = False)\n \n #test for isolating positive values:\n \n expected_pos_vals = expected_df_sorted[expected_df_sorted[COL]>0]\n expected_df_filtered = pd.DataFrame(expected_pos_vals)\n\n \n result = ddf.sort_and_filter_by_col(expected_df,expected_df[\"URA\"])\n \n assert result == expected_df_filtered\n \n \n \n \n \n\n#test combine_antibiotics() to see if it combines all positive values of col into one dictionary\ndef test_combine_antibiotics():\n \n expected_df = ddf.read_excel_file(SAMPLE_XLSX)\n markers = ['NAT','HYG','URA']\n \n \n expected_all_positive = {}\n for marker in markers:\n expected_marker = ddf.sort_and_filter_by_col(expected_df,marker)\n expected_all_positive[marker + '_plus'] = expected_marker\n return expected_all_positive\n \n result = ddf.combine_antibiotics(expected_df,markers)\n \n assert result == expected_all_positive\n \n \n \n \n#tests write_marker_dict_to_disk() to see if it creates a new excel doucment for the newly created library\ndef test_write_marker_dict_to_disk():\n \n\n file_out = \"test.xlsx\"\n marker = \"URA\"\n \n writer = pd.ExcelWriter(file_out, engine='xlsxwriter')\n anti_bs = {\"a\": pd.DataFrame({\"Plate\": [1,1,1], \"Tetrad\":[12,12,12],})}\n for sheet_name in anti_bs.keys():\n anti_bs[sheet_name].to_excel(writer, sheet_name=sheet_name, index=False)\n expected_result = writer.save\n \n result = ddf.write_marker_dict_to_disk(marker=[anti_bs,file_out])\n \n assert result == expected_result\n\n \n \n \n#tests test_antibiotic_analysis() to see if it sorts the data within the new excel document before the document is sent out\ndef test_antibiotic_analysis():\n \n file_out = \"test.xlsx\"\n markers = ['NAT','HYG','URA']\n expected_df = ddf.read_excel_file(SAMPLE_XLSX)\n \n expected_df_tetrad = ddf.read_excel_file(SAMPLE_XLSX)\n expected_output_dict = ddf.combine_antibiotics(expected_df_tetrad, markers)\n expected_result = ddf.writer_marker_dict_to_disk(expected_output_dict,file_out)\n \n result = ddf.antibiotic_analysis(SAMPLE_XLSX,file_out=\"Antibiotic_markers.xlsx\",markers=markers)\n \n assert result == expected_result\n \n\n \n#for testing\nif __name__=='__main__':\n test_read_excel_file()\n test_sort_and_filter_by_col()\n test_combine_antibiotics()\n test_write_marker_dict_to_disk()\n test_antibiotic_analysis()","sub_path":"tests/test_tetrad_analysis.py","file_name":"test_tetrad_analysis.py","file_ext":"py","file_size_in_byte":3545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"342467056","text":"from tkinter import *\r\n\r\n\r\nclass Nota_fiscal(Toplevel):\r\n def __init__(self, parent, control):\r\n super().__init__(parent)\r\n self.control = control\r\n self.title('Nota de Venda')\r\n self.geometry('400x400+200+200')\r\n self.transient(parent)\r\n self.grab_set()\r\n\r\n file = open('nota_fiscal.txt', 'r')\r\n self.text = Text(self, width=50, height=20)\r\n self.text.insert('1.0', file.read())\r\n self.text.grid(row=0, column=0)\r\n\r\n Button(self, text='Fechar Janela', command=super().destroy).grid(row=2, column=0, pady=25)","sub_path":"nota_fiscal.py","file_name":"nota_fiscal.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"142372997","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom message_text import *\nimport os\n\ndef start_menu(user,text):\n\t#print(user,text)\n\t#print(\"len\",len(text))\n\ttry:\n\t\tif text[0] == \"!\":\n\t\t\tif text[1:7] == u\"помошь\":\n\t\t\t\treturn HELP_MESSAGE\n\t\t\telif text[1:5] == u\"цены\":\n\t\t\t\treturn PRICE_MESSAGE\n\t\t\telif text[1:6] == u\"оботе\":\n\t\t\t\treturn ABOUT_MESSAGE\n#\t\t\telif text[1:6] == \"whois\":\n#\t\t\t\tprint(os.execv(\"/usr/bin/whois\",text[7:len(text)]))\n\t#\t\t\treturn \"help_msg\"\n\t\t\telif text[1:8] == u\"справка\":\n\t\t\t\treturn INFO_MESSAGE\n\t#\t\telif text[1:6] == \"about\":\n\t#\t\t\treturn \"help_msg\"\n\t\t\telse :\n\t\t\t\treturn EROR_MESSAGE\n\t\telse :\n\t\t\treturn text\n\texcept:\n\t\tprint(user,text)\n\n\nif __name__ == '__main__':\n\twhile 1==1:\n\t\ttext = input(\"ввод: \")\n\t\tprint(parse_cmd(text))","sub_path":"comand_parser.py","file_name":"comand_parser.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"35241645","text":"def thirdMax(nums):\n \"\"\"\n without using sort or set\n :type nums: List[int]\n :rtype: int\n \"\"\"\n n = len(nums)\n max_1 = nums[0]\n for i in range(1, n):\n max_1 = max(max_1, nums[i])\n if n < 3:\n return max_1\n flag = False\n for i in range(n):\n if nums[i] < max_1 and not flag:\n max_2 = nums[i]\n flag = True\n if nums[i] < max_1 and nums[i] > max_2:\n max_2 = nums[i]\n if not flag:\n return max_1\n flag = False\n for i in range(n):\n if nums[i] < max_2 and not flag:\n max_3 = nums[i]\n flag = True\n if nums[i] < max_2 and nums[i] > max_3:\n max_3 = nums[i]\n if not flag:\n return max_1\n return max_3","sub_path":"LeetCode/ThirdMaximumNumber.py","file_name":"ThirdMaximumNumber.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"409150086","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\n@File : haa.py\n@Author: 姚宁\n@Date : 2021/5/24 23:31\n@Desc : \n'''\ndef minzi(merchant_id,total_fee,service):\n service_type=service\n total_fee2=total_fee\n mch_id=merchant_id\n return mch_id,total_fee2,service_type\n\n\n","sub_path":"Pay_request/haa.py","file_name":"haa.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"169078778","text":"# AQICN.org (Air Quality Open Data Platform) - a provider of AQI througout a world (an alternative /a fallback/ for Airly which is more popular in Central Europe)\n\nfrom acquire import Acquire\n\nimport logging\nimport requests\nfrom collections import namedtuple\n\n\nAqicnTuple = namedtuple('Aqicn', ['provider', 'pm25', 'pm10', 'humidity', 'pressure', 'temperature', 'aqi', 'level', 'advice'])\n\n\nclass Aqicn(Acquire):\n\n\n DEFAULT = AqicnTuple(provider='AQICN', pm25=-1, pm10=-1, pressure=-1, humidity=-1, temperature=None, aqi=-1, level='n/a', advice='n/a')\n\n\n def __init__(self, key, lat, lon, city_or_id, cache_ttl):\n self.key = key\n self.lat = lat\n self.lon = lon\n self.city_or_id = city_or_id\n self.cache_ttl = cache_ttl\n\n\n def cache_name(self):\n return \"aqicn.json\"\n\n\n def ttl(self):\n return self.cache_ttl\n\n\n def acquire(self):\n logging.info(\"Getting a Aqicn status from the internet...\")\n\n try:\n r = requests.get(\n \"https://api.waqi.info/feed/{}/?token={}\".format(\n self.city_or_id if self.city_or_id else \"geo:{};{}\".format(self.lat, self.lon),\n self.key\n )\n )\n return r.status_code, r.text\n except Exception as e:\n logging.exception(e)\n\n return (None, None)\n\n\n def get(self):\n try:\n aqicn_data = self.load()\n if aqicn_data is None or aqicn_data[\"status\"] != 'ok' or 'data' not in aqicn_data or 'iaqi' not in aqicn_data[\"data\"]:\n logging.warn(\"No reasonable data returned by Aqicn. Check API key (status code) or whether the given city/id/lon&lat is known and handled by the service (visit: https://aqicn.org/search/)\")\n return self.DEFAULT\n\n return AqicnTuple(\n provider='AQICN',\n pm25=aqicn_data[\"data\"][\"iaqi\"][\"pm25\"][\"v\"] if 'pm25' in aqicn_data[\"data\"][\"iaqi\"] else -1,\n pm10=aqicn_data[\"data\"][\"iaqi\"][\"pm10\"][\"v\"] if 'pm10' in aqicn_data[\"data\"][\"iaqi\"] else -1,\n pressure=aqicn_data[\"data\"][\"iaqi\"][\"p\"][\"v\"] if 'p' in aqicn_data[\"data\"][\"iaqi\"] else -1,\n humidity=aqicn_data[\"data\"][\"iaqi\"][\"h\"][\"v\"] if 'h' in aqicn_data[\"data\"][\"iaqi\"] else -1,\n temperature=aqicn_data[\"data\"][\"iaqi\"][\"t\"][\"v\"] if 't' in aqicn_data[\"data\"][\"iaqi\"] else None,\n aqi=aqicn_data[\"data\"][\"aqi\"],\n level=None,\n advice=None\n )\n\n except Exception as e:\n logging.exception(e)\n return self.DEFAULT\n\n\n","sub_path":"providers/aqicn.py","file_name":"aqicn.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"11427021","text":"#-------------------------------------------------------------------------------\n# Name: insertReg\n# Purpose: Insert a register in project's database\n# Author: Trigam\n# Created: 22/03/2015\n# Status: Incomplete\n#-------------------------------------------------------------------------------\n\nimport settings\n\n#Insert new register\ndef insertReg():\n\n car_name = raw_input(\"Insert a car's name:\");\n car_price = raw_input(\"Insert a car's price\");\n\n with settings.con:\n cur = settings.con.cursor();\n cur.execute(\"INSERT INTO Cars VALUES(10,'\" + car_name + \"','\"+ car_price +\"')\");\n\n return;","sub_path":"Python_2.7/insertReg.py","file_name":"insertReg.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"83087360","text":"import os\nimport codecs\nfrom markdown import Markdown\nfrom werkzeug.utils import cached_property\nfrom flask import Flask, current_app, request, abort, url_for, render_template, render_template_string, Markup, Blueprint, send_from_directory\nfrom .markdown_extensions import BootstrapTableExtension\n\nclass Page:\n def __init__(self, path, content=None):\n self.path = path\n # UTF-8 here is intentional!\n if content is None:\n with codecs.open(self.path, encoding='utf-8') as f:\n self.raw_content = f.read()\n else:\n self.raw_content = content\n\n self._load_meta()\n\n # Because we need only the meta, we parse the document without executing jinja templates inside it\n def _load_meta(self):\n markdown = Markdown(extensions=['meta']) # No need for other extensions\n markdown.convert(self.raw_content)\n self.meta = markdown.Meta\n self.meta['page'] = self\n self.meta['template'] = self.meta.get('template', 'page.html')\n\n def load(self):\n content = render_template_string(self.raw_content, page=self)\n markdown = Markdown(extensions=[BootstrapTableExtension(), 'meta', 'fenced_code', 'codehilite', 'nl2br'])\n self.html_content = markdown.convert(content)\n\n @cached_property\n def url(self):\n path = os.path.relpath(self.path, current_app.config['PAGES_DIR'])\n path = os.path.splitext(path)[0]\n return url_for('portal.render_page', path=path)\n\n @cached_property\n def title(self):\n path = os.path.relpath(self.path, current_app.config['PAGES_DIR'])\n alt_title = os.path.splitext(path)[0]\n return self.meta.get('title', [alt_title])[0]\n\n# Stop autoescaping\nclass Portal(Flask):\n def select_jinja_autoescape(self, filename):\n return False\n\n\nblueprint = Blueprint('portal', __name__)\n\n\n@blueprint.route('/favicon.ico')\ndef favicon():\n return send_from_directory(os.path.join(current_app.root_path, 'static'),\n 'favicon.ico', mimetype='image/vnd.microsoft.icon')\n\n\n@blueprint.route('/', defaults={'path': 'index'})\n@blueprint.route('/')\ndef render_page(path):\n try:\n page = Page(os.path.join(current_app.config['PAGES_DIR'], path + '.md'))\n page.load()\n except IOError:\n abort(404)\n\n return render_template(page.meta['template'], content=page.html_content, page=page)\n\n","sub_path":"examples/miniportal/portal/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"484295035","text":"hs=[]\ncrs=[]\nms=[]\nfas=[]\nfor sub in range(numsubs):\n graph = uinvite_graphs[sub]\n hit=miss=fa=cr=0\n for rownum, row in enumerate(graph):\n for colnum, val in enumerate(row):\n item1 = items[sub][rownum]\n item2 = items[sub][colnum]\n idx1 = usf_items.keys()[usf_items.values().index(item1)]\n idx2 = usf_items.keys()[usf_items.values().index(item2)]\n if (val==1) and (usf_graph[idx1][idx2] == 1):\n hit += 1\n if (val==1) and (usf_graph[idx1][idx2] == 0):\n fa += 1\n if (val==0) and (usf_graph[idx1][idx2] == 1):\n miss += 1\n if (val==0) and (usf_graph[idx1][idx2] == 0):\n cr += 1\n #hs.append(hit / float(hit + fa)) # ~ .7\n #crs.append(cr / float(cr + miss)) # ~.96\n hs.append(hit)\n crs.append(cr)\n ms.append(miss)\n fas.append(fa)\n","sub_path":"tmp.py","file_name":"tmp.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"339552515","text":"from db_bot import DbBotHelper\nfrom db_scrap import DbScrapHelper\n\ndb = DbBotHelper()\n\nprint(db.get_all_routes())\n\nroute_id = 2\n\nprint(db.get_major_stops(route_id))\n\nmajor_stop_id = 10\nbusstop_id = 26\n\n# обратные рейсы привязать к направлению \"на Расторгуево\" или \"на ул.Завидная\"\n#db1 = DbScrapHelper()\n#route_id = 2\n#busstop_id = db1.find_busstop(db1.conn.cursor(), 'ул.Завидная, д.24')\n#print('ул.Завидная, д.24 busstop_id =', busstop_id)\n#print(list(db1.exec(\"SELECT * FROM trip WHERE trip.route_id = ? and trip.is_return = 1 and trip.trip_id in \"\n# \"(select trip_id from stoptime where stoptime.trip_id = trip.trip_id and stoptime.busstop_id = ?);\",\n# (route_id, busstop_id))))\n#\n#busstop_id = db1.find_busstop(db1.conn.cursor(), 'ст.Расторгуево')\n#print('ст.Расторгуево busstop_id =', busstop_id)\n#print(list(db1.exec(\"SELECT * FROM trip WHERE trip.route_id = ? and trip.is_return = 1 and trip.trip_id in \"\n# \"(select trip_id from stoptime where stoptime.trip_id = trip.trip_id and stoptime.busstop_id = ?);\",\n# (route_id, busstop_id))))\n\nprint(db.get_directions(major_stop_id))\n\ndirection_id = 3\nweekday_id = 7\n\nprint(db.get_day_schedule(busstop_id, weekday_id, direction_id))\n\nprint(db.get_hour_schedule(busstop_id, weekday_id, direction_id, 6 * 60 + 00, 7 * 60 + 00))","sub_path":"playground.py","file_name":"playground.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"526269320","text":"from typing import Optional\nfrom fastapi import FastAPI, Response\nfrom starlette.responses import StreamingResponse\nfrom fastapi.responses import FileResponse\nfrom fastapi import FastAPI, File, UploadFile\nfrom fastapi.middleware.cors import CORSMiddleware\nimport time\nimport processing\n\n\napp = FastAPI()\n\norigins = [\n \"http://localhost\",\n \"http://localhost:9050\",\n]\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n@app.get(\"/\")\ndef read_root():\n return {\"Hello\": \"World\"}\n\n@app.get(\"/id={ids}\")\ndef process(ids: int):\n \"\"\"\n Take ids, call processing, return response from processing (code 200, e.g.)\n \n \"\"\"\n response = processing.main(ids)\n return StreamingResponse(response, media_type=\"image/png\")\n # return {'Result of prediction': \"All ur base are mine\", 'id': ids, 'responce': StreamingResponse(response)}\n\n\n@app.post(\"/file/{id}\")\nasync def image(image: UploadFile = File(...), id: int = 0):\n data = await image.read()\n\n response = processing.processing(data)\n\n return StreamingResponse(response, media_type=\"image/png\")\n # return {'r': 5}\n","sub_path":"listener.py","file_name":"listener.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"57376919","text":"from django.shortcuts import render, redirect\nfrom django.http.response import JsonResponse\nfrom rest_framework.parsers import JSONParser\nfrom rest_framework import status\nfrom .models import Url\nimport pyshorteners\nfrom .serializers import UrlShortnerSerializer\nfrom rest_framework.decorators import api_view\n\n\n@api_view(['GET', 'POST', 'DELETE'])\ndef url_list(request):\n if request.method == 'GET':\n urls = Url.objects.filter(status=1)\n url_serializer = UrlShortnerSerializer(urls, many=True)\n return JsonResponse(url_serializer.data, safe=False)\n\n elif request.method == 'POST':\n url_data = JSONParser().parse(request)\n if \"original_url\" in url_data.keys():\n count = Url.objects.filter(original_url=url_data[\"original_url\"],status=0)\n if count:\n Url.objects.filter(original_url=url_data[\"original_url\"], status=0).update(status=1)\n return JsonResponse({'message': 'Existed Inactive URL status marked as 1 and is Active'})\n else:\n short_url = create_short_url(url_data)\n url_data[\"short_url\"] = short_url\n url_serializer = UrlShortnerSerializer(data=url_data)\n if url_serializer.is_valid():\n url_serializer.save()\n return JsonResponse(url_serializer.data, status=status.HTTP_201_CREATED)\n return JsonResponse(url_serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n elif \"short_url\" in url_data.keys():\n urls = Url.objects.filter(short_url=url_data[\"short_url\"],status=1)\n url_serializer = UrlShortnerSerializer(urls,many=True)\n return JsonResponse(url_serializer.data,safe=False, status=status.HTTP_200_OK)\n else:\n url_serializer = UrlShortnerSerializer(data=url_data,many=True)\n return JsonResponse(url_serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n elif request.method == 'DELETE':\n url_data = JSONParser().parse(request)\n count = Url.objects.filter(original_url=url_data[\"original_url\"],status=1).update(status=0)\n if count == 1:\n return JsonResponse({'message': '{} URL deleted successfully and status marked as 0'})\n else:\n return JsonResponse({'message': 'URL already deleted'})\n\n\ndef urlRedirect(request, short_url):\n data = Url.objects.get(short_url=short_url)\n return redirect(data.original_url)\n\ndef create_short_url(request):\n url = request[\"original_url\"]\n if url.startswith(\"https://www.\"):\n url = url.replace(\"https://www.\", \"\")\n elif url.startswith(\"http://www.\"):\n url = url.replace(\"http://www.\", \"\")\n elif url.startswith(\"http://\"):\n url = url.replace(\"http://\", \"\")\n elif url.startswith(\"https://\"):\n url = url.replace(\"https://\", \"\")\n elif url.startswith(\"www.\"):\n url = url.replace(\"www.\", \"\")\n else:\n url = url\n if url.endswith(\"/\"):\n url = url.replace(\"/\", \"\")\n short_url = pyshorteners.Shortener().tinyurl.short(url)\n return short_url","sub_path":"url_shortner/url_shortner_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"638771293","text":"# Copyright 2020 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# 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\"\"\" Creates a Cloud Task that invokes an AI Platform Prediction version. \"\"\"\n\n\nimport argparse\nimport datetime\nimport json\nimport googleapiclient.discovery\nimport logging\n\nfrom typing import List, Optional, Text, Union, Dict\nfrom google.cloud import tasks_v2\nfrom google.protobuf import timestamp_pb2\n\ndef create_predict_task(\n project: str,\n queue: str,\n service_account: str,\n location: str,\n model_name: str,\n model_version: str, \n instances: List[Union[Dict,List]],\n execute_time: datetime):\n \n \"\"\"Creates a Cloud Tasks task that calls the AI Platform Prediction service.\"\"\"\n \n client = tasks_v2.CloudTasksClient()\n parent = client.queue_path(project, location, queue)\n\n service_uri = 'https://ml.googleapis.com/v1/projects/{}/models/{}/versions/{}:predict'.format(\n project, model_name, model_version)\n instances = json.dumps({'instances': instances})\n\n task = {\n 'http_request': { \n 'http_method': 'POST',\n 'url': service_uri,\n 'body': instances.encode(),\n 'headers': {'content-type': 'application/json'},\n 'oauth_token': {'service_account_email': service_account}\n }\n }\n\n timestamp = timestamp_pb2.Timestamp()\n timestamp.FromDatetime(execute_time)\n task['schedule_time'] = timestamp\n\n response = client.create_task(parent, task)\n logging.info(\"Created task: {}\".format(response.name))\n\n return response\n\n\ndef generate_predict_tasks(\n project: str,\n queue: str,\n service_account: str,\n location: str,\n model_name: str,\n model_version: str,\n data_file: str,\n start_time: datetime,\n instances_per_call: int,\n time_between_calls: int):\n\n \"\"\"Creates a set of tasks that call AI Platform Prediction service.\"\"\"\n \n #with open(data_file, 'r') as json_examples:\n # instances = []\n # execute_time = datetime.datetime.fromisoformat(start_time)\n # for json_example in json_examples:\n # instances.append(json.loads(json_example))\n # if len(instances) == instances_per_call:\n # create_predict_task(\n # project: str,\n # queue: str,\n # service_account: str,\n # location: str,\n # model_name: str,\n # model_version: str, instances, \n # execute_time + datetime.timedelta(seconds=time_between_calls)\n # instances = []\n # if len(instances):\n # _create_predict_task(instances, execute_time)\n\nif __name__ == '__main__':\n logging.basicConfig()\n logging.getLogger().setLevel(logging.INFO)\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n '--project',\n help='Project of the queue to add the task to.',\n required=True,\n )\n\n parser.add_argument(\n '--queue',\n help='ID (short name) of the queue to add the task to.',\n required=True,\n )\n\n parser.add_argument(\n '--service_account',\n help='An email of a service account to use for submitting calls.',\n required=True,\n )\n\n parser.add_argument(\n '--location',\n help='Location of the queue to add the task to.',\n required=True,\n )\n\n parser.add_argument(\n '--model_name',\n help='The AI Platform Prediction model',\n required=True,\n )\n\n parser.add_argument(\n '--model_version',\n help='The AI Platform Prediction model version',\n required=True\n )\n\n parser.add_argument(\n '--data_file',\n help=\"A path to a file with instances.\",\n required=True\n )\n\n parser.add_argument(\n '--start_time', \n help='The start date and time for a simulation in ISO format',\n required=True\n )\n\n parser.add_argument(\n '--instances_per_call',\n help='The number of instances batched in each call',\n type=int,\n default=3,\n )\n\n parser.add_argument(\n '--time_between_calls',\n help='The delay between calls in seconds',\n type=int,\n default=60,\n )\n args = parser.parse_args()\n\n generate_predict_tasks(\n project=args.project, \n queue=args.queue, \n service_account=args.service_account,\n location=args.location,\n model_name=args.model_name,\n model_version=args.model_version,\n data_file=args.data_file, \n start_time=args.start_time,\n instances_per_call=args.instances_per_call,\n time_between_calls=args.time_between_calls)","sub_path":"utilities/player/generate_predict_tasks.py","file_name":"generate_predict_tasks.py","file_ext":"py","file_size_in_byte":5215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"53373644","text":"#!/usr/bin/env python\n# Name:\n# Student number:\n\"\"\"\nThis script visualizes data obtained from a .csv file\n\"\"\"\n\nimport csv\nimport matplotlib.pyplot as plt\nfrom collections import defaultdict\nimport numpy as np\nimport pandas as pd\n\n# Global constants for the input file, first and last year\nINPUT_CSV = \"movies.csv\"\nSTART_YEAR = 2008\nEND_YEAR = 2018\n\n# Global dictionary for the data\ndata_dict = {}\nmovies = defaultdict(list)\n\nif __name__ == \"__main__\":\n\n years, ratings, y = [], [], []\n\n with open(INPUT_CSV, newline='') as csvfile:\n\n reader = csv.DictReader(csvfile)\n\n for row in reader:\n movies[row['year']].append(row['rating'])\n\n # averaging scores per year\n for year in range(START_YEAR, END_YEAR):\n year_ratings = np.array(movies[str(year)])\n year_ratings = year_ratings.astype(np.float)\n data_dict[str(year)] = round(np.mean(year_ratings), 1)\n\n # create array with all the years\n x = list(range(START_YEAR, END_YEAR))\n\n # create array with all the mean ratings of said year\n for i in range(len(x)):\n y.append(data_dict[str(x[i])])\n\n # initiate plot\n plot = plt.plot(x, y)\n\n # titles\n plt.title(\"'08 and '18\")\n plt.suptitle(\"Average Rating of Movies on IMDB\", fontsize=14)\n plt.xlabel(\"Year\")\n plt.ylabel(\"Rating\")\n\n # linestyle, width and color\n plt.setp(plot, linestyle='-', linewidth=2, color='r', alpha=0.5)\n\n # removing ugly frame lines\n ax = plt.subplot()\n ax.spines[\"top\"].set_visible(False)\n ax.spines[\"right\"].set_visible(False)\n\n # moving the labels a bit further a way from the plot\n ax.xaxis.labelpad = 10\n ax.yaxis.labelpad = 10\n\n # setting y limits to emphasize the differences between years\n plt.ylim(7.7, 8.8)\n\n # visualize plot\n plt.show()\n","sub_path":"Homework/week_1/visualizer_old.py","file_name":"visualizer_old.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"497324734","text":"import urllib.request\nimport json\nfrom firebase import firebase\nfrom bs4 import BeautifulSoup\nimport re\nimport html\nimport math\n\n\nfirebase_url = \"https://mudig3.firebaseio.com/\"\nfirebase = firebase.FirebaseApplication(firebase_url, None)\n\n# Get the last \"Apply HN\"\nurl = \"https://news.ycombinator.com/applynew\"\n\nreq = urllib.request.Request(\n url,\n data=None,\n headers={\n 'User-Agent': 'muDIG'\n }\n)\n\nf = urllib.request.urlopen(req)\nthread = f.read().decode('utf-8')\n\nsoup = BeautifulSoup(thread, \"html.parser\")\n\n\nposts = soup.find_all(attrs = {'class' : 'athing'})\n\nfor post in posts:\n foo = post.find_all(\"td\", attrs = {'class' : 'title'})[1].a\n\n url = foo.get('href')\n name =foo.contents[0][10:] #Remove \"Apply HN\"\n\n id = url[8:]\n\n if \"item\" not in url:\n continue\n\n jsonurl = \"https://hacker-news.firebaseio.com/v0/item/\"+id+\".json\"\n\n req = urllib.request.Request(\n jsonurl,\n data=None,\n headers={\n 'User-Agent': 'muDIG'\n }\n )\n\n f = urllib.request.urlopen(req)\n thread = f.read().decode('utf-8')\n thread = json.loads(thread)\n\n author = thread[\"by\"]\n body_html = html.unescape(thread[\"text\"])\n created = thread[\"time\"]\n score = thread[\"score\"]\n\n urls = re.findall(r'https?://[^\\s<>\"]+|www\\.[^\\s<>\"]+', body_html)\n url = \"\"\n\n if urls:\n url = urls[0]\n\n word_count = len(body_html)\n\n url01 = 0\n if url:\n url01 = 1\n\n # c0, c_score, c_word_count, c_url_01\n qs = 29.24 + 8.07025371e-01*score - 3.02876503e-03*word_count + 6.29742825e+00*url01\n print(qs)\n\n result = firebase.put('/yc', id, {'name': name, 'qs': qs, 'author': author, 'body_html': body_html, 'url': url, 'score': score, 'created': created})\n\n","sub_path":"scripts/ycombinator.py","file_name":"ycombinator.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"404828781","text":"import chainer\nimport chainer.functions as F\nimport chainer.links as L\n\n\n# https://github.com/zaburo-ch/chainercv/blob/master/chainercv/links/connection/seblock.py\nclass SEBlock(chainer.Chain):\n\n \"\"\"A squeeze-and-excitation block.\n This block is part of squeeze-and-excitation networks. Channel-wise\n multiplication weights are inferred from and applied to input feature map.\n Please refer to `the original paper\n `_ for more details.\n .. seealso::\n :class:`chainercv.links.model.senet.SEResNet`\n Args:\n n_channel (int): The number of channels of the input and output array.\n ratio (int): Reduction ratio of :obj:`n_channel` to the number of\n hidden layer units.\n \"\"\"\n\n def __init__(self, n_channel, ratio=16):\n\n super(SEBlock, self).__init__()\n reduction_size = n_channel // ratio\n\n with self.init_scope():\n self.down = L.Linear(n_channel, reduction_size)\n self.up = L.Linear(reduction_size, n_channel)\n\n def __call__(self, u):\n B, C, H, W = u.shape\n\n z = F.average(u, axis=(2, 3))\n x = F.relu(self.down(z))\n x = F.sigmoid(self.up(x))\n\n x = F.broadcast_to(x, (H, W, B, C))\n x = x.transpose((2, 3, 0, 1))\n\n return u * x\n\n\nclass BottleNeck(chainer.Chain):\n\n def __init__(self, n_in, n_mid, n_out, stride=1, use_conv=False, add_seblock=False):\n w = chainer.initializers.HeNormal()\n super(BottleNeck, self).__init__()\n with self.init_scope():\n self.conv1 = L.Convolution2D(n_in, n_mid, 1, stride, 0, True, w)\n self.bn1 = L.BatchNormalization(n_mid)\n self.conv2 = L.Convolution2D(n_mid, n_mid, 3, 1, 1, True, w)\n self.bn2 = L.BatchNormalization(n_mid)\n self.conv3 = L.Convolution2D(n_mid, n_out, 1, 1, 0, True, w)\n self.bn3 = L.BatchNormalization(n_out)\n if add_seblock:\n self.se = SEBlock(n_out)\n if use_conv:\n self.conv4 = L.Convolution2D(\n n_in, n_out, 1, stride, 0, True, w)\n self.bn4 = L.BatchNormalization(n_out)\n self.use_conv = use_conv\n self.add_seblock = add_seblock\n\n def __call__(self, x):\n h = F.relu(self.bn1(self.conv1(x)))\n h = F.relu(self.bn2(self.conv2(h)))\n h = self.bn3(self.conv3(h))\n if self.add_seblock:\n h = self.se(h)\n return h + self.bn4(self.conv4(x)) if self.use_conv else h + x\n\n\nclass Block(chainer.ChainList):\n\n def __init__(self, n_in, n_mid, n_out, n_bottlenecks, stride=2, add_seblock=False):\n super(Block, self).__init__()\n self.add_link(BottleNeck(n_in, n_mid, n_out, stride, True, add_seblock))\n for _ in range(n_bottlenecks - 1):\n self.add_link(BottleNeck(n_out, n_mid, n_out, add_seblock=add_seblock))\n\n def __call__(self, x):\n for f in self:\n x = f(x)\n return x\n\n\nclass ResNet(chainer.Chain):\n\n def __init__(self, n_class=10, n_blocks=[3, 4, 6, 3], add_seblock=False):\n super(ResNet, self).__init__()\n w = chainer.initializers.HeNormal()\n with self.init_scope():\n self.conv1 = L.Convolution2D(None, 64, 3, 1, 0, True, w)\n self.bn2 = L.BatchNormalization(64)\n self.res3 = Block(64, 64, 256, n_blocks[0], 1, add_seblock)\n self.res4 = Block(256, 128, 512, n_blocks[1], 2, add_seblock)\n self.res5 = Block(512, 256, 1024, n_blocks[2], 2, add_seblock)\n self.res6 = Block(1024, 512, 2048, n_blocks[3], 2, add_seblock)\n self.fc7 = L.Linear(None, n_class)\n\n def __call__(self, x):\n h = F.relu(self.bn2(self.conv1(x)))\n h = self.res3(h)\n h = self.res4(h)\n h = self.res5(h)\n h = self.res6(h)\n h = F.average_pooling_2d(h, h.shape[2:])\n h = self.fc7(h)\n return h\n\n\nclass ResNet50(ResNet):\n\n def __init__(self, n_class=10, add_seblock=False):\n super(ResNet50, self).__init__(n_class, [3, 4, 6, 3], add_seblock)\n\n\nclass ResNet101(ResNet):\n\n def __init__(self, n_class=10, add_seblock=False):\n super(ResNet101, self).__init__(n_class, [3, 4, 23, 3], add_seblock)\n\n\nclass ResNet152(ResNet):\n\n def __init__(self, n_class=10, add_seblock=False):\n super(ResNet152, self).__init__(n_class, [3, 8, 36, 3], add_seblock)\n\n\nif __name__ == '__main__':\n import numpy as np\n x = np.random.randn(1, 3, 32, 32).astype(np.float32)\n model = ResNet(10)\n y = model(x)\n","sub_path":"models/resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":4566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"25787510","text":"import threading\n\nimport matplotlib.pyplot as plt\nimport reacton.ipywidgets as widgets\nimport solara\nfrom matplotlib.figure import Figure\nfrom matplotlib.ticker import MaxNLocator\n\n# Avoid interactive backend\nplt.switch_backend(\"agg\")\n\n\nclass JupyterContainer:\n def __init__(\n self,\n model_class,\n model_params,\n measures=None,\n name=\"Mesa Model\",\n agent_portrayal=None,\n ):\n self.model_class = model_class\n self.split_model_params(model_params)\n self.measures = measures\n self.name = name\n self.agent_portrayal = agent_portrayal\n self.thread = None\n\n def split_model_params(self, model_params):\n self.model_params_input = {}\n self.model_params_fixed = {}\n for k, v in model_params.items():\n if self.check_param_is_fixed(v):\n self.model_params_fixed[k] = v\n else:\n self.model_params_input[k] = v\n\n def check_param_is_fixed(self, param):\n if not isinstance(param, dict):\n return True\n if \"type\" not in param:\n return True\n\n def do_step(self):\n self.model.step()\n self.set_df(self.model.datacollector.get_model_vars_dataframe())\n\n def do_play(self):\n self.model.running = True\n while self.model.running:\n self.do_step()\n\n def threaded_do_play(self):\n if self.thread is not None and self.thread.is_alive():\n return\n self.thread = threading.Thread(target=self.do_play)\n self.thread.start()\n\n def do_pause(self):\n if (self.thread is None) or (not self.thread.is_alive()):\n return\n self.model.running = False\n self.thread.join()\n\n def portray(self, g):\n x = []\n y = []\n s = [] # size\n c = [] # color\n for i in range(g.width):\n for j in range(g.height):\n content = g._grid[i][j]\n if not content:\n continue\n if not hasattr(content, \"__iter__\"):\n # Is a single grid\n content = [content]\n for agent in content:\n data = self.agent_portrayal(agent)\n x.append(i)\n y.append(j)\n if \"size\" in data:\n s.append(data[\"size\"])\n if \"color\" in data:\n c.append(data[\"color\"])\n out = {\"x\": x, \"y\": y}\n if len(s) > 0:\n out[\"s\"] = s\n if len(c) > 0:\n out[\"c\"] = c\n return out\n\n\ndef make_space(viz):\n space_fig = Figure()\n space_ax = space_fig.subplots()\n space_ax.scatter(**viz.portray(viz.model.grid))\n space_ax.set_axis_off()\n solara.FigureMatplotlib(space_fig, dependencies=[viz.model, viz.df])\n\n\ndef make_plot(viz, measure):\n fig = Figure()\n ax = fig.subplots()\n ax.plot(viz.df.loc[:, measure])\n ax.set_ylabel(measure)\n # Set integer x axis\n ax.xaxis.set_major_locator(MaxNLocator(integer=True))\n solara.FigureMatplotlib(fig, dependencies=[viz.model, viz.df])\n\n\ndef make_text(renderer):\n def function(viz):\n solara.Markdown(renderer(viz.model))\n\n return function\n\n\ndef make_user_input(user_input, k, v):\n if v[\"type\"] == \"SliderInt\":\n solara.SliderInt(\n v.get(\"label\", \"label\"),\n value=user_input,\n min=v.get(\"min\"),\n max=v.get(\"max\"),\n step=v.get(\"step\"),\n )\n elif v[\"type\"] == \"SliderFloat\":\n solara.SliderFloat(\n v.get(\"label\", \"label\"),\n value=user_input,\n min=v.get(\"min\"),\n max=v.get(\"max\"),\n step=v.get(\"step\"),\n )\n\n\n@solara.component\ndef MesaComponent(viz, space_drawer=None, play_interval=400):\n solara.Markdown(viz.name)\n\n # 1. User inputs\n user_inputs = {}\n for k, v in viz.model_params_input.items():\n user_input = solara.use_reactive(v[\"value\"])\n user_inputs[k] = user_input.value\n make_user_input(user_input, k, v)\n\n # 2. Model\n def make_model():\n return viz.model_class(**user_inputs, **viz.model_params_fixed)\n\n viz.model = solara.use_memo(make_model, dependencies=list(user_inputs.values()))\n viz.df, viz.set_df = solara.use_state(\n viz.model.datacollector.get_model_vars_dataframe()\n )\n\n # 3. Buttons\n playing = solara.use_reactive(False)\n\n def on_value_play(change):\n if viz.model.running:\n viz.do_step()\n else:\n playing.value = False\n\n with solara.Row():\n solara.Button(label=\"Step\", color=\"primary\", on_click=viz.do_step)\n # This style is necessary so that the play widget has almost the same\n # height as typical Solara buttons.\n solara.Style(\n \"\"\"\n .widget-play {\n height: 30px;\n }\n \"\"\"\n )\n widgets.Play(\n value=0,\n interval=play_interval,\n repeat=True,\n show_repeat=False,\n on_value=on_value_play,\n playing=playing.value,\n on_playing=playing.set,\n )\n # threaded_do_play is not used for now because it\n # doesn't work in Google colab. We use\n # ipywidgets.Play until it is fixed. The threading\n # version is definite a much better implementation,\n # if it works.\n # solara.Button(label=\"▶\", color=\"primary\", on_click=viz.threaded_do_play)\n # solara.Button(label=\"⏸︎\", color=\"primary\", on_click=viz.do_pause)\n # solara.Button(label=\"Reset\", color=\"primary\", on_click=do_reset)\n\n with solara.GridFixed(columns=2):\n # 4. Space\n if space_drawer is None:\n make_space(viz)\n else:\n space_drawer(viz)\n # 5. Plots\n for measure in viz.measures:\n if callable(measure):\n # Is a custom object\n measure(viz)\n else:\n make_plot(viz, measure)\n\n\n# JupyterViz has to be a Solara component, so that each browser tabs runs in\n# their own, separate simulation thread. See https://github.com/projectmesa/mesa/issues/856.\n@solara.component\ndef JupyterViz(\n model_class,\n model_params,\n measures=None,\n name=\"Mesa Model\",\n agent_portrayal=None,\n space_drawer=None,\n play_interval=400,\n):\n return MesaComponent(\n JupyterContainer(model_class, model_params, measures, name, agent_portrayal),\n space_drawer=space_drawer,\n play_interval=play_interval,\n )\n","sub_path":"mesa/experimental/jupyter_viz.py","file_name":"jupyter_viz.py","file_ext":"py","file_size_in_byte":6614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"463263799","text":"import numpy as np\nfrom geneticalgorithm import geneticalgorithm as ga\nimport pygad\n\n\nclass GeneticAlg:\n @classmethod\n def genetic_alg(cls, iteration_num, parent_num, fitness,\n number_of_solutions, num_genes, crossover_probability,\n mutation_probability, after_mutation_func):\n # initial_population is built by sol_per_pop and num_genes\n # num_genes = Number of genes in the solution / chromosome\n ga_instance = pygad.GA(num_generations=iteration_num,\n num_parents_mating=parent_num,\n fitness_func=fitness,\n sol_per_pop=number_of_solutions,\n num_genes=num_genes,\n gene_type=float,\n init_range_low=0.0,\n init_range_high=1.0,\n parent_selection_type=\"rws\",\n keep_parents=0,\n crossover_type=\"single_point\",\n crossover_probability=crossover_probability,\n mutation_type=\"random\",\n mutation_probability=mutation_probability,\n mutation_by_replacement=False,\n random_mutation_min_val=0.0,\n random_mutation_max_val=1.0,\n on_mutation=after_mutation_func)\n ga_instance.run()\n solution, solution_fitness, solution_idx = ga_instance.best_solution()\n print(\"Parameters of the best solution : {solution}\".format(solution=solution))\n print(\"Fitness value of the best solution = {solution_fitness}\".format(solution_fitness=solution_fitness))\n print(\"Index of the best solution : {solution_idx}\".format(solution_idx=solution_idx))\n filename = 'genetic'\n ga_instance.save(filename=filename)\n loaded_ga_instance = pygad.load(filename=filename)\n return loaded_ga_instance.best_solution()\n\n @classmethod\n def on_mutation(cls, ga_instance, offspring_mutation):\n for chromosome in offspring_mutation:\n sum_ = 0\n for q in chromosome:\n if q < 0:\n offspring_mutation.remove(chromosome)\n break\n sum_ += q\n if sum_ > 1:\n offspring_mutation.remove(chromosome)\n return offspring_mutation\n","sub_path":"algorithmes/genetic_alg.py","file_name":"genetic_alg.py","file_ext":"py","file_size_in_byte":2530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"616870816","text":"\"\"\"\n\n 02_fetching_rows.py\n\n The following source will create a namedtuple called School.\n\n It then retrieves rows of data from schools.db which has assumed to have been\n created already. If it has not, run the 01 example in this folder first.\n\n\"\"\"\nimport sqlite3\nfrom collections import namedtuple\n\nSchool = namedtuple('School', 'school_id name city state country')\n\nschool_data = []\nconnection = None\nstate = input('Schools from which state: ').upper()\ntry:\n connection = sqlite3.connect('schools.db')\n connection.row_factory = sqlite3.Row\n cursor = connection.cursor()\n cursor.execute('SELECT * FROM schools WHERE state=?', (state,))\n for sch in cursor.fetchall():\n school_data.append(School(sch['school_id'], sch['fullname'], sch['city'], sch['state'], sch['country']))\nexcept sqlite3.Error as e:\n print('Error: {0}'.format(e))\nfinally:\n if connection:\n connection.close()\n\nprint('Schools in {0}'.format(state))\nfor school in school_data:\n print('{name}, {city} {state}'.format(**school.__dict__))\n","sub_path":"student_files/ch02_database/02_fetching_rows.py","file_name":"02_fetching_rows.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"362185599","text":"import serial\nfrom datetime import datetime\n\n# COM port on windows /dev/tty* on Unix system\nport = \"COM3\"\n# port = \"/dev/tty3\"\n\nser = serial.Serial(port, 115200, timeout = 1000)\nser.flushInput()\n\ncurrent_date = datetime.now().strftime('%d-%m-%Y')\nfilename = f'../logs/arduino-{current_date}.log'\nf = open(filename, \"w\")\nf.close() \n\nwhile True:\n ser_bytes = ser.readline().decode(\"utf-8\")[:-2] + \"\\n\"\n with open(filename,\"a\") as f:\n split = ser_bytes.split(\"FM=\")\n if len(split) > 1 and split[1][0] == \"0\":\n ser_bytes = split[0] + \"FM=1\" + split[1] \n if len(ser_bytes) > 5:\n split = ser_bytes.split(\"RSSI=\")\n ser_bytes = split[0] + \"RSSI=-\" + split[1]\n f.write(ser_bytes)\n ","sub_path":"arduino/serial_reading.py","file_name":"serial_reading.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"20742612","text":"\"\"\"\n* @author: Divyesh Patel\n* @email: pateldivyesh009@gmail.com \n* @date: 27/05/20\n* @decription: Write a Python program to get the difference between the two lists\n\"\"\"\n\nfirst = ['divyesh', 'patel', 'rushabh', 'dave']\nsecond = ['preet', 'patel']\n\ndiff_res = list()\n\nfor each in first:\n if each not in second:\n diff_res.append(each)\n\nprint(diff_res)\n","sub_path":"dp_w3resource_solutions/list/19_difference_between_two_lists.py","file_name":"19_difference_between_two_lists.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"610302971","text":"import random\n\nclass Battle:\n\tbase_health = 100\n\tdef fight(equipped, hit_chance, enemy_name=\"Monster\", enemy_hp=10):\n\t\tbattle = True\n\t\t# While the battle is going on, well, battle goes on\n\t\twhile battle:\n\t\t\ta = int(input(\"What to do?\\n1. Fight\\n2. Run\"))\n\t\t\tif a == 1:\n\t\t\t\tchance = random.random()\n\t\t\t\tif chance > (int(hit_chance)/100):\n\t\t\t\t\tweapon = equipped[\"weapon\"]\n\t\t\t\t\tprint(f\"Hit for {weapon[1]}!\\n\")\n\t\t\t\t\tif int(weapon[1]) > int(enemy_hp):\n\t\t\t\t\t\tprint(f\"{enemy_name} has been defeated!\")\n\t\t\t\t\t\tbattle = False\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Argh! A miss!\")\n# class Boss:","sub_path":"battle.py","file_name":"battle.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"446684848","text":"'''\n 进行以太网通讯\n'''\nimport binascii, Test2, Build, re, time\nfrom socket import *\nimport xml.etree.ElementTree as ET\n\n\ndef judgeRequest(data):\n # => 68 17 00 43 05 05 00 00 00 00 00 00 D1 89 05 01 1D 40 00 02 00 00 39 68 16\n C_D2to0 = int(Test2.dec2bin(int(Build.makelist(data)[3], 16)).zfill(8)[5:], 2)\n if C_D2to0 == 0:\n print('0')\n if C_D2to0 == 1:\n print('Received pre-link request:', data)\n data_SA_CA = ResponseStr(data)\n if C_D2to0 == 3:\n print('Data exchange service')\n Data_exchange_service(data)\n # print('data:', data)\n return C_D2to0, data_SA_CA\n\n\ndef Data_exchange_service(data):\n C = ctrlc(data)\n if data[14][0] == 0:\n re_APDU_1 = '8' + data[14][1]\n if data[14][0] == 8:\n re_APDU_1 = '0' + data[14][1]\n else: print('ERROR ON Data_exchange_service')\n lenth = int(data[18],16)\n while lenth:\n lenth -= 1\n ShowOAD = Information(re_APDU_1, data[15], data[14:-3], data)\n\n\ndef ctrlc(data):\n C = Test2.dec2bin(int(Build.makelist(data)[3], 16)).zfill(8)\n C_D7 = C[0]\n if C_D7 == '1': # 上行\n re_C = int('0' + C_D7[1:], 2)\n return re_C\n\n\ndef ResponseStr(data):\n data = Test2.makelist(data)\n data_C = '01'\n data_SA_CA = data[4:12]\n result = '80'\n times_request = data[19:29]\n time_recive = times_request\n times_request_1 = Build.list2str(times_request)\n time_recive[-3] = hex(int(times_request[-3], 16) + 2)[2:].zfill(2)\n time_response = Build.list2str(time_recive)\n APDU = '8100' + result + times_request_1 + time_response + time_response\n lenth = Build.makelist(hex(len(Build.makelist(APDU)) + 15)[2:].zfill(4))\n lenth = lenth[1] + lenth[0]\n Head = Build.makelist(lenth + data_C + Build.list2str(data_SA_CA))\n HCS = hex(Test2.pppfcs16(0xffff, Test2.strto0x(Head), len(Test2.strto0x(Head)))).zfill(4)[2:]\n if len(HCS) == 3: # 4ce\n HCS = '0' + HCS\n HCS = HCS[2:] + HCS[0:2]\n Full = Test2.strto0x(Head + Build.makelist(HCS) + Build.makelist(APDU))\n FCS = hex(Test2.pppfcs16(0xffff, Full, len(Full))).zfill(4)[2:]\n if len(FCS) == 3: # 4ce\n FCS = '0' + FCS\n FCS = FCS[2:] + FCS[0:2]\n message_response = '68' + lenth + data_C + Build.list2str(data_SA_CA) + HCS + APDU + FCS + '16'\n print('Sending pre-link response :', message_response)\n sent = tctimeClient.send(binascii.a2b_hex(message_response))\n return data_SA_CA\n\n\ndef Information(num, detail, APDU, code):\n if num == '01':\n print(num, '预链接请求')\n elif num == '81':\n print(num, '预链接响应')\n elif num == '02':\n print(num, '应用链接请求')\n elif num == '82':\n print(num, '应用链接响应')\n elif num == '03':\n print(num, '断开链接响应')\n elif num == '83':\n print(num, '断开链接请求')\n elif num == '05':\n print(num, '读取请求', end=' ')\n if detail == '01':\n print(detail, '读取一个对象属性请求(GetRequestNormal) ')\n elif detail == '02':\n print(detail, '读取若干个对象属性请求 (GetRequestNormalList) ')\n elif detail == '03':\n print(detail, '读取一个记录型对象属性请求 (GetRequestRecord) ')\n elif detail == '04':\n print(detail, '读取若干个记录型对象属性请求 (GetRequestRecordList) ')\n elif detail == '05':\n print(detail, '读取分帧响应的下一个数据块请求 (GetRequestNext) ')\n elif detail == '06':\n print(detail, '读取一个对象属性的 MD5 值 (GetRequestMD5) ')\n else:\n print('ERROR:05??')\n elif num == '85':\n print(num, '读取响应', end=' ')\n if detail == '01':\n print(detail, '读取一个对象属性的响应(GetResponseNormal) ')\n elif detail == '02':\n print(detail, '读取若干个对象属性的响应 (GetResponseNormalList) ')\n elif detail == '03':\n print(detail, '读取一个记录型对象属性的响应 (GetResponseRecord) ')\n APDU_remain = PIIDACD(APDU[2], APDU[3:])\n # returnvalue = A_ResultRecord_SEQUENCE(APDU_remain)\n # if returnvalue[0] == '00':\n # print('无跟随上报信息域')\n # if code[-4] == '00':\n # print('无时间标签')\n # if code[-1] == '16':\n # print('结束符正确')\n elif detail == '04':\n print(detail, '读取若干个记录型对象属性的响应 (GetResponseRecordList) ')\n elif detail == '05':\n print(detail, '分帧响应一个数据块 (GetResponseNext) ')\n elif detail == '06':\n print(detail, '读取一个对象属性的 MD5 值的响应 (GetResponseMD5) ')\n else:\n print('ERROR:85??')\n elif num == '06':\n print(num, '设置请求')\n elif num == '86':\n print(num, '设置响应')\n elif num == '07':\n print(num, '操作请求')\n elif num == '87':\n print(num, '操作响应')\n elif num == '08':\n print(num, '上报回应')\n elif num == '88':\n print(num, '上报请求')\n remain = PIIDACD(APDU[2], APDU[3:])\n revalue = Report_SequenceOfARecordRow_len(remain)\n\n\ndef PIIDACD(detail1, args):\n detail1 = int(detail1, 16)\n detail1 = Test2.dec2bin(detail1).zfill(8)\n if detail1[0] == '0':\n print('0 服务优先级:一般的')\n else:\n print('1 服务优先级:高级的', detail1, 'PIIDACD')\n if detail1[1] == '0':\n print('0 请求访问 ACD:不请求')\n else:\n print('1 请求访问 ACD:请求')\n print('服务序号', detail1[2:])\n return args\n\n\ndef PIID(detail2):\n detail2 = int(detail2, 16)\n detail2 = Test2.dec2bin(detail2).zfill(8) # 补0\n if detail2[0] == '0':\n print('0 服务优先级:一般的')\n else:\n print('1 服务优先级:高级的', detail2, 'PIIDACD')\n print('服务序号', detail2[2:])\n\n\ndef Report_SequenceOfARecordRow_len(remain):\n lenth = int(remain[0], 16)\n returncvalue = []\n while lenth:\n lenth -= 1\n remain.pop()\n returncvalue.append(OAD_SEQUENCE(remain[0]+remain[1]+remain[2]+remain[3], remain[4], remain[5]))\n remain = remain[6:]\n RCSD(remain[0], remain[1:])\n return returncvalue\n\n\ndef OAD_SEQUENCE(OI, unsigned1, unsigned2):\n OI = int(OI)\n unsigned11 = Test2.dec2bin(int(unsigned1)).zfill(8) # 特征值\n unsigned11 = int(unsigned11[0:4], 10)\n unsigned1 = '属性 ' + unsigned1[1]\n if 6000 <= OI <= 7000:\n for child in root[0]:\n for childern in child: # Table\n for grandchildern in childern: # Row\n Data = grandchildern.find(\"Data\")\n try:\n if Data.text == str(OI):\n print(Data.text, end=' ')\n global i\n i = 0\n i += 1\n if i == 3:\n print(Data.text, end=' ')\n global x\n x += 1\n if x == 1:\n try:\n if Data.text[3] == unsigned1[3]:\n print(Data.text, '特征:', unsigned11, '索引:', unsigned2)\n x += 1\n\n except:\n pass\n except:\n pass\n if OI < 6000:\n for child in root[1]:\n for childern in child: # Table\n for grandchildern in childern: # Row\n Data = grandchildern.find(\"Data\")\n try:\n if Data.text == str(OI).zfill(4):\n print(Data.text, unsigned1, end=' ')\n global ii\n ii = 0\n ii += 1\n if ii == 3:\n print(Data.text, '特征:', unsigned11, '索引:', unsigned2)\n except:\n pass\n return OI, unsigned1, unsigned2\n\n\ndef RCSD(remain_len, args):\n lens =int(remain_len)\n print('lens', lens)\n while lens > 0:\n args = CSD_CHOICE(args)\n lens -= 1\n return args\n\n\ndef CSD_CHOICE(args):\n type = args[0]\n if type == '00':\n print('CSD:', type)\n OAD = int(args[1] + args[2])\n OAD_SEQUENCE(OAD, args[3], args[4])\n if args == []:\n print('CSD_CHOICE is NULL')\n return args[5:]\n elif type == '01':\n # value = ROAD(args[1:])\n pass\n # if value == []:\n # print('CSD_CHOICE is NULL')\n # return value\n else:\n print('ERRORS:CSD_CHOICE')\n\n\ndef GetAPDU(SA): # list\n f = open('APDU', 'r', encoding='UTF-8')\n while 1:\n text = f.readline()[:-1]\n if text == '':\n print('Finished...')\n break\n point = re.findall('#', text)\n try:\n if point[0] == '#':\n text = text.split('#')\n print(text[0])\n SentWithAPDUbyEthernet(text[1].replace(' ', ''), SA)\n time.sleep(2)\n except:\n if not point:\n if text[0] == '0':\n SentWithAPDUbyEthernet(text.replace(' ', ''), SA)\n time.sleep(2)\n else:\n print(text)\n time.sleep(2)\n else:\n SentWithAPDUbyEthernet(text.replace(' ', ''), SA)\n time.sleep(2)\n\n\ndef SentWithAPDUbyEthernet(APDU, SA_address):\n C = '43'\n SA_sign = '0'\n CA = '00'\n APDUlist = Build.makelist(APDU)\n SA_address_nospace = Build.list2str(SA_address)\n lenth = int(Test2.dec2bin(len(SA_address)), 2)\n SA_sign = SA_sign + str(lenth - 1)\n Total_length = 5 + lenth + 3 + len(APDUlist) + 3\n Total_length_false = Total_length\n Total_length = hex(Total_length - 2)[2:].zfill(4)\n lenth1 = Total_length[2:]\n lenth2 = Total_length[0:2]\n Head = Test2.strto0x(Build.makelist(lenth1 + lenth2 + C + SA_sign + SA_address_nospace + CA))\n HCS = str(hex(Test2.pppfcs16(0xffff, Head, len(Head)))).zfill(4)[2:]\n if len(HCS) == 3:\n HCS = '0' + HCS\n HCS = HCS[2:] + HCS[0:2]\n message = Test2.strto0x(Build.makelist(lenth1 + lenth2 + C + SA_sign + SA_address_nospace + CA + HCS + APDU))\n FCS = hex(Test2.pppfcs16(0xffff, message, len(message))).zfill(4)[2:]\n if len(FCS) == 3:\n FCS = '0' + FCS\n FCS = FCS[2:] + FCS[0:2]\n message_full = '68' + lenth1 + lenth2 + C + SA_sign + SA_address_nospace + CA + HCS + APDU + FCS + '16'\n print('Sending:', message_full)\n remessage = binascii.a2b_hex(message_full)\n send = tctimeClient.send(remessage)\n while True:\n data = tctimeClient.recv(buffsize)\n data = str(binascii.b2a_hex(data))[2:-1]\n if data is not None:\n print('Received message:', data)\n time.sleep(2)\n break\n\n\nif __name__ == '__main__':\n asd = open('output.xml', 'r', encoding='UTF-8', errors='ignore')\n tree = ET.parse(asd)\n root = tree.getroot()\n host = '192.168.1.253'\n port = 8888\n buffsize = 2048\n ADDR = (host, port)\n tctime = socket(AF_INET, SOCK_STREAM)\n tctime.bind(ADDR)\n tctime.listen(5)\n while True:\n print('Wait for connection ...')\n tctimeClient, addr = tctime.accept()\n print(\"Connection from :\", addr)\n while True:\n data = tctimeClient.recv(buffsize)\n data = str(binascii.b2a_hex(data))[2:-1]\n if data is not None:\n print('Received message:', data)\n renum = judgeRequest(data)\n if renum[0] == 1:\n break\n GetAPDU(renum[1][1:7])\n\n # remessage = binascii.a2b_hex()\n # send = tctimeClient.send(remessage)\n\n # while True:\n # print('Wait for connection ...')\n # tctimeClient, addr = tctime.accept()\n # print(\"Connection from :\", addr)\n # while True:\n # data = tctimeClient.recv(buffsize)\n # data = str(binascii.b2a_hex(data))[2:-1]\n # print('Pre-link request:', data)\n # break\n # remessage = binascii.a2b_hex(ResponseStr(data))\n # sent = tctimeClient.send(remessage)\n # while True:\n # data = tctimeClient.recv(buffsize)\n # data = str(binascii.b2a_hex(data))[2:-1]\n # if data is not None:\n # print('received message:', data)\n # judgeRequest(data)\n # # break\n # tctimeClient.close()\n\n\n\n","sub_path":"Start.py","file_name":"Start.py","file_ext":"py","file_size_in_byte":12809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"89235044","text":"from decimal import *\n\ndef pidigits(trials):\n s = Decimal(1)\n denom = Decimal(1)\n res = Decimal(0)\n for i in range(trials):\n res += s*(Decimal(1)/denom)\n s *= -1\n denom += Decimal(2)\n return res*4\n\ndef pidigitssin(trials):\n import math\n prev = 3\n for i in range(trials):\n prev = prev+math.sin(prev)\n return prev\n\ndef pi():\n \"\"\"Compute Pi to the current precision.\n\n >>> print(pi())\n 3.141592653589793238462643383\n\n \"\"\"\n getcontext().prec += 2 # extra digits for intermediate steps\n three = Decimal(3) # substitute \"three=3.0\" for regular floats\n lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24\n while s != lasts:\n lasts = s\n n, na = n+na, na+8\n d, da = d+da, da+32\n t = (t * n) / d\n s += t\n getcontext().prec -= 2\n return +s \n\n\ngetcontext().prec = 51\npi_int = pi()\nprint(pi_int)\npi_str = str(pi_int/10)[2:]\npi_notes = ''\n\nfor d in pi_str:\n notes = ['b','C','D','E','F','G','A','B','c','d']\n notes = ['D0 ', 'Eb1 ','F1 ','G1 ', 'Ab1 ', 'Bb1 ', 'C2 ', 'D2 ', 'Eb2 ', 'F2 ']\n pi_notes += notes[int(d)]\nprint(pi_notes)\n","sub_path":"Pi Digits.py","file_name":"Pi Digits.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"90284292","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n:copyright:\n Lion Krischer (krischer@geophysik.uni-muenchen.de), 2013-2014\n:license:\n BSD 3-Clause (\"BSD New\" or \"BSD Simplified\")\n\"\"\"\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\n\nimport collections\nimport os\nimport sys\nimport time\nimport warnings\nimport weakref\n\nimport numpy as np\nimport obspy\n\nfrom .header import MSG_TAGS\n\n# Tuple holding a the body of a received message.\nReceivedMessage = collections.namedtuple(\"ReceivedMessage\", [\"data\"])\n# Tuple denoting a single worker.\nWorker = collections.namedtuple(\"Worker\", [\"active_jobs\",\n \"completed_jobs_count\"])\n\n\ndef get_multiprocessing():\n \"\"\"\n Helper function returning the multiprocessing module or the threading\n version of it.\n \"\"\"\n if is_multiprocessing_problematic():\n msg = (\"NumPy linked against 'Accelerate.framework'. Multiprocessing \"\n \"will be disabled. See \"\n \"https://github.com/obspy/obspy/wiki/Notes-on-Parallel-\"\n \"Processing-with-Python-and-ObsPy for more information.\")\n warnings.warn(msg)\n # Disable by replacing with dummy implementation using threads.\n import multiprocessing as mp\n from multiprocessing import dummy # NOQA\n multiprocessing = dummy\n multiprocessing.cpu_count = mp.cpu_count\n else:\n import multiprocessing # NOQA\n return multiprocessing\n\n\ndef is_multiprocessing_problematic():\n \"\"\"\n Return True if multiprocessing is known to have issues on the given\n platform.\n\n Mainly results from the fact that some BLAS/LAPACK implementations\n cannot deal with forked processing.\n \"\"\"\n # Handling numpy linked against accelerate.\n config_info = str([value for key, value in\n np.__config__.__dict__.items()\n if key.endswith(\"_info\")]).lower()\n\n if \"accelerate\" in config_info or \"veclib\" in config_info:\n return True\n elif \"openblas\" in config_info:\n # Most openBLAS can only operate with one thread...\n os.environ[\"OPENBLAS_NUM_THREADS\"] = \"1\"\n else:\n return False\n\n\ndef sizeof_fmt(num):\n \"\"\"\n Handy formatting for human readable filesize.\n\n From http://stackoverflow.com/a/1094933/1657047\n \"\"\"\n for x in [\"bytes\", \"KB\", \"MB\", \"GB\"]:\n if num < 1024.0 and num > -1024.0:\n return \"%3.1f %s\" % (num, x)\n num /= 1024.0\n return \"%3.1f %s\" % (num, \"TB\")\n\n\nclass AuxiliaryDataContainer(object):\n def __init__(self, data, data_type, tag, parameters):\n self.data = data\n self.data_type = data_type\n self.tag = tag\n self.parameters = parameters\n\n def __str__(self):\n return (\n \"Auxiliary Data of Type '{data_type}'\\n\"\n \"\\tTag: '{tag}'\\n\"\n \"\\tData shape: '{data_shape}', dtype: '{dtype}'\\n\"\n \"\\tParameters:\\n\\t\\t{parameters}\"\n .format(data_type=self.data_type, data_shape=self.data.shape,\n dtype=self.data.dtype, tag=self.tag,\n parameters=\"\\n\\t\\t\".join([\n \"%s: %s\" % (_i[0], _i[1]) for _i in\n sorted(self.parameters.items(), key=lambda x: x[0])])))\n\n\nclass AuxiliaryDataAccessor(object):\n \"\"\"\n Helper class facilitating access to the actual waveforms and stations.\n \"\"\"\n def __init__(self, auxiliary_data_type, asdf_data_set):\n # Use weak references to not have any dangling references to the HDF5\n # file around.\n self.__auxiliary_data_type = auxiliary_data_type\n self.__data_set = weakref.ref(asdf_data_set)\n\n def __getattr__(self, item):\n return self.__data_set()._get_auxiliary_data(\n self.__auxiliary_data_type, item.replace(\"___\", \".\"))\n\n def __dir__(self):\n __group = self.__data_set()._auxiliary_data_group[\n self.__auxiliary_data_type]\n return sorted([_i.replace(\".\", \"___\") for _i in __group.keys()])\n\n\nclass AuxiliaryDataGroupAccessor(object):\n \"\"\"\n Helper class to facilitate access to the auxiliary data types.\n \"\"\"\n def __init__(self, asdf_data_set):\n # Use weak references to not have any dangling references to the HDF5\n # file around.\n self.__data_set = weakref.ref(asdf_data_set)\n\n def __getattr__(self, item):\n __auxiliary_data_group = self.__data_set()._auxiliary_data_group\n if item not in __auxiliary_data_group:\n raise AttributeError\n return AuxiliaryDataAccessor(item, self.__data_set())\n\n def __dir__(self):\n __auxiliary_group = self.__data_set()._auxiliary_data_group\n return sorted(__auxiliary_group.keys())\n\n def __len__(self):\n return len(self.__dir__())\n\n\nclass StationAccessor(object):\n \"\"\"\n Helper class to facilitate access to the waveforms and stations.\n \"\"\"\n def __init__(self, asdf_data_set):\n # Use weak references to not have any dangling references to the HDF5\n # file around.\n self.__data_set = weakref.ref(asdf_data_set)\n\n def __getattr__(self, item):\n __waveforms = self.__data_set()._waveform_group\n if item.replace(\"_\", \".\") not in __waveforms:\n raise AttributeError\n return WaveformAccessor(item.replace(\"_\", \".\"), self.__data_set())\n\n def __dir__(self):\n __waveforms = self.__data_set()._waveform_group\n return sorted(set(\n [_i.replace(\".\", \"_\") for _i in __waveforms.keys()]))\n\n def __len__(self):\n return len(self.__dir__())\n\n\nclass WaveformAccessor(object):\n \"\"\"\n Helper class facilitating access to the actual waveforms and stations.\n \"\"\"\n def __init__(self, station_name, asdf_data_set):\n # Use weak references to not have any dangling references to the HDF5\n # file around.\n self.__station_name = station_name\n self.__data_set = weakref.ref(asdf_data_set)\n\n def __getattr__(self, item):\n if item != \"StationXML\":\n __station = self.__data_set()._waveform_group[self.__station_name]\n keys = [_i for _i in __station.keys()\n if _i.endswith(\"__\" + item)]\n traces = [self.__data_set()._get_waveform(_i) for _i in keys]\n return obspy.Stream(traces=traces)\n else:\n return self.__data_set()._get_station(self.__station_name)\n\n def __dir__(self):\n __station = self.__data_set()._waveform_group[self.__station_name]\n directory = []\n if \"StationXML\" in __station:\n directory.append(\"StationXML\")\n directory.extend([_i.split(\"__\")[-1]\n for _i in __station.keys()\n if _i != \"StationXML\"])\n return sorted(set(directory))\n\n\ndef is_mpi_env():\n \"\"\"\n Returns True if the current environment is an MPI environment.\n \"\"\"\n try:\n import mpi4py\n except ImportError:\n return False\n\n try:\n import mpi4py.MPI\n except ImportError:\n return False\n\n if mpi4py.MPI.COMM_WORLD.size == 1 and mpi4py.MPI.COMM_WORLD.rank == 0:\n return False\n return True\n\n\nclass StreamBuffer(collections.MutableMapping):\n \"\"\"\n Very simple key value store for obspy stream object with the additional\n ability to approximate the size of all stored stream objects.\n \"\"\"\n def __init__(self):\n self.__streams = {}\n\n def __getitem__(self, key):\n return self.__streams[key]\n\n def __setitem__(self, key, value):\n if not isinstance(value, obspy.Stream):\n raise TypeError\n self.__streams[key] = value\n\n def __delitem__(self, key):\n del self.__streams[key]\n\n def keys(self):\n return self.__streams.keys()\n\n def __len__(self):\n return len(self.__streams)\n\n def __iter__(self):\n return iter(self.__streams)\n\n def get_size(self):\n \"\"\"\n Try to approximate the size of all stores Stream object.\n \"\"\"\n cum_size = 0\n for stream in self.__streams.values():\n cum_size += sys.getsizeof(stream)\n for trace in stream:\n cum_size += sys.getsizeof(trace)\n cum_size += sys.getsizeof(trace.stats)\n cum_size += sys.getsizeof(trace.stats.__dict__)\n cum_size += sys.getsizeof(trace.data)\n cum_size += trace.data.nbytes\n # Add one percent buffer just in case.\n return cum_size * 1.01\n\n\n# Two objects describing a job and a worker.\nclass Job(object):\n __slots__ = \"arguments\", \"result\"\n\n def __init__(self, arguments, result=None):\n self.arguments = arguments\n self.result = result\n\n def __repr__(self):\n return \"Job(arguments=%s, result=%s)\" % (str(self.arguments),\n str(self.result))\n\n\nclass JobQueueHelper(object):\n \"\"\"\n A simple helper class managing job distribution to workers.\n \"\"\"\n def __init__(self, jobs, worker_names):\n \"\"\"\n Init with a list of jobs and a list of workers.\n\n :type jobs: List of arguments distributed to the jobs.\n :param jobs: A list of jobs that will be distributed to the workers.\n :type: list of integers\n :param workers: A list of usually integers, each denoting a worker.\n \"\"\"\n self._all_jobs = [Job(_i) for _i in jobs]\n self._in_queue = self._all_jobs[:]\n self._finished_jobs = []\n self._poison_pills_received = 0\n\n self._workers = {_i: Worker([], [0]) for _i in worker_names}\n\n self._starttime = time.time()\n\n def poison_pill_received(self):\n \"\"\"\n Increment the point pills received counter.\n \"\"\"\n self._poison_pills_received += 1\n\n def get_job_for_worker(self, worker_name):\n \"\"\"\n Get a job for a worker.\n\n :param worker_name: The name of the worker requesting work.\n \"\"\"\n job = self._in_queue.pop(0)\n self._workers[worker_name].active_jobs.append(job)\n return job.arguments\n\n def received_job_from_worker(self, arguments, result, worker_name):\n \"\"\"\n Call when a worker returned a job.\n\n :param arguments: The arguments the jobs was called with.\n :param result: The result of the job\n :param worker_name: The name of the worker.\n \"\"\"\n # Find the correct job.\n job = [_i for _i in self._workers[worker_name].active_jobs\n if _i.arguments == arguments]\n if len(job) == 0:\n msg = (\"MASTER: Job %s from worker %i not found. All jobs: %s\\n\" %\n (str(arguments), worker_name,\n str(self._workers[worker_name].active_jobs)))\n raise ValueError(msg)\n if len(job) > 1:\n raise ValueError(\"WTF %i %s %s\" % (\n worker_name, str(arguments),\n str(self._workers[worker_name].active_jobs)))\n job = job[0]\n job.result = result\n\n self._workers[worker_name].active_jobs.remove(job)\n self._workers[worker_name].completed_jobs_count[0] += 1\n self._finished_jobs.append(job)\n\n def __str__(self):\n workers = \"\\n\\t\".join([\n \"Worker %s: %i active, %i completed jobs\" %\n (str(key), len(value.active_jobs), value.completed_jobs_count[0])\n for key, value in self._workers.items()])\n\n return (\n \"Jobs (running %.2f seconds): \"\n \"queued: %i | finished: %i | total: %i\\n\"\n \"\\t%s\\n\" % (time.time() - self._starttime, len(self._in_queue),\n len(self._finished_jobs), len(self._all_jobs),\n workers))\n\n @property\n def queue_empty(self):\n return not bool(self._in_queue)\n\n @property\n def finished(self):\n return len(self._finished_jobs)\n\n @property\n def all_done(self):\n return len(self._all_jobs) == len(self._finished_jobs)\n\n @property\n def all_poison_pills_received(self):\n return len(self._workers) == self._poison_pills_received\n\n\ndef pretty_sender_log(rank, destination, tag, payload):\n import colorama\n prefix = colorama.Fore.RED + \"sent to \" + colorama.Fore.RESET\n _pretty_log(prefix, destination, rank, tag, payload)\n\n\ndef pretty_receiver_log(source, rank, tag, payload):\n import colorama\n prefix = colorama.Fore.GREEN + \"received from\" + colorama.Fore.RESET\n _pretty_log(prefix, rank, source, tag, payload)\n\n\ndef _pretty_log(prefix, first, second, tag, payload):\n import colorama\n\n colors = (colorama.Back.WHITE + colorama.Fore.MAGENTA,\n colorama.Back.WHITE + colorama.Fore.BLUE,\n colorama.Back.WHITE + colorama.Fore.GREEN,\n colorama.Back.WHITE + colorama.Fore.YELLOW,\n colorama.Back.WHITE + colorama.Fore.BLACK,\n colorama.Back.WHITE + colorama.Fore.RED,\n colorama.Back.WHITE + colorama.Fore.CYAN)\n\n tag_colors = (\n colorama.Fore.RED,\n colorama.Fore.GREEN,\n colorama.Fore.BLUE,\n colorama.Fore.YELLOW,\n colorama.Fore.MAGENTA,\n )\n\n # Deterministic colors also on Python 3.\n msg_tag_keys = sorted(MSG_TAGS.keys(), key=lambda x: str(x))\n tags = [i for i in msg_tag_keys if isinstance(i, (str, bytes))]\n\n tag = MSG_TAGS[tag]\n tag = tag_colors[tags.index(tag) % len(tag_colors)] + tag + \\\n colorama.Style.RESET_ALL\n\n first = colorama.Fore.YELLOW + \"MASTER \" + colorama.Fore.RESET \\\n if first == 0 else colors[first % len(colors)] + \\\n (\"WORKER %i\" % first) + colorama.Style.RESET_ALL\n second = colorama.Fore.YELLOW + \"MASTER \" + colorama.Fore.RESET \\\n if second == 0 else colors[second % len(colors)] + \\\n (\"WORKER %i\" % second) + colorama.Style.RESET_ALL\n\n print(\"%s %s %s [%s] -- %s\" % (first, prefix, second, tag, str(payload)))\n","sub_path":"pyasdf/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":13985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"616311081","text":"# -*- coding: utf-8 -*- \n__author__ = 'zhougy'\n__date__ = '2018/7/11 上午10:03' \n\nfrom django.shortcuts import render, HttpResponseRedirect\nfrom .models import Tag, Art\nfrom django.db.models import Q\n\n'''\n页面搜索功能:\n\n 接口URL: /art/search?key=XXX&page=1\n\n 方法:GET\n\n 输入参数说明:\n\n key: 搜索的关键词\n\n page: 获取第几页\n\n 输出:\n\n 渲染搜索列表页面\n'''\n\n\n\ndef SearchHandler(request):\n\tkey = request.GET.get(\"key\", \"\") ##获取输入参数key对应的值,默认为空\n\tif key == \"\":\n\t\treturn HttpResponseRedirect(\"/art/index\")\n\telse:\n\t\tpage = request.GET.get(\"page\", 1)\n\t\tpage = int(page)\n\t\t# 查询数据,或操作\n\t\tart_sets = Art.objects.filter(Q(a_title__contains=str(key))\n\t\t\t\t\t\t\t\t\t | Q(a_content__contains=str(key))\n\t\t\t\t\t\t\t\t\t | Q(a_info__contains=str(key))).distinct()\n\t\t# 查询数据,与操作\n\t\t# mdict = {\n\t\t# 'a_title':str(key),\n\t\t# 'a_content':str(key)\n\t\t# }\n\t\t# Art.objects.filter(mdict)\n\n\t\ttotal = art_sets.count()\n\tshownum = 10\n\timport math\n\tpagenum = int(math.ceil(total / shownum))\n\tif page < 1:\n\t\treturn HttpResponseRedirect(request.path + \"?page=%d&key=%s\" % (1, key))\n\tif (total > 0) and (page > pagenum):\n\t\treturn HttpResponseRedirect(request.path + \"?page=%d&key=%s\" % (pagenum, key))\n\n\tif total == 0:\n\t\tcontext = dict(\n\t\t\tpagenum=1,\n\t\t\ttotal=0,\n\t\t\tprev=1,\n\t\t\tnext=1,\n\t\t\tpagerange=range(1, 2),\n\t\t\tdata=[],\n\t\t\turl=request.path,\n\t\t\tkey=key,\n\t\t\tpage=1\n\t\t)\n\t\treturn render(request, \"search_handler.html\", context=context)\n\n\toffset = (page - 1) * shownum\n\n\tdata = art_sets[offset:(shownum + offset)]\n\tbtnnum = 5\n\tif btnnum > pagenum:\n\t\tfirstpage = 1\n\t\tlastpage = pagenum\n\telse:\n\t\tif page == 1:\n\t\t\tfirstpage = 1\n\t\t\tlastpage = btnnum\n\t\telse:\n\t\t\tfirstpage = page - 2\n\t\t\tlastpage = page + btnnum - 3\n\t\t\tif firstpage < 1:\n\t\t\t\tfirstpage = 1\n\t\t\tif lastpage > pagenum:\n\t\t\t\tlastpage = pagenum\n\tprev = page - 1\n\tnext = page + 1\n\tif prev < 1:\n\t\tprev = 1\n\tif next > pagenum:\n\t\tnext = pagenum\n\tcontext = dict(\n\t\tpagenum=pagenum,\n\t\ttotal=total,\n\t\tprev=prev,\n\t\tnext=next,\n\t\tpagerange=range(firstpage, lastpage + 1),\n\t\tdata=data,\n\t\turl=request.path,\n\t\tkey=key,\n\t\tpage=page\n\t)\n\n\treturn render(request, \"search_handler.html\", context=context)","sub_path":"SH1802Django/apps/arts_app/search_handler.py","file_name":"search_handler.py","file_ext":"py","file_size_in_byte":2253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"486748304","text":"# -*- python -*-\nImport('env')\n\n# build info & packaging\n\nimport platform\narchitecture = platform.machine()\nsystem = platform.system()\nif system == 'Linux':\n dist = platform.linux_distribution(full_distribution_name=False)\n operating_system = dist[0] + dist[1]\nelif system == 'Darwin':\n dist = platform.mac_os()\n operating_system = system + dist[0]\nelif system == 'Windows':\n dist = platform.release()\n operating_system = system + dist\nelse:\n raise Exception('unsupported system: ' + system)\n\nfrom ConfigParser import ConfigParser\n\ncfg = ConfigParser()\ncfg.read('version.ini')\nver = {'major': cfg.get('DEFAULT', 'major'),\n 'minor': cfg.get('DEFAULT', 'minor'),\n 'revision': cfg.get('DEFAULT', 'revision'),\n 'language': cfg.get('DEFAULT', 'language'),\n 'platform': operating_system,\n 'architecture': architecture}\n\nfp = open(env.File('$BUILD_DIR/src/tablestore/core/impl/buildinfo.cpp.in').abspath)\ntempl = fp.read()\nfp.close()\nfp = open(env.File('$BUILD_DIR/src/tablestore/core/impl/buildinfo.cpp').abspath, 'w')\nfp.write(templ % ver)\n\ntarball_name = 'aliyun-tablestore-%(language)s-sdk-%(major)s.%(minor)s.%(revision)s-%(platform)s-%(architecture)s.tar.gz' % ver\nxs = [\n ('', '#version.ini'),\n ('lib/', ['$LIB_DIR/libtablestore_core.so',\n '$LIB_DIR/libtablestore_core_static.a',\n '$LIB_DIR/libtablestore_util.so',\n '$LIB_DIR/libtablestore_util_static.a']),\n ('include/tablestore/util/', env.Glob('$BUILD_DIR/src/tablestore/util/*.hpp')),\n ('include/tablestore/util/', env.Glob('$BUILD_DIR/src/tablestore/util/*.ipp')),\n ('include/tablestore/core/', env.Glob('$BUILD_DIR/src/tablestore/core/*.hpp')),\n ('include/tablestore/core/', env.Glob('$BUILD_DIR/src/tablestore/core/*.ipp'))]\nenv.Alias('PACK', env.tarball(tarball_name, xs))\n\nenv.addExtLib(['protobuf-lite', 'protobuf',\n 'ssl', 'crypto',\n 'rt',\n 'boost_system', 'boost_thread', 'boost_chrono'])\nenv.subDir('test')\nenv.subDir('src')\nenv.subDir('examples')\n\n","sub_path":"SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":2062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"458333817","text":"import re\nimport os\nimport cv2\nimport pdb\nimport sys\nimport argparse\nimport pandas as pd\nimport tensorflow as tf\n\n\nfrom termcolor import cprint\nfrom model_pipeline_utils.data_pipeline import read_json_file\nfrom model_pipeline_utils.train_model_utils import show_image\nfrom model_pipeline_utils.prediction_functions import interactive_check_predictions, get_appropriate_prediction_fn\n\n\ndef load_graph(frozen_graph_filename):\n # We load the protobuf file from the disk and parse it to retrieve the\n # unserialized graph_def\n with tf.gfile.GFile(frozen_graph_filename, \"rb\") as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n # Then, we import the graph_def into a new Graph and returns it\n with tf.Graph().as_default() as graph:\n # The name var will prefix every op/nodes in your graph\n # Since we load everything in a new graph, this is not needed\n tf.import_graph_def(graph_def, name=\"prefix\")\n return graph\n\n\ndef main(graph_dir, config_file, frozen_graph_names, test_data_dir, output_func, output_labels):\n output_tensor_names = read_json_file(\"data/model_output_config_{}.json\".format(graph_dir))[\"output\"]\n for graph in frozen_graph_names:\n # We use our \"load_graph\" function\n graph = load_graph('data/graphs/{}/{}.pb'.format(graph_dir, graph))\n # We can verify that we can access the list of operations in the graph\n for op in graph.get_operations():\n print(op.name)\n # We access the input and output nodes\n image_batch = graph.get_tensor_by_name('prefix/image_batch:0')\n is_training = graph.get_tensor_by_name('prefix/is_training/input:0')\n final_dropout_rate = graph.get_tensor_by_name('prefix/final_dropout_rate/input:0')\n input_dims = read_json_file(config_file)[\"input_dims\"]\n preds = graph.get_tensor_by_name('prefix/prediction:0')\n softmax_tensor = graph.get_tensor_by_name('prefix/softmax_tensor:0')\n # Don't need this but oh well\n # softmax_tensor = graph.get_tensor_by_name(\"prefix/softmax_tensor:0\")\n test_predictions, test_ids = [], []\n with tf.Session(graph=graph) as sess:\n # Note: we don't nee to initialize/restore anything\n # There is no Variables in this graph, only hardcoded constants\n for idx, image in enumerate(os.listdir(test_data_dir)):\n # Image gets read in as bgr - need to convert it to rgb\n img = cv2.cvtColor(cv2.imread(os.path.join(test_data_dir, image)), cv2.COLOR_BGR2RGB)\n img = cv2.resize(img, (input_dims[1], input_dims[0]))\n img = img / 255.0\n image_with_batch = img.reshape((1,) + img.shape)\n # Cat is 0,1 (s0ftmax tensor), or 1 (predictions)\n test_prediction = sess.run([preds, softmax_tensor], feed_dict={image_batch: image_with_batch, is_training: False, final_dropout_rate: 0})\n test_id = int(re.match(r'\\d{1,999999999}', image).group())\n test_predictions.append(test_prediction)\n test_ids.append(test_id)\n print(\"Finished image {}/{}\".format(idx, len(os.listdir(test_data_dir))), end=\"\\r\")\n # To interactively go through some predictions, uncomment these lines:\n # interactive_check_predictions(img, prediction)\n prediction_output_fn = get_appropriate_prediction_fn(output_func)\n prediction_output_fn(test_predictions, test_ids, output_labels)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--graph-dir\", default=None, help=\"Directory graph is stored in -> data/graphs/\")\n parser.add_argument('--config-file', type=str, default='data/tfrecord_config.json', help='Location of tfrecord_config.json - defaults to the same directory as train_model.py')\n parser.add_argument(\"--frozen-graph-names\", default=\"data/graphs/frozen_model.pb\", type=str, help=\"Frozen model file(s) to import -> data/graphs//\")\n parser.add_argument(\"--test-data-dir\", default=None, help=\"Full path to test data directory\")\n parser.add_argument(\"--output-func\", default=None, help=\"Name of function to create prediction(s)\")\n parser.add_argument(\"--output-labels\", default=None, help=\"Name of the keys in the prediction csv(s)/json(s)\")\n args = parser.parse_args()\n main(args.graph_dir, args.config_file, args.frozen_graph_names.split(\",\"), args.test_data_dir, args.output_func, args.output_labels.split(','))\n\n# Example: python3 make_predictions.py --graph-dir cat_dog_cnn_desktop --frozen-graph-names model_10,model_12 --test-data-dir '/home/michael/hard_drive/datasets/dogs_vs_cats_data/test' --output-func cat_dog_classifier_output --output-labels id,label","sub_path":"model_pipeline_template/make_predictions.py","file_name":"make_predictions.py","file_ext":"py","file_size_in_byte":4830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"39845400","text":"from Database.oracle import Oracle\r\nfrom config_file import config_na1 as database\r\nimport config_file as cf\r\nfrom Graphics.diagram_layout_maker import Diagramm_Layout_Maker as diagram_layout\r\nimport datetime\r\nimport numpy as np\r\nfrom Analysis.fitting import fit_1D_data, filter_relevant, funcs\r\nfrom Tools.date_tools import find_next_weekday\r\nimport xlwt\r\nimport Birnbaum_Reporter as br\r\nimport BB_Ticketforecast as btf\r\n\r\n\r\n\"\"\"\r\nName: BB-Feldtickets\r\nPurpose: Get temporal distribution of Field Tickets caused by Birnbaum. Mainly uses functions from Birnbaum_Reporter.py\r\nOutput: - PDF with diagram of temporal distribution of Birnbaum Feldtickets\r\nTables used for the Report: - tickets\r\n - tickets_undisclosed (only needed because of receiver-info)\r\n - map_uep_tpop\r\n - kunden_grundstuecke\r\n - grundstuecke\r\n - SH.Birnbaum (Table containing: Region, Grussz, TV_POP, NEL-ID (netzelement-id of TV-POP), Datum (date when TV-POP is birnbaumed), KW, Frequenz, WES (according to Planung)\r\n - $User.Birnbaumtickets (Table created for this report: contains all the relevant ticketdata within +-30d of Birnbaum event for every TV-POP \r\n - SH.uep_hude (table containing ueps that have to be treated as a virtual birnbaum evennt because they were switched to another TV-POP). Hude is the name of one (the first) of these villages\r\n\r\n\"\"\"\r\n\r\n\r\nif __name__ == '__main__':\r\n oracle = Oracle()\r\n monitoring_period = 30\r\n dialay = diagram_layout()\r\n dialay.set_defaults(defaultset='powerpoint') # set default layout\r\n TPOPs = br.get_TPOP_list()\r\n # br.create_Tickettable(days_plus=50, days_minus=30)\r\n\r\n # Threshold: only regard TV-POPs with more KAD-customers than here\r\n KAD_thr = 120000\r\n\r\n print(TPOPs)\r\n baseline_g = []\r\n baseline_w = []\r\n baseline_g = []\r\n baseline_mo = []\r\n baseline_tu = []\r\n baseline_we = []\r\n baseline_th = []\r\n baseline_fr = []\r\n baseline_sa = []\r\n baseline_su = []\r\n\r\n baseline_g_now = []\r\n baseline_w_now = []\r\n baseline_g_now = []\r\n baseline_mo_now = []\r\n baseline_tu_now = []\r\n baseline_we_now = []\r\n baseline_th_now = []\r\n baseline_fr_now = []\r\n baseline_sa_now = []\r\n baseline_su_now = []\r\n\r\n KAD = []\r\n tickets = []\r\n tickets_now = []\r\n for row in TPOPs: # first step: get basic numbers (baselines etc.) per TV-POP\r\n # Get baselines and tickets for all new TV-POPs \r\n if row[3] > datetime.datetime(2012, 8, 15, 0, 0) and row[3] < datetime.datetime(2012, 9, 6, 0, 0) and row[6] >= KAD_thr:\r\n bsd = row[3] - datetime.timedelta(30)\r\n bsdate = str(bsd.day) + \".\" + str(bsd.month) + \".\" + str(bsd.year)\r\n edate = row[3] + datetime.timedelta(30)\r\n eddate = str(edate.day) + \".\" + str(edate.month) + \".\" + str(edate.year)\r\n bdate = str(row[3].day) + \".\" + str(row[3].month) + \".\" + str(row[3].year)\r\n KAD += [row[6]]\r\n avg, av_mo, av_tu, av_we, av_th, av_fr, av_sa, av_su, av_wd = btf.get_avg_Ticketzahl_stat(\r\n Region=str(row[1]),\r\n TV_pop=row[2],\r\n startdate=bsdate,\r\n enddate=bdate,\r\n Ticketart=\"Feldticket\",\r\n Dienstkategorie=['KAA', 'KAD', 'NTF', 'VOD', 'HDW'],\r\n ABE='')\r\n baseline_g_now += [avg]\r\n baseline_mo_now += [av_mo]\r\n baseline_tu_now += [av_tu]\r\n baseline_we_now += [av_we]\r\n baseline_th_now += [av_th]\r\n baseline_fr_now += [av_fr]\r\n baseline_sa_now += [av_sa]\r\n baseline_su_now += [av_su]\r\n sd = str(row[3].day) + '.' + str(row[3].month) + '.' + str(row[3].year)\r\n dd = row[3] + datetime.timedelta(monitoring_period)\r\n ed = str(dd.day) + '.' + str(dd.month) + '.' + str(dd.year)\r\n tickets_now += [br.get_Tickets(TV_pop=row[2], startdate=bsdate, enddate=ed, Ticketart='Feldticket',\r\n Dienstkategorie=[\"KAA\", \"KAD\", \"VOD\", \"HDW\", \"NTF\"],\r\n ab_st1='', ab_st2='', ABE='', period='DDD')]\r\n\r\n # Get baselines and tickets for TV-POPs that have been birnbaumed before\r\n if row[3] <= datetime.datetime(2012, 8, 1, 0, 0) and row[3] > datetime.datetime(2012, 7, 1, 0, 0) and row[6] >= 10000:\r\n bsd = row[3] - datetime.timedelta(30)\r\n bsdate = str(bsd.day) + \".\" + str(bsd.month) + \".\" + str(bsd.year)\r\n edate = row[3] + datetime.timedelta(30)\r\n eddate = str(edate.day) + \".\" + str(edate.month) + \".\" + str(edate.year)\r\n bdate = str(row[3].day) + \".\" + str(row[3].month) + \".\" + str(row[3].year)\r\n KAD += [row[6]]\r\n avg, av_mo, av_tu, av_we, av_th, av_fr, av_sa, av_su, av_wd = btf.get_avg_Ticketzahl_stat(\r\n Region=str(row[1]),\r\n TV_pop=row[2],\r\n startdate=bsdate,\r\n enddate=bdate,\r\n Ticketart=\"Feldticket\",\r\n Dienstkategorie=['KAA', 'KAD', 'NTF', 'VOD', 'HDW'],\r\n ABE='')\r\n baseline_g += [avg]\r\n baseline_mo += [av_mo]\r\n baseline_tu += [av_tu]\r\n baseline_we += [av_we]\r\n baseline_th += [av_th]\r\n baseline_fr += [av_fr]\r\n baseline_sa += [av_sa]\r\n baseline_su += [av_su]\r\n sd = str(row[3].day) + '.' + str(row[3].month) + '.' + str(row[3].year)\r\n dd = row[3] + datetime.timedelta(monitoring_period)\r\n ed = str(dd.day) + '.' + str(dd.month) + '.' + str(dd.year)\r\n tickets += [br.get_Tickets(TV_pop=row[2], startdate=bsdate, enddate=ed, Ticketart='Feldticket',\r\n Dienstkategorie=[\"KAA\", \"KAD\", \"VOD\", \"HDW\", \"NTF\"],\r\n ab_st1='', ab_st2='', ABE='', period='DDD')]\r\n\r\n\r\n rel_arr = []\r\n re_arr = []\r\n rel_arr_now = []\r\n re_arr_now = []\r\n\r\n \"\"\" Calculate quotient of Tickets and baseline (=expected value) for that weekday\r\n Got to do this for the old and new TV-POPs separately \r\n \"\"\"\r\n for i in range(len(baseline_g)):\r\n dummy = []\r\n for j in range(len(tickets[i][0])):\r\n if find_next_weekday(tickets[i][0][j], 1) == tickets[i][0][j]:\r\n bl = baseline_mo[i]\r\n elif find_next_weekday(tickets[i][0][j], 2) == tickets[i][0][j]:\r\n bl = baseline_tu[i]\r\n elif find_next_weekday(tickets[i][0][j], 3) == tickets[i][0][j]:\r\n bl = baseline_we[i]\r\n elif find_next_weekday(tickets[i][0][j], 4) == tickets[i][0][j]:\r\n bl = baseline_th[i]\r\n elif find_next_weekday(tickets[i][0][j], 5) == tickets[i][0][j]:\r\n bl = baseline_fr[i]\r\n elif find_next_weekday(tickets[i][0][j], 6) == tickets[i][0][j]:\r\n bl = baseline_sa[i]\r\n elif find_next_weekday(tickets[i][0][j], 7) == tickets[i][0][j]:\r\n bl = baseline_su[i]\r\n #bl = baseline_g[i]\r\n\r\n if bl == 0:\r\n print(bl)\r\n print(tickets[i][0][j])\r\n bl = 1\r\n dummy += [tickets[i][1][j] / float(bl)]\r\n\r\n rel_arr += [dummy]\r\n\r\n for i in range(len(baseline_g_now)):\r\n dummy = []\r\n for j in range(len(tickets_now[i][0])):\r\n if find_next_weekday(tickets_now[i][0][j], 1) == tickets_now[i][0][j]:\r\n bl_now = baseline_mo_now[i]\r\n elif find_next_weekday(tickets_now[i][0][j], 2) == tickets_now[i][0][j]:\r\n bl_now = baseline_tu_now[i]\r\n elif find_next_weekday(tickets_now[i][0][j], 3) == tickets_now[i][0][j]:\r\n bl_now = baseline_we_now[i]\r\n elif find_next_weekday(tickets_now[i][0][j], 4) == tickets_now[i][0][j]:\r\n bl_now = baseline_th_now[i]\r\n elif find_next_weekday(tickets_now[i][0][j], 5) == tickets_now[i][0][j]:\r\n bl_now = baseline_fr_now[i]\r\n elif find_next_weekday(tickets_now[i][0][j], 6) == tickets_now[i][0][j]:\r\n bl_now = baseline_sa_now[i]\r\n elif find_next_weekday(tickets_now[i][0][j], 7) == tickets_now[i][0][j]:\r\n bl_now = baseline_su_now[i]\r\n #bl_now = baseline_g_now[i]\r\n\r\n if bl_now == 0:\r\n print(bl_now)\r\n print(tickets_now[i][0][j])\r\n bl_now = 1\r\n dummy += [tickets_now[i][1][j] / float(bl_now)]\r\n\r\n rel_arr_now += [dummy]\r\n\r\n\r\n t_p_d = []\r\n for i in range(len(rel_arr[0])):\r\n dummy = []\r\n for j in range(len(rel_arr)):\r\n dummy += [rel_arr[j][i]]\r\n t_p_d += [dummy]\r\n\r\n\r\n narr = np.array(t_p_d)\r\n average = []\r\n stddev = []\r\n dx = []\r\n for i in range(len(narr)):\r\n average += [np.average(narr[i])]\r\n stddev += [np.std(narr[i])]\r\n dx += [i - 30]\r\n print(\"Tag \" + str(i - 30) + \", Avg: \" + str(average[i]) + \", stddev: \" + str(stddev[i]))\r\n\r\n\r\n t_p_d_now = []\r\n for i in range(len(rel_arr_now[0])):\r\n dummy = []\r\n for j in range(len(rel_arr_now)):\r\n dummy += [rel_arr_now[j][i]]\r\n t_p_d_now += [dummy]\r\n\r\n\r\n narr_now = np.array(t_p_d_now)\r\n average_now = []\r\n stddev_now = []\r\n dx_now = []\r\n print(narr_now)\r\n for i in range(len(narr_now)):\r\n dummy = []\r\n for j in range(len(narr_now[i])):\r\n if (narr_now[i][j] > 0) or (narr_now[i][j] == 0 and j < len(narr_now[i]) - 1 and narr_now[i][j + 1] > 0):\r\n dummy += [narr_now[i][j]]\r\n average_now += [np.average(dummy)]\r\n stddev_now += [np.std(dummy)]\r\n dx_now += [i - 30]\r\n print(\"Tag \" + str(i - 30) + \", Avg: \" + str(average_now[i]) + \", stddev: \" + str(stddev_now[i]))\r\n\r\n dialay.add_lineplot(x=[dx, dx_now],\r\n y=[average, average_now],\r\n yerr=[stddev, stddev_now],\r\n ylabel=\"Anzahl Feldtickets / Baseline\",\r\n xlabel=\"Tage vor/nach Birnbaum\",\r\n title=\"Relativer Feldticketverlauf Birnbaum \",\r\n labels=[\"TV-POPs im Juli\", \"TV-POP Muenchen\"])\r\n\r\n dialay.save(save='BirnbaumFeldticketforecast', show=True)\r\n\r\n","sub_path":"naos-python/Source/SH/Birnbaum/BB_Feldtickets.py","file_name":"BB_Feldtickets.py","file_ext":"py","file_size_in_byte":10734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"523233341","text":"import pygame, random, time, sys\n\npygame.init()\nm = 80\nImgbody = pygame.transform.scale(pygame.image.load('img/gamecho.png'), (m, m))\nImgbhead = pygame.transform.scale(pygame.image.load('img/tao.jpg'), (m, m))\nImgfood = pygame.transform.scale(pygame.image.load('img/choghe.jpg'), (m, m))\n\ngameSurFace = pygame.display.set_mode((1500, 800))\npygame.display.set_caption('Game chó̉')\n# mau sac\nred = pygame.Color(255, 0, 0)\nblue = pygame.Color(65, 105, 255)\nblack = pygame.Color(0, 0, 0)\nwhite = pygame.Color(255, 255, 255)\ngray = pygame.Color(128, 128, 128)\n# khai baos biến\nsnakepos = [400, 320]\nsnakebody = [[400, 320], [240, 160], [80, 0]]\nfoodx = random.randrange(1, 15)\nfoody = random.randrange(1, 5)\nif foodx % 2 != 0: foodx += 1\nif foody % 2 != 0: foody += 1\nfoodpos = [foodx * 80, foody * 80]\nfoodflat = True\ndirection = \"RIGHT\"\nchangeto = direction\nscore = 0\n\n\ndef game_over():\n print(\"out\")\n gfont = pygame.font.SysFont('consolas', 40)\n gsurf = gfont.render('Game Over!', True, red)\n grect = gsurf.get_rect()\n grect.midtop(360, 150)\n gameSurFace.blit(gsurf, grect)\n show_score(0)\n pygame.display.flip()\n time.sleep(5)\n pygame.quit()\n sys.exit()\n\n\ndef show_score(choice=1):\n sfont = pygame.font.SysFont('consolas', 30)\n ssurf = sfont.render(' Bat Cho:{0}'.format(score), True, black)\n srect = ssurf.get_rect()\n if choice == 1:\n srect.midtop = (70, 20)\n else:\n srect.midtop = (360, 230)\n gameSurFace.blit(ssurf, srect)\n\n\nwhile True:\n pygame.time.delay(200)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n if event.type == pygame.KEYDOWN:\n print(event.type)\n if event.key == pygame.K_RIGHT:\n print(\"Right\")\n changeto = 'RIGHT'\n if event.key == pygame.K_LEFT:\n print(\"left\")\n changeto = 'LEFT'\n if event.key == pygame.K_UP:\n print(\"up\")\n changeto = 'UP'\n if event.key == pygame.K_DOWN:\n print(\"down\")\n changeto = 'DOWN'\n if event.key == pygame.K_ESCAPE:\n pygame.event.post(pygame.evet.Event(pygame.QUIT))\n\n # huong di\n if changeto == 'RIGHT' and not direction == 'LEFT':\n direction = 'RIGHT'\n if changeto == 'LEFT' and not direction == 'RIGHT':\n direction = 'LEFT'\n if changeto == 'UP' and not direction == 'DOWN':\n direction = 'UP'\n if changeto == 'DOWN' and not direction == 'UP':\n direction = 'DOWN'\n\n # cap nhat vi tri moi\n if direction == 'RIGHT':\n snakepos[0] += m\n if direction == 'LEFT':\n snakepos[0] -= m\n if direction == 'UP':\n snakepos[1] -= m\n if direction == 'DOWN':\n snakepos[1] += m\n #\n snakebody.insert(0, list(snakepos))\n if snakepos[0] == foodpos[0] and snakepos[1] == foodpos[1]:\n score += 1\n foodflat = False\n else:\n snakebody.pop()\n\n # san sinh ra moi\n if foodflat == False:\n foodx = random.randrange(1, 15)\n foody = random.randrange(1, 5)\n if foodx % 2 != 0: foodx += 1\n if foody % 2 != 0: foody += 1\n foodpos = [foodx * 80, foody * 80]\n foodflat = True\n # cap nhat cua so len\n gameSurFace.fill(white)\n for pos in snakebody:\n gameSurFace.blit(Imgbody, pygame.Rect(pos[0], pos[1], m, m))\n gameSurFace.blit(Imgbhead, pygame.Rect(snakebody[0][0], snakebody[0][1], m, m))\n gameSurFace.blit(Imgfood, pygame.Rect(foodpos[0], foodpos[1], m, m))\n\n # cham canh bien\n # if snakepos[0] > 710 or snakepos[0] < 10:\n # game_over()\n # if snakepos[1] > 710 or snakepos[1] < 10:\n # game_over()\n # tu an chinh minh\n for b in snakebody[1:]:\n if snakepos[0] == b[0] and snakepos[1] == b[1]:\n game_over()\n # duong vien\n # pygame.draw.rect(gameSurFace, gray, (10, 10, 715, 455), 2)\n show_score()\n pygame.display.flip()\n","sub_path":"Code/Python/Gmaes/SnakeGame/GmaeCho.py","file_name":"GmaeCho.py","file_ext":"py","file_size_in_byte":4007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"445687308","text":"import json\nimport random\nimport os\nimport torchvision\nimport torch\nimport numpy as np\nfrom torch import nn\nimport time\nfrom pathlib import Path\nfrom torch.utils.data.dataloader import DataLoader\nfrom torchvision.transforms import Compose, ToTensor, Resize, Normalize,ToPILImage\nfrom pathlib import Path\n\nfrom model.inceptionv4 import Inceptionv4 \nfrom model.resnet import resnet34\nfrom utils import get_mean_std,Logger, worker_init_fn, get_lr,AverageMeter, calculate_accuracy,calculate_union_accuracy,find_badcase\n# from utils import AverageMeter, calculate_accuracy\nfrom dataset.val_dataloader import LmdbDataset_val\nfrom torch.utils.data._utils.collate import default_collate # 注意版本\n\n\n\n# def collate_fn(batch):\n# batch_clips, batch_targets,batch_keys = zip(*batch)\n\n# # batch_keys = [key for key in batch_keys]\n\n# return default_collate(batch_clips), default_collate(batch_targets), batch_keys\n\nmid_chexing = '/home/zhaoliu/car_brand/datasets_new/maps/mid_2_chexing'\nmid_label = '/home/zhaoliu/car_brand/datasets_new/maps/mid_2_label'\n\nmid_2_chexing = {}\nmid_2_label = {}\nfor line in open(mid_chexing,'r'):\n index,index1 = line.strip().split()\n mid_2_chexing[int(index)]=int(index1)\n\nfor line in open(mid_label,'r'):\n index,index1 = line.strip().split()\n mid_2_label[int(index1)]=index\n\ndef cal_chexing_acc(outputs, targets):\n n_correct_elems = 0\n\n assert len(outputs) == len(targets)\n outputs = outputs.numpy()\n outputs = np.argmax(outputs,1)\n\n outputs = outputs.tolist() \n chexing_targets = targets.numpy().tolist()\n\n chexing_targets = [mid_2_chexing[int(target)] for target in targets] # int\n chexing_outputs = [mid_2_chexing[int(output)] for output in outputs] # int\n\n\n\n for i in range(len(outputs)):\n\n if str(chexing_outputs[i]) == str(chexing_targets[i]):\n n_correct_elems+=1\n\n return n_correct_elems/len(outputs)\n\ndef cal_ori_acc(outputs, targets):\n n_correct_elems = 0\n\n assert len(outputs) == len(targets)\n outputs = outputs.numpy()\n outputs = np.argmax(outputs,1)\n\n outputs = outputs.tolist() \n chexing_targets = targets.numpy().tolist()\n\n ori_targets = []\n ori_outputs = []\n\n for target in chexing_targets:\n ori_t = mid_2_label[target][0]\n if ori_t == 'b':\n ori = 0\n elif ori_t == 's':\n ori = 1\n else:\n ori =2\n ori_targets.append(ori)\n\n for output in outputs:\n ori_o = mid_2_label[output][0]\n if ori_o == 'b':\n ori = 0\n elif ori_o == 's':\n ori = 1\n else:\n ori =2\n ori_outputs.append(ori)\n\n\n # ori_targets = [mid_2_chexing[int(target)] for target in targets] # int\n # ori_outputs = [mid_2_chexing[int(output)] for output in outputs] # int\n\n\n\n for i in range(len(outputs)):\n\n if str(ori_targets[i]) == str(ori_outputs[i]):\n n_correct_elems+=1\n\n return n_correct_elems/len(outputs)\n\ndef get_test_utils(test_path,keys_path):\n \n transform = []\n # normalize = get_normalize_method(opt.mean, opt.std, opt.no_mean_norm,\n # opt.no_std_norm)\n normalize = Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])\n \n resize = Resize(240)\n # transform.append(ToPILImage())\n transform.append(resize)\n\n transform.append(ToTensor())\n transform.append(normalize)\n transform = Compose(transform)\n \n test_data = LmdbDataset_val(test_path,transform,keys_path)\n print(len(test_data))\n\n\n test_loader = torch.utils.data.DataLoader(test_data,\n batch_size=512,\n shuffle=False,\n num_workers=16,\n # collate_fn = collate_fn,\n pin_memory=True)\n \n\n\n return test_loader\n\n\n\ndef test(model,test_loader):\n model.eval()\n\n batch_time = AverageMeter()\n data_time = AverageMeter()\n accuracies = AverageMeter()\n accuracies_chexing = AverageMeter()\n accuracies_ori = AverageMeter()\n end_time = time.time()\n\n\n print('----------开始测试----------')\n\n badcase_keys=[]\n with torch.no_grad():\n for i, (inputs, targets) in enumerate(test_loader):\n data_time.update(time.time() - end_time)\n\n\n\n # chexing = torch.tensor(targets)\n\n outputs= model(inputs)\n\n\n acc = calculate_accuracy(outputs, targets)\n acc_chexing = cal_chexing_acc(outputs,targets)\n acc_ori = cal_ori_acc(outputs,targets)\n\n accuracies_ori.update(acc_ori,inputs.size(0))\n accuracies_chexing.update(acc_chexing,inputs.size(0))\n accuracies.update(acc, inputs.size(0))\n\n batch_time.update(time.time() - end_time)\n end_time = time.time()\n\n\n print('test iter: {}/{}\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Data {data_time.val:.3f} ({data_time.avg:.3f})\\t'\n 'Acc_ori {acc_ori.val:.3f} ({acc_ori.avg:.3f})\\t'\n 'Acc_chexing {acc_chexing.val:.3f} ({acc_chexing.avg:.3f})\\t'\n 'Acc_mid {acc.val:.3f} ({acc.avg:.3f})'.format(\n i + 1,\n len(test_loader),\n batch_time=batch_time,\n data_time=data_time,\n acc_ori = accuracies_ori,\n acc_chexing=accuracies_chexing,\n acc=accuracies))\n\n\n\ndef resume_model(pth_path, model):\n print('loading checkpoint {} model'.format(pth_path))\n checkpoint = torch.load(pth_path, map_location='cpu')\n # assert arch == checkpoint['arch']\n\n if hasattr(model, 'module'):\n model.module.load_state_dict(checkpoint['state_dict'])\n else:\n model.load_state_dict(checkpoint['state_dict'])\n\n return model\n\ndef main():\n\n pth_path = '/home/zhaoliu/car_brand/car_mid/results_perspective/per_1/save_50.pth'\n \n # test_result=Path('/home/zhaoliu/car_class+ori/test_result')\n # test_path = '/home/zhaoliu/car_data/训练数据/4.9新加测试集/val_lmdb'\n # keys_path = '/home/zhaoliu/car_data/训练数据/4.9新加测试集/new_val.npy'\n test_path = \"/mnt/disk/zhaoliu_data/perspective/lmdb/test\"\n keys_path = '/home/zhaoliu/car_brand/perspective_data/prespective_test.npy'\n\n\n model = resnet34(num_classes=1189)\n model = resume_model(pth_path,model)\n test_loader = get_test_utils(test_path,keys_path)\n print('数据加载完毕...')\n test(model,test_loader)\n\nif __name__ == '__main__':\n main()\n","sub_path":"car_mid/infer.py","file_name":"infer.py","file_ext":"py","file_size_in_byte":6752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"9840604","text":"# -*- coding: utf-8 -*-\n# Copyright 2023 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# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfrom __future__ import annotations\n\nfrom typing import MutableMapping, MutableSequence\n\nimport proto # type: ignore\n\nfrom google.cloud.aiplatform_v1.types import feature_selector as gca_feature_selector\nfrom google.cloud.aiplatform_v1.types import types\nfrom google.protobuf import timestamp_pb2 # type: ignore\n\n\n__protobuf__ = proto.module(\n package=\"google.cloud.aiplatform.v1\",\n manifest={\n \"WriteFeatureValuesRequest\",\n \"WriteFeatureValuesPayload\",\n \"WriteFeatureValuesResponse\",\n \"ReadFeatureValuesRequest\",\n \"ReadFeatureValuesResponse\",\n \"StreamingReadFeatureValuesRequest\",\n \"FeatureValue\",\n \"FeatureValueList\",\n },\n)\n\n\nclass WriteFeatureValuesRequest(proto.Message):\n r\"\"\"Request message for\n [FeaturestoreOnlineServingService.WriteFeatureValues][google.cloud.aiplatform.v1.FeaturestoreOnlineServingService.WriteFeatureValues].\n\n Attributes:\n entity_type (str):\n Required. The resource name of the EntityType for the\n entities being written. Value format:\n ``projects/{project}/locations/{location}/featurestores/ {featurestore}/entityTypes/{entityType}``.\n For example, for a machine learning model predicting user\n clicks on a website, an EntityType ID could be ``user``.\n payloads (MutableSequence[google.cloud.aiplatform_v1.types.WriteFeatureValuesPayload]):\n Required. The entities to be written. Up to 100,000 feature\n values can be written across all ``payloads``.\n \"\"\"\n\n entity_type: str = proto.Field(\n proto.STRING,\n number=1,\n )\n payloads: MutableSequence[\"WriteFeatureValuesPayload\"] = proto.RepeatedField(\n proto.MESSAGE,\n number=2,\n message=\"WriteFeatureValuesPayload\",\n )\n\n\nclass WriteFeatureValuesPayload(proto.Message):\n r\"\"\"Contains Feature values to be written for a specific entity.\n\n Attributes:\n entity_id (str):\n Required. The ID of the entity.\n feature_values (MutableMapping[str, google.cloud.aiplatform_v1.types.FeatureValue]):\n Required. Feature values to be written, mapping from Feature\n ID to value. Up to 100,000 ``feature_values`` entries may be\n written across all payloads. The feature generation time,\n aligned by days, must be no older than five years (1825\n days) and no later than one year (366 days) in the future.\n \"\"\"\n\n entity_id: str = proto.Field(\n proto.STRING,\n number=1,\n )\n feature_values: MutableMapping[str, \"FeatureValue\"] = proto.MapField(\n proto.STRING,\n proto.MESSAGE,\n number=2,\n message=\"FeatureValue\",\n )\n\n\nclass WriteFeatureValuesResponse(proto.Message):\n r\"\"\"Response message for\n [FeaturestoreOnlineServingService.WriteFeatureValues][google.cloud.aiplatform.v1.FeaturestoreOnlineServingService.WriteFeatureValues].\n\n \"\"\"\n\n\nclass ReadFeatureValuesRequest(proto.Message):\n r\"\"\"Request message for\n [FeaturestoreOnlineServingService.ReadFeatureValues][google.cloud.aiplatform.v1.FeaturestoreOnlineServingService.ReadFeatureValues].\n\n Attributes:\n entity_type (str):\n Required. The resource name of the EntityType for the entity\n being read. Value format:\n ``projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entityType}``.\n For example, for a machine learning model predicting user\n clicks on a website, an EntityType ID could be ``user``.\n entity_id (str):\n Required. ID for a specific entity. For example, for a\n machine learning model predicting user clicks on a website,\n an entity ID could be ``user_123``.\n feature_selector (google.cloud.aiplatform_v1.types.FeatureSelector):\n Required. Selector choosing Features of the\n target EntityType.\n \"\"\"\n\n entity_type: str = proto.Field(\n proto.STRING,\n number=1,\n )\n entity_id: str = proto.Field(\n proto.STRING,\n number=2,\n )\n feature_selector: gca_feature_selector.FeatureSelector = proto.Field(\n proto.MESSAGE,\n number=3,\n message=gca_feature_selector.FeatureSelector,\n )\n\n\nclass ReadFeatureValuesResponse(proto.Message):\n r\"\"\"Response message for\n [FeaturestoreOnlineServingService.ReadFeatureValues][google.cloud.aiplatform.v1.FeaturestoreOnlineServingService.ReadFeatureValues].\n\n Attributes:\n header (google.cloud.aiplatform_v1.types.ReadFeatureValuesResponse.Header):\n Response header.\n entity_view (google.cloud.aiplatform_v1.types.ReadFeatureValuesResponse.EntityView):\n Entity view with Feature values. This may be\n the entity in the Featurestore if values for all\n Features were requested, or a projection of the\n entity in the Featurestore if values for only\n some Features were requested.\n \"\"\"\n\n class FeatureDescriptor(proto.Message):\n r\"\"\"Metadata for requested Features.\n\n Attributes:\n id (str):\n Feature ID.\n \"\"\"\n\n id: str = proto.Field(\n proto.STRING,\n number=1,\n )\n\n class Header(proto.Message):\n r\"\"\"Response header with metadata for the requested\n [ReadFeatureValuesRequest.entity_type][google.cloud.aiplatform.v1.ReadFeatureValuesRequest.entity_type]\n and Features.\n\n Attributes:\n entity_type (str):\n The resource name of the EntityType from the\n [ReadFeatureValuesRequest][google.cloud.aiplatform.v1.ReadFeatureValuesRequest].\n Value format:\n ``projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entityType}``.\n feature_descriptors (MutableSequence[google.cloud.aiplatform_v1.types.ReadFeatureValuesResponse.FeatureDescriptor]):\n List of Feature metadata corresponding to each piece of\n [ReadFeatureValuesResponse.EntityView.data][google.cloud.aiplatform.v1.ReadFeatureValuesResponse.EntityView.data].\n \"\"\"\n\n entity_type: str = proto.Field(\n proto.STRING,\n number=1,\n )\n feature_descriptors: MutableSequence[\n \"ReadFeatureValuesResponse.FeatureDescriptor\"\n ] = proto.RepeatedField(\n proto.MESSAGE,\n number=2,\n message=\"ReadFeatureValuesResponse.FeatureDescriptor\",\n )\n\n class EntityView(proto.Message):\n r\"\"\"Entity view with Feature values.\n\n Attributes:\n entity_id (str):\n ID of the requested entity.\n data (MutableSequence[google.cloud.aiplatform_v1.types.ReadFeatureValuesResponse.EntityView.Data]):\n Each piece of data holds the k requested values for one\n requested Feature. If no values for the requested Feature\n exist, the corresponding cell will be empty. This has the\n same size and is in the same order as the features from the\n header\n [ReadFeatureValuesResponse.header][google.cloud.aiplatform.v1.ReadFeatureValuesResponse.header].\n \"\"\"\n\n class Data(proto.Message):\n r\"\"\"Container to hold value(s), successive in time, for one\n Feature from the request.\n\n This message has `oneof`_ fields (mutually exclusive fields).\n For each oneof, at most one member field can be set at the same time.\n Setting any member of the oneof automatically clears all other\n members.\n\n .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields\n\n Attributes:\n value (google.cloud.aiplatform_v1.types.FeatureValue):\n Feature value if a single value is requested.\n\n This field is a member of `oneof`_ ``data``.\n values (google.cloud.aiplatform_v1.types.FeatureValueList):\n Feature values list if values, successive in\n time, are requested. If the requested number of\n values is greater than the number of existing\n Feature values, nonexistent values are omitted\n instead of being returned as empty.\n\n This field is a member of `oneof`_ ``data``.\n \"\"\"\n\n value: \"FeatureValue\" = proto.Field(\n proto.MESSAGE,\n number=1,\n oneof=\"data\",\n message=\"FeatureValue\",\n )\n values: \"FeatureValueList\" = proto.Field(\n proto.MESSAGE,\n number=2,\n oneof=\"data\",\n message=\"FeatureValueList\",\n )\n\n entity_id: str = proto.Field(\n proto.STRING,\n number=1,\n )\n data: MutableSequence[\n \"ReadFeatureValuesResponse.EntityView.Data\"\n ] = proto.RepeatedField(\n proto.MESSAGE,\n number=2,\n message=\"ReadFeatureValuesResponse.EntityView.Data\",\n )\n\n header: Header = proto.Field(\n proto.MESSAGE,\n number=1,\n message=Header,\n )\n entity_view: EntityView = proto.Field(\n proto.MESSAGE,\n number=2,\n message=EntityView,\n )\n\n\nclass StreamingReadFeatureValuesRequest(proto.Message):\n r\"\"\"Request message for\n [FeaturestoreOnlineServingService.StreamingFeatureValuesRead][].\n\n Attributes:\n entity_type (str):\n Required. The resource name of the entities' type. Value\n format:\n ``projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entityType}``.\n For example, for a machine learning model predicting user\n clicks on a website, an EntityType ID could be ``user``.\n entity_ids (MutableSequence[str]):\n Required. IDs of entities to read Feature values of. The\n maximum number of IDs is 100. For example, for a machine\n learning model predicting user clicks on a website, an\n entity ID could be ``user_123``.\n feature_selector (google.cloud.aiplatform_v1.types.FeatureSelector):\n Required. Selector choosing Features of the\n target EntityType. Feature IDs will be\n deduplicated.\n \"\"\"\n\n entity_type: str = proto.Field(\n proto.STRING,\n number=1,\n )\n entity_ids: MutableSequence[str] = proto.RepeatedField(\n proto.STRING,\n number=2,\n )\n feature_selector: gca_feature_selector.FeatureSelector = proto.Field(\n proto.MESSAGE,\n number=3,\n message=gca_feature_selector.FeatureSelector,\n )\n\n\nclass FeatureValue(proto.Message):\n r\"\"\"Value for a feature.\n\n This message has `oneof`_ fields (mutually exclusive fields).\n For each oneof, at most one member field can be set at the same time.\n Setting any member of the oneof automatically clears all other\n members.\n\n .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields\n\n Attributes:\n bool_value (bool):\n Bool type feature value.\n\n This field is a member of `oneof`_ ``value``.\n double_value (float):\n Double type feature value.\n\n This field is a member of `oneof`_ ``value``.\n int64_value (int):\n Int64 feature value.\n\n This field is a member of `oneof`_ ``value``.\n string_value (str):\n String feature value.\n\n This field is a member of `oneof`_ ``value``.\n bool_array_value (google.cloud.aiplatform_v1.types.BoolArray):\n A list of bool type feature value.\n\n This field is a member of `oneof`_ ``value``.\n double_array_value (google.cloud.aiplatform_v1.types.DoubleArray):\n A list of double type feature value.\n\n This field is a member of `oneof`_ ``value``.\n int64_array_value (google.cloud.aiplatform_v1.types.Int64Array):\n A list of int64 type feature value.\n\n This field is a member of `oneof`_ ``value``.\n string_array_value (google.cloud.aiplatform_v1.types.StringArray):\n A list of string type feature value.\n\n This field is a member of `oneof`_ ``value``.\n bytes_value (bytes):\n Bytes feature value.\n\n This field is a member of `oneof`_ ``value``.\n metadata (google.cloud.aiplatform_v1.types.FeatureValue.Metadata):\n Metadata of feature value.\n \"\"\"\n\n class Metadata(proto.Message):\n r\"\"\"Metadata of feature value.\n\n Attributes:\n generate_time (google.protobuf.timestamp_pb2.Timestamp):\n Feature generation timestamp. Typically, it\n is provided by user at feature ingestion time.\n If not, feature store will use the system\n timestamp when the data is ingested into feature\n store. For streaming ingestion, the time,\n aligned by days, must be no older than five\n years (1825 days) and no later than one year\n (366 days) in the future.\n \"\"\"\n\n generate_time: timestamp_pb2.Timestamp = proto.Field(\n proto.MESSAGE,\n number=1,\n message=timestamp_pb2.Timestamp,\n )\n\n bool_value: bool = proto.Field(\n proto.BOOL,\n number=1,\n oneof=\"value\",\n )\n double_value: float = proto.Field(\n proto.DOUBLE,\n number=2,\n oneof=\"value\",\n )\n int64_value: int = proto.Field(\n proto.INT64,\n number=5,\n oneof=\"value\",\n )\n string_value: str = proto.Field(\n proto.STRING,\n number=6,\n oneof=\"value\",\n )\n bool_array_value: types.BoolArray = proto.Field(\n proto.MESSAGE,\n number=7,\n oneof=\"value\",\n message=types.BoolArray,\n )\n double_array_value: types.DoubleArray = proto.Field(\n proto.MESSAGE,\n number=8,\n oneof=\"value\",\n message=types.DoubleArray,\n )\n int64_array_value: types.Int64Array = proto.Field(\n proto.MESSAGE,\n number=11,\n oneof=\"value\",\n message=types.Int64Array,\n )\n string_array_value: types.StringArray = proto.Field(\n proto.MESSAGE,\n number=12,\n oneof=\"value\",\n message=types.StringArray,\n )\n bytes_value: bytes = proto.Field(\n proto.BYTES,\n number=13,\n oneof=\"value\",\n )\n metadata: Metadata = proto.Field(\n proto.MESSAGE,\n number=14,\n message=Metadata,\n )\n\n\nclass FeatureValueList(proto.Message):\n r\"\"\"Container for list of values.\n\n Attributes:\n values (MutableSequence[google.cloud.aiplatform_v1.types.FeatureValue]):\n A list of feature values. All of them should\n be the same data type.\n \"\"\"\n\n values: MutableSequence[\"FeatureValue\"] = proto.RepeatedField(\n proto.MESSAGE,\n number=1,\n message=\"FeatureValue\",\n )\n\n\n__all__ = tuple(sorted(__protobuf__.manifest))\n","sub_path":"google/cloud/aiplatform_v1/types/featurestore_online_service.py","file_name":"featurestore_online_service.py","file_ext":"py","file_size_in_byte":15942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"357656041","text":"import db\nimport re\nimport datetime\nimport os\n\nfrom db.models import Entity, Transaction\n\ndatabase = db.Database()\nrunning_date = datetime.datetime.now()\n\ndef add_entity(type):\n entity = Entity()\n\n entity.name = input(\"Name: \")\n entity.value = float(input(\"Value: ₹\"))\n entity.type = type\n\n database.add_entity(entity)\n\ndef edit_entity():\n\n id = input(\"ID: \")\n entity = database.get_entity(id)\n\n newval = input(\"Enter New Value: \")\n if re.search('[a-zA-Z]', newval):\n # CONTAINS LETTERS, SO EDIT THE NAME\n entity.name = newval\n else:\n # ONLY CONTAINS NUMBERS, SO EDIT THE VALUE\n entity.value = float(newval)\n\n database.update_entity(entity)\n\ndef edit_transaction():\n id = int(input(\"ID: \"))\n transaction = database.get_transaction(id)\n\n while True:\n assets = database.get_entities(Entity.TYPE_ASSET)\n debts = database.get_entities(Entity.TYPE_DEBT)\n incomes = database.get_entities(Entity.TYPE_INCOME)\n expenses = database.get_entities(Entity.TYPE_EXPENSE)\n\n\n from_entities = assets + incomes + debts\n to_entities = assets + expenses + debts\n\n menu = '''\n--------------------\nEDIT TRANSACTION #{}\n--------------------\n\n{}\n\n[F]rom\n[T]o\n[D]ate\n[A]mount\n[C]omment\n[Q]Back\n[S]ave and Back\n\n\n>'''.format(\n id,\n str(transaction)\n )\n\n selection = input(menu)\n\n if selection.lower() == 'q':\n break\n elif selection.lower() == 'f':\n print(\"\\n-----------------\")\n print(\"FROM\")\n print(\"-----------------\\n\")\n\n for e in from_entities:\n print(str(e))\n\n transaction.from_entity = database.get_entity(input(\"> \"))\n \n elif selection.lower() == 't':\n print(\"\\n-----------------\")\n print(\"TO\")\n print(\"-----------------\\n\")\n\n for e in to_entities:\n print(str(e))\n\n transaction.to_entity = database.get_entity(input(\"> \"))\n\n elif selection.lower() == 'd':\n transaction.set_date_from_str(input(\"Date: dd-mm-yy: \"))\n\n elif selection.lower() == 'a':\n transaction.amount = float(input(\"New Amount: ₹\"))\n\n elif selection.lower() == 'c':\n transaction.comment = input(\"New Comment: \")\n\n elif selection.lower() == 's':\n database.update_transaction(transaction)\n break\n\n\n\n\n\n\n\n\ndef delete_entity():\n database.delete_entity(\n database.get_entity(\n input(\n \"ID: \"\n )\n )\n )\n\ndef add_transaction():\n\n\n assets = database.get_entities(Entity.TYPE_ASSET)\n debts = database.get_entities(Entity.TYPE_DEBT)\n incomes = database.get_entities(Entity.TYPE_INCOME)\n expenses = database.get_entities(Entity.TYPE_EXPENSE)\n\n\n from_entities = assets + incomes + debts\n to_entities = assets + expenses + debts\n\n print(\"\\n-----------------\")\n print(\"FROM\")\n print(\"-----------------\\n\")\n\n for e in from_entities:\n print(str(e))\n\n from_e = database.get_entity(input(\"> \"))\n\n\n print(\"\\n-----------------\")\n print(\"TO\")\n print(\"-----------------\\n\")\n\n for e in to_entities:\n print(str(e))\n\n to_e = database.get_entity(input(\"> \"))\n amount = float(input(\"Amount: ₹\"))\n comment = input(\"Comment: \")\n\n\n t = Transaction()\n t.from_entity = from_e\n t.to_entity = to_e\n t.amount = amount\n t.comment = comment\n t.set_date_from_str(input(\"Date: dd-mm-yy: \"))\n\n database.add_transaction(t)\n\n\n\n # INTELLIGENTLY UPDATE VALUES OF ENTITIES\n if from_e.type == Entity.TYPE_ASSET:\n from_e.value -= amount\n if to_e.type == Entity.TYPE_DEBT:\n to_e.value -= amount\n elif (to_e.type == Entity.TYPE_EXPENSE) or (to_e.type == Entity.TYPE_ASSET):\n to_e.value += amount\n \n if from_e.type == Entity.TYPE_INCOME:\n from_e.value += amount\n if to_e.type == Entity.TYPE_ASSET:\n to_e.value += amount\n elif to_e.type == Entity.TYPE_DEBT:\n to_e.value -= amount\n\n if from_e.type == Entity.TYPE_DEBT:\n if to_e.type == Entity.TYPE_ASSET:\n from_e.value += amount\n to_e.value += amount\n \n database.update_entity(from_e)\n database.update_entity(to_e)\n\ndef get_transaction():\n id = input(\"ID: \")\n t = database.get_transaction(id)\n\n print(str(t.from_entity))\n print(str(t.to_entity))\n print(t.amount)\n print(t.date)\n return t\n\ndef delete_transaction():\n database.delete_transaction(get_transaction())\n\n\n# ----------------MAIN STUFF-----------------------\ndef display_home():\n menu = '''\n\n-----------------------\nHOME\n-----------------------\n\n\nEnter a selection:\n\n[A]ssets\n[D]ebts\n[I]ncomes\n[E]xpenses\n[T]ransactions\n[S]tats\n[R]Export Data\n[B]Debug\n[Q]uit\n\n> '''\n \n while True:\n selection = input(menu)\n\n if selection.lower() == \"a\":\n display_entities(Entity.TYPE_ASSET)\n if selection.lower() == \"d\":\n display_entities(Entity.TYPE_DEBT)\n if selection.lower() == \"i\":\n display_entities(Entity.TYPE_INCOME)\n if selection.lower() == \"e\":\n display_entities(Entity.TYPE_EXPENSE)\n if selection.lower() == \"t\":\n display_transactions()\n if selection.lower() == \"s\":\n display_stats()\n if selection.lower() == \"r\":\n database.dump_database()\n if selection.lower() == \"b\":\n # database.switch_to_new_month()\n print(\"Nothing to see here. Move along.\")\n if selection.lower() == \"q\":\n database.dump_database()\n break\n\ndef display_stats():\n\n net_worth=database.get_net_worth()\n avg_monthly_exp=database.get_avg_monthly_expense()\n avg_monthly_income=database.get_avg_monthly_income()\n avg_monthly_net=database.get_avg_monthly_net()\n\n month = running_date.strftime(\"%B\")\n total_month_income = database.get_total_month_income(running_date.month)\n total_month_expense = database.get_total_month_expense(running_date.month)\n total_month_net = total_month_income-total_month_expense\n\n avg_daily_exp=database.get_avg_daily_expense() \n daily_inc=database.get_daily_income()\n daily_balance = round(daily_inc - avg_daily_exp , 2)\n\n\n stats = '''\n \n--------------------------------------------------------\nSTATS\n--------------------------------------------------------\n\nNet Worth:\\t\\t\\t₹{net_worth}\n\nAverage Monthly Income:\\t\\t₹{avg_monthly_income}\nAverage Monthly Expense:\\t₹{avg_monthly_exp}\nAverage Monthly Net:\\t\\t₹{avg_monthly_net}\n\nTotal {month} Income:\\t\\t₹{total_month_income}\nTotal {month} Expense:\\t\\t₹{total_month_expense}\nTotal {month} Net:\\t\\t₹{total_month_net}\n\nEquivalent Daily Income:\\t₹{daily_inc}\nAverage Daily Expense:\\t\\t₹{avg_daily_exp}\nDaily Net:\\t\\t\\t₹{daily_balance}\n\n--------------------------------------------------------\n\n[Q]Back\n\n> '''.format(\n net_worth=net_worth,\n avg_daily_exp=avg_daily_exp,\n avg_monthly_exp=avg_monthly_exp,\n avg_monthly_income=avg_monthly_income,\n avg_monthly_net=avg_monthly_net,\n daily_inc=daily_inc,\n daily_balance=daily_balance,\n month=month,\n total_month_income=total_month_income,\n total_month_expense=total_month_expense,\n total_month_net=total_month_net\n )\n\n while True:\n selection = input(stats)\n if selection.lower() == 'q':\n break\n\n\ndef display_entities(type):\n typestring = \"Yikes, this shouldn't be shwoing up...\"\n if type == Entity.TYPE_ASSET:\n typestring = \"ASSETS\"\n elif type == Entity.TYPE_DEBT:\n typestring = \"DEBTS\"\n elif type == Entity.TYPE_INCOME:\n typestring = \"INCOEMS\"\n elif type == Entity.TYPE_EXPENSE:\n typestring = \"EXPENSES\"\n while True:\n entities = database.get_entities(type)\n\n menu = '''\n\n-----------------------\n{}\n-----------------------\n\n'''.format(typestring)\n\n for e in entities:\n menu += str(e) + \"\\n\"\n\n menu += '''\n\n[A]dd\n[E]dit\n[D]elete\n[Q]Back\n\n> '''\n selection = input(menu)\n\n if selection.lower() == \"a\":\n add_entity(type)\n if selection.lower() == \"e\":\n edit_entity()\n if selection.lower() == \"d\":\n delete_entity()\n if selection.lower() == \"q\":\n break \n \n \n\ndef display_transactions():\n while True:\n transactions = database.get_transactions(datetime.datetime.now().month)\n menu = '''\n\n-----------------------\nTRANSACTIONS\n-----------------------\n\n'''\n prev_day = None\n for transaction in transactions:\n if transaction.date.day != prev_day:\n menu += \"\\n\"\n menu += str(transaction) + \"\\n\"\n prev_day = transaction.date.day\n\n menu += '''\n\n[A]dd\n[E]dit\n[D]elete\n[Q]Back\n\n> '''\n selection = input(menu)\n\n if selection.lower() == \"a\":\n add_transaction()\n if selection.lower() == \"e\":\n edit_transaction()\n if selection.lower() == \"d\":\n delete_transaction()\n if selection.lower() == \"q\":\n break\n\n\n\n\n# MAIN\n\n# CHECK IF DATE CHANGED\nnow = datetime.datetime.now()\nmonth_name = now.strftime(\"%B\")\n\nif not os.path.exists(\"2019/{}.xlsx\".format(month_name)):\n last_month_name = datetime.datetime.fromtimestamp(\n int(now.timestamp()) - (now.day + 1) * 24 * 60 * 60\n ).strftime(\"%B\")\n\n if os.path.exists(\"2019/{}.xlsx\".format(last_month_name)):\n print(\"\\n\\nSwitching from {} to {}...\\n\\n\".format(last_month_name, month_name))\n database.switch_to_new_month()\n\n\n# LAUNCH PROGRAM\ndisplay_home()","sub_path":"liquidity.py","file_name":"liquidity.py","file_ext":"py","file_size_in_byte":9827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"575532422","text":"from Structure import *\r\n\r\n\r\n\r\np6 = struct()\r\n\r\nnrNodes = 33 # Number of nodes\r\nlength = 500 # Length between\r\nh0 = length/100 # height at mid span\r\nx = linspace(0, length, nrNodes)\r\ny = (4*h0*(x/length))*(1-(x/length)) # curvature of beam\r\ny = zeros_like(x)\r\nfor i in range(0, nrNodes):\r\n if i == 0:\r\n p6.addNode(i + 1, array([0, 0, 1]), array([x[i], y[i]]))\r\n elif i == nrNodes-1:\r\n p6.addNode(i + 1, array([1, 0, 1]), array([x[i], y[i]]))\r\n else:\r\n p6.addNode(i + 1, array([1, 1, 1]), array([x[i], y[i]]))\r\n\r\npara = {'E': 1.0,\r\n 'A': 10000.0,\r\n 'I': 100000.0,\r\n 'nu': 0.0}\r\n\r\nfor i in range(0, nrNodes - 1):\r\n p6.addEle(i + 1, i + 1, i + 2, CurvedBeam_V2(params=para))\r\n\r\n# Assign loads\r\np6.addLoad(1, nrNodes, array([-1., 0., 0.]))\r\n\r\np6.updateElements()\r\n\r\n\r\np6.partitionK()\r\n\r\n\r\ntarget = array([nrNodes, array([-100, 0, 0])])\r\n\r\nstart_time = time.time()\r\nupath, load, s_hist, R_hist, det_hist = p6.solveArc(load=6, s_lim=500,nodeDis=target, la=0.2, alfa=0.0, data=True)\r\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\r\n\r\np6.plotStructure(deformed=True, mark=True)\r\n\r\nstart_time = time.time()\r\n\r\np6.partitionK()\r\n#print(p5.kff)\r\n#print(p5.rtot)\r\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\r\n\r\n\r\n\r\nnrEle = nrNodes -1\r\nmid = int(nrEle/2 * 3 + 1)\r\nquart_1 = int(nrEle/4 * 3 + 1)\r\nquart_3 = int(nrEle*3/4 * 3 + 1)\r\n\r\nprint(f'mid {mid}, quart {quart_1}, 3 quart {quart_3}')\r\n\r\nfig1 = plt.figure()\r\nax1 = fig1.add_subplot(111)\r\n#ax1.scatter(load[1::], det_hist[1::], color='b', label='$det[K]$ ')\r\nax1.plot(load[1::], det_hist[1::], color='b', label='$min(eig([Kff]))$ ')\r\nax1.plot([0, load[len(load)-1]], [0, 0], color='r')\r\nax1.plot([3.9478417604, 3.9478417604], [min(det_hist), max(det_hist)], label='True value straight beam')\r\n#ax1.semilogy(load[1::], det_hist[1::], color='b', label='$det[K]$ ')\r\nplt.title(f'Homework 6-4, {nrEle} elements straight beam')\r\nax1.set_xlabel('Load factor')\r\nax1.set_ylabel('Value')\r\n#ax1.set(ylim=(0, 1000))\r\nax1.legend()\r\n\r\nplt.show()","sub_path":"Assignments/Assignment6/CESG506 HW6_4.py","file_name":"CESG506 HW6_4.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"125487626","text":"#!/usr/bin/env python3.5\n''' Class to contain config data.\n'''\n\nimport sys\nimport json\nimport logging\n\nclass Config:\n ''' Contains user configuration for lootbot, loaded from a file specified at initialization.\n '''\n token = None\n clientid = None\n custom_messages = None\n def __init__(self, filename):\n ''' Try to load config data from file config.json.\n return True on success or False on failure.\n '''\n logging.info('Loading config from %s...', filename)\n try:\n with open(filename) as config:\n config = json.load(config)\n # Failure cases we want to catch: not being able to open the config file,\n # or not being able to read the opened config file as valid JSON data\n except (OSError, ValueError) as err:\n logging.error(err)\n sys.exit(1)\n # Load the Discord App Bot User Token (required)\n self.token = config.get('token')\n if not self.token:\n logging.error('No token found in config file\\n')\n sys.exit(1)\n # Try to load clientid\n self.clientid = config.get('clientid')\n if not self.clientid:\n logging.warning('No clientid found in config file\\n')\n # Try to load custom messages\n self.custom_messages = config.get('custom_messages')\n # Success\n logging.info('Config loaded successfully.')\n","sub_path":"lib/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"385119322","text":"'''\n[气球游戏]小Q在进行射击气球的游\n戏,如果小Q在连续T枪中打爆了所有颜\n色的气球,将得到一只QQ公仔作为奖\n励。(每种 颜色的气球至少被打爆一\n只)。这个游戏中有m种不同颜色的气\n球,编号1到m。小Q一共有n发子弹,\n然后连续开了n枪。小Q想知道在这n枪\n中,打爆所有颜色的气球最少用了连续\n几枪?\n输入描述:\n第一行两个空格间隔的整数数n,m。\nn<=1000000 m<=2000\n第二行一-共n个空格间隔的整数,分别表\n示每一枪打中的气球的颜色,0表示没打\n中任何颜色的气球。\n输出描述:\n一个整数表示小Q打爆所有颜色气球用\n的最少枪数。如果小Q无法在这n枪打爆\n所有颜色的气球,则输出-1\n示例\n输入:\n12 5\n2 531 32410543\n输出:\n6\n'''\n\n# #coding=utf-8\n# import sys \n# text = []\n# for line in sys.stdin:\n# text.append(line.split())\n# n = int(text[0][0])\n# m = int(text[0][1])\n# candidate = text[1]\n# # 转换为int方便后面处理\n# candidate = [int(candidate[i]) for i in range(n)]\n# # print(candidate)\n# # 构建候选序列 \n# dp = [-1 for i in range(m)]\n# min_len = 1000001\n# for i in range(n):\n# # 如果遇到未命中,直接清空\n# if candidate[i] == 0:\n# dp = [-1 for i in range(m)]\n# continue\n# # 记录当前打爆气球的索引\n# dp[(candidate[i])-1] = i\n# # 判断是否包含了打爆了所有气球\n# if not -1 in dp:\n# # 取出最小长度\n# min_len = min((max(dp) - min(dp)),min_len)\n# # print(dp)\n# # print('-------')\n# if min_len == 1000001:\n# # 未找到子列\n# print(-1)\n# else:\n# print(min_len+1)\n# # print('Hello,World!')\n\n\n\n\n# 3-16 https://www.acwing.com/problem/content/572/\n#coding=utf-8\n# 3-17 AC代码\n# 核心在于,双指针,气球记录个数就行,不用记录位置,记录位置每次要对list进行append和pop会超时\nimport sys \ntext = []\nfor line in sys.stdin:\n text.append(line.split())\nn = int(text[0][0])\nm = int(text[0][1])\ncandidate = text[1]\n# 转换为int方便后面处理\ncandidate = [int(candidate[i]) for i in range(n)]\ndp = [0 for _ in range(m)]\n# 双指针:对于每一个右指针,找到最小的左指针范围\npt1 = 0\npt2 = 0\nmin_len = 1000001\nwhile pt1 < n:\n # 如果有空的,则pt2一直往下,直到找到dp中包含全部的\n if 0 in dp:\n if pt2 == n:\n break\n elif not candidate[pt2] == 0:\n dp[candidate[pt2]-1]+=1\n pt2+=1\n else:\n if not candidate[pt1] == 0:\n # 如果没有空的,那么对于当前的pt2找到最小pt1\n min_len = min(min_len,pt2-pt1)\n dp[candidate[pt1]-1]-=1\n pt1+=1\nif min_len == 1000001:\n print(-1)\nelse:\n print(min_len)\n\n# AC c++\n'''\n#include \n#include \n\nusing namespace std;\n\nint main() {\n int n, m;\n vector balls;\n cin >> n >> m;\n for (int i = 0; i < n; i ++) {\n int k;\n cin >> k;\n balls.push_back(k);\n }\n int s[2001] = {0};\n\n int l = 0, r = -1;\n int cnt = 0;\n int minLen = n + 1;\n # 左指针小于长度\n while (l < n) {\n # 右指针小于长度并且计数器小于m\n if (r + 1 < n && cnt < m) {\n # 这里也是维护了一个这样的\n s[balls[r + 1]] ++;\n\n if (s[balls[r + 1]] <= 1 && balls[r + 1] != 0) {\n cnt ++;\n }\n r ++;\n } else {\n if (cnt == m && r - l + 1 < minLen) {\n minLen = r - l + 1;\n }\n s[balls[l]] --;\n if (s[balls[l]] < 1 && balls[l] != 0) {\n cnt --;\n }\n l ++;\n }\n }\n if (minLen == n + 1) {\n cout << \"-1\" << endl;\n } else {\n cout << minLen << endl; \n }\n return 0;\n\n}\n\n'''","sub_path":"TX3月11一面题目.py","file_name":"TX3月11一面题目.py","file_ext":"py","file_size_in_byte":3860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"319075102","text":"from django.conf.urls import patterns, url\n\nfrom blog import views\n\nurlpatterns = patterns('',\n url(r'^$', views.index, name='index'),\n url(r'^post/(?P[0-9])/$', views.detail, name='detail'),\n url(r'^form/$',views.form, name='form'),\n url(r'^crearPost/$',views.crearPost, name='crearPost'),\n \n)","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"493218878","text":"#OTAA Node LoRaWAN Accelerometer\n#Juan Manuel Galán Serrano\n#UPC-ALSTOM 2018\n#------------------------------------------------------------------------------#\nfrom network import LoRa\nimport socket\nimport binascii\nimport struct\nimport pycom\nimport time\nimport machine\nimport _thread\nfrom machine import Timer\nfrom network import WLAN\n#------------------------------------------------------------------------------#\n#Librerias de Pysense y sensores\nfrom pysense import Pysense\nfrom LIS2HH12 import LIS2HH12\n\nWAKE_REASON_PUSH_BUTTON = 2\nWAKE_REASON_ACCELEROMETER = 1\n\nFULL_SCALE_4G = const(2)\nODR_800_HZ = const(6)\n#------------------------------------------------------------------------------#\nclass Node:\n def __init__(self,data_rate,py):\n self.lora = None # Instancia de Lora (sin inicializar)\n self.s = None # Instancia Socket (sin inicializar)\n self.dr = data_rate # Data Rate (defecto 5)\n self.py = py # Instancia de Pysense\n self.acc = LIS2HH12(self.py) # Instancia del Acelerometro\n self.last = [0,0,0] # Último valor leído de aceleracion\n self.raw = [0,0,0] # Valor leído actual de aceleracion\n self.busy = 0 # Value has passed limit\n self.interval = 10 # Intervalo de toma de datos\n self.battery = None # Valor de la tensión de batería\n self.s_lock = _thread.allocate_lock() # Semaforo para envío\n#------------------------------------------------------------------------------#\n def connect(self,dev_eui,app_eui, app_key):\n \"\"\"\n Connect device to LoRa.\n Set the socket and lora instances.\n \"\"\"\n # Initialize LoRa in LORAWAN mode\n self.lora = LoRa(mode = LoRa.LORAWAN,device_class=LoRa.CLASS_A)\n # Set the 3 default channels to the same frequency (must be before\n # sending the OTAA join request)\n self.lora.add_channel(0, frequency=868100000, dr_min=0, dr_max=5)\n self.lora.add_channel(1, frequency=868100000, dr_min=0, dr_max=5)\n self.lora.add_channel(2, frequency=868100000, dr_min=0, dr_max=5)\n # Join a network using OTAA (Over the Air Activation)\n self.lora.join(activation = LoRa.OTAA, auth = (dev_eui,app_eui, app_key),\n timeout = 0, dr=5) #login for TheThingsNetwork see here:\n #https://www.thethingsnetwork.org/forum/t/lopy-otaa-example/4471\n # Wait until the module has joined the network\n while not self.lora.has_joined():\n print(\"Trying to join LoraWAN with OTAA\")\n time.sleep(2.5)\n print (\"LoraWAN joined! \")\n #Handler de Recepción\n #self.lora.callback(trigger=(LoRa.RX_PACKET_EVENT),handler=self.lora_cb)\n # save the LoRaWAN connection state\n self.lora.nvram_save()\n#------------------------------------------------------------------------------#\n def send(self,data):\n \"\"\"\n Send data over the network.\n \"\"\"\n\n self.s_lock.acquire() # Espera a que el semáforo esté disponible (tiempo indefinido)\n\n if py.get_wake_reason() == WAKE_REASON_ACCELEROMETER: #Si despierta tras deepsleep\n # Initialize LoRa in LORAWAN mode\n self.lora = LoRa(mode = LoRa.LORAWAN,adr=True,device_class=LoRa.CLASS_A)\n # restore the LoRaWAN connection state\n try:\n self.lora.nvram_restore()\n except OSError:\n print(\"Error: LoRa Configuration could not be restored\")\n self.connect(binascii.unhexlify('006A76B0778AEDA7'),\n binascii.unhexlify('70B3D57ED0009ABB'),\n binascii.unhexlify('08D62712D816F1C28B7E6EA39E711209'))\n print(\"LoRa Connection Parameters Recovered\")\n for i in range(3, 16):\n self.lora.remove_channel(i)\n # Set the 3 default channels to the same frequency\n # (must be before sending the OTAA join request)\n self.lora.add_channel(0, frequency=868100000, dr_min=0, dr_max=5)\n self.lora.add_channel(1, frequency=868100000, dr_min=0, dr_max=5)\n self.lora.add_channel(2, frequency=868100000, dr_min=0, dr_max=5)\n # Create a LoRa socket\n self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)\n print(\"Created LoRaWAN socket\")\n # Make the socket non-blocking\n self.s.setblocking(True)\n\n try:\n self.s.send(data)\n self.s.setblocking(False) #Espera para posible recepción\n rx = bytes(self.s.recv(128)) #Recepción de datos\n self.receive(rx=rx)\n self.lora.nvram_save()\n except OSError as e:\n if e.errno == 11:\n print(\"Caught exception while sending\")\n print(\"errno: \", e.errno)\n\n self.s_lock.release() #Libera el semáforo\n _thread.exit() #Cierra el hilo\n\n#------------------------------------------------------------------------------#\n#Función de recpeción de datos.Es activada tras la ventana de recepción\n#posterior al envío.\n def receive(self,rx=None):\n if len(rx) == 0: #No hay mensaje de recepción\n pass\n else:\n if rx[0] == 82: #Orden de Cambio Data Rate (ASCII hex R=0x52 dec 87)\n print(\"Cambiando Data Rate %d\" %(int.from_bytes(rx[1:],'big')))\n self.dr = int.from_bytes(rx[1:],'big') #Decodifica el valor del nuevo data Rate\n pycom.nvs_set('data_rate',self.data_rate) #Lo guarda en NVRAM\n else:\n pass\n#------------------------------------------------------------------------------#\n#Función de lectura de medidas. Los sensores ya han sido inicializados al\n#crear la instancia de la clase Node\n def readsens(self):\n self.raw = self.acc.acceleration() # Devuelve tuple con aceleracion en tres ejes (G)\n print(\"Aceleracion-> X:%fG Y:%fG Z:%fG\"%(self.raw[0],self.raw[1],self.raw[2]))\n #Cálculos\n #if (self.raw[0] > 2.1) or (self.raw[1] > 2.1) or (self.raw[2] > 2.1):\n # print(\"Enviando datos\")\n # XR=int(self.raw[0]*10000).to_bytes(2,'little')\n # YR=int(self.raw[1]*10000).to_bytes(2,'little')\n # ZR=int(self.raw[2]*10000).to_bytes(2,'little')\n # XL=int(self.last[0]*10000).to_bytes(2,'little')\n # YL=int(self.last[1]*10000).to_bytes(2,'little')\n # ZL=int(self.last[2]*10000).to_bytes(2,'little')\n # data = XR+YR+ZR+XL+YL+ZL\n # _thread.start_new_thread(self.send,data) # Se crea un hilo para el envío de valores\n self._compare_update()\n alarmaPub = Timer.Alarm(self.readsens(),10, periodic=False)\n #if (self.raw[0] < 1.5) and (self.raw[1] < 1.5) and (self.raw[2] < 1.5):\n # alarmaPub.cancel();\n # n.py.setup_int_wake_up(rising=True,falling=False) #Activa la interrupcion para el boton DEBUG\n # print('Activada Interrupccion de Actividad')\n # n.acc.enable_activity_interrupt(1500,100) #Threshold= 1,5G, Min Time = 100ms\n # print(\"Going to Sleep\")\n # n.py.setup_sleep(300)\n # n.py.go_to_sleep()\n\n #self.battery = round(self.py.read_battery_voltage(),2)\n #print(\"Battery: %f\",%(self.battery))\n #if (self.battery < 3.4):\n # print(\"Batería Crítica\")\n # _thread.start_new_thread(self.send,(\"Batería\",\" Crítica\")) # Se crea un hilo para el envío de alarma de batería\n\n#------------------------------------------------------------------------------#\n def _compare_update(self):\n if self.raw is not self.last:\n self.last = self.raw\n else:\n pass\n#------------------------------------------------------------------------------#\n\n#Codigo principal\ndev_eui = binascii.unhexlify('006A76B0778AEDA7')\napp_eui = binascii.unhexlify('70B3D57ED0009ABB') #ID de la app. (Seleccionada por el usuario)\napp_key = binascii.unhexlify('08D62712D816F1C28B7E6EA39E711209') #Clave de la app para realizar el handshake. Única para cada dispositivo.\npy = Pysense()\n\n#Según el modo de inicio, se realizan unas serie de acciones u otras.\nif (py.get_wake_reason() == WAKE_REASON_ACCELEROMETER):\n print('Accelerometer Interrupt.')\n try:\n data_rate = pycom.nvs_get('data_rate')\n except (0):\n print(\"Error: Value could not be restore\")\n data_rate = 5\n pycom.nvs_set('data_rate', data_rate)\n pass\n n = Node(data_rate,py) #Crea una instancia de Node\n n.readsens()\n\n\nelif (py.get_wake_reason() == WAKE_REASON_PUSH_BUTTON):\n uart = UART(0, 115200) #Se activa la UART\n os.dupterm(uart)\n wlan = WLAN()\n wlan.init(mode=WLAN.AP, ssid='lopy-pysense', auth=(WLAN.WPA2,'lopy-pysense'),\n channel=7,antenna=WLAN.INT_ANT) #Inicia el servidor FTP\n\n print(\"Device entered into debugging mode\")\n print(\"Please do not connect to battery\")\n pycom.heartbeat(True) #Se activa el Heartbeat\n while(1):\n if py.button_pressed():\n print(\"Exit DEBUG MODE, reseting...\")\n print('- ' * 20)\n machine.reset()\nelse: #Si viene de Boot o Hard Reset\n print('Power-On or Hard Reset')\n data_rate = 5\n try:\n pycom.nvs_set('data_rate', data_rate)\n except (None):\n print(\"Error: Value could not be stored\")\n pass\n pycom.wifi_on_boot(False) #disable WiFi on boot TODO: Intentar en versiones posteriores, da un Core Error.\n print('Desactivado Wifi On Boot')\n n = Node(data_rate,py) #Crea una instancia de Node\n #n.connect(dev_eui,app_eui, app_key) #Join LoRaWAN with OTAA\n n.acc.set_full_scale(FULL_SCALE_4G)\n print('Escala Acelerometro 4G')\n n.acc.set_odr(ODR_800_HZ)\n print('ODR 50Hz')\n n.py.setup_int_wake_up(rising=True,falling=False) #Activa la interrupcion para el boton DEBUG\n print('Activada Interrupccion de Actividad')\n n.acc.enable_activity_interrupt(1500,100) #Threshold= 1G, Min Time = 100ms\n print('Set Acc Interrupt.')\n n.py.setup_sleep(300)\n n.py.go_to_sleep()\n","sub_path":"OTAA_Aceleracion_STOPPED/otaa_node_acc_deepsleep.py","file_name":"otaa_node_acc_deepsleep.py","file_ext":"py","file_size_in_byte":11800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"578490167","text":"import random\nfrom Item import Item\n\n\n\ndef genoutputs(items):\n \t\n\tv = ''\n\tk = 0\n\trows = ''\n\tfor x in items:\n\t\trows += x.ToHtmlRow();\n\n\ttext = \" МСС-М \"\\\n\t + rows + ''\n\treturn text\n\nl= []\nfor x in range(1,10):\n\ti = Item()\n\ti.number = random.randint(1, 5)\n\ti.pheader = random.randint(1, 5)\n\ti.sigment = random.randint(1, 5)\n\tl.append(i)\n\n#Выводит [Decode error - output not utf-8] Это ошибка сублайма.\n#Решение тут https://toster.ru/q/158563\n\n\nprint(genoutputs(l))\nmtext = genoutputs(l)\n\nf = open('o.html', 'w', encoding='utf8')\nf.write(mtext)\nf.close()","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"459172110","text":"# -*- coding: UTF-8 -*-\nimport json\nimport math\nimport pandas as pd\n\n\nclass HmmPosTag:\n def __init__(self):\n self.trans_prop = {}\n self.emit_prop = {}\n self.start_prop = {}\n self.poslist = []\n self.trans_sum = {}\n self.emit_sum = {}\n\n def __upd_trans(self, curpos, nxtpos):\n \"\"\"更新转移概率矩阵\n\n Args:\n curpos (string): 当前词性\n nxtpos (string): 下一词性\n \"\"\"\n if curpos in self.trans_prop:\n if nxtpos in self.trans_prop[curpos]:\n self.trans_prop[curpos][nxtpos] += 1\n else:\n self.trans_prop[curpos][nxtpos] = 1\n else:\n self.trans_prop[curpos] = {nxtpos: 1}\n\n def __upd_emit(self, pos, word):\n \"\"\"更新发射概率矩阵\n\n Args:\n pos (string): 词性\n word (string): 词语\n \"\"\"\n if pos in self.emit_prop:\n if word in self.emit_prop[pos]:\n self.emit_prop[pos][word] += 1\n else:\n self.emit_prop[pos][word] = 1\n else:\n self.emit_prop[pos] = {word: 1}\n\n def __upd_start(self, pos):\n \"\"\"更新初始状态矩阵\n\n Args:\n pos (string): 初始词语的词性\n \"\"\"\n if pos in self.start_prop:\n self.start_prop[pos] += 1\n else:\n self.start_prop[pos] = 1\n\n def train(self, data_path):\n \"\"\"训练 hmm 模型、求得转移矩阵、发射矩阵、初始状态矩阵\n\n Args:\n data_path (string): 训练数据的路径\n \"\"\"\n f = open(data_path, 'r', encoding='utf-8')\n for line in f.readlines():\n line = line.strip().split()\n # 统计初始状态的概率\n self.__upd_start(line[0].split('/')[1])\n # 统计转移概率、发射概率\n for i in range(len(line) - 1):\n self.__upd_emit(line[i].split('/')[1], line[i].split('/')[0])\n self.__upd_trans(line[i].split('/')[1],\n line[i + 1].split('/')[1])\n i = len(line) - 1\n self.__upd_emit(line[i].split('/')[1], line[i].split('/')[0])\n f.close()\n # 记录所有的 pos\n self.poslist = list(self.emit_prop.keys())\n self.poslist.sort()\n # 统计 trans、emit 矩阵中各个 pos 的归一化分母\n num_trans = [\n sum(self.trans_prop[key].values()) for key in self.trans_prop\n ]\n self.trans_sum = dict(zip(self.trans_prop.keys(), num_trans))\n num_emit = [\n sum(self.emit_prop[key].values()) for key in self.emit_prop\n ]\n self.emit_sum = dict(zip(self.emit_prop.keys(), num_emit))\n\n def predict(self, sentence):\n \"\"\"Viterbi 算法预测词性\n\n Args:\n sentence (string): 分词后的句子(空格隔开)\n\n Returns:\n list: 词性标注序列 \n \"\"\"\n sentence = sentence.strip().split()\n posnum = len(self.poslist)\n dp = pd.DataFrame(index=self.poslist)\n path = pd.DataFrame(index=self.poslist)\n # 初始化 dp 矩阵(DP 矩阵: posnum * wordsnum 存储每个 word 每个 pos 的最大概率)\n start = []\n num_sentence = sum(self.start_prop.values()) + posnum\n for pos in self.poslist:\n sta_pos = self.start_prop.get(pos, 1e-16) / num_sentence\n sta_pos *= (self.emit_prop[pos].get(sentence[0], 1e-16) /\n self.emit_sum[pos])\n sta_pos = math.log(sta_pos)\n start.append(sta_pos)\n dp[0] = start\n # 初始化 path 矩阵\n path[0] = ['_start_'] * posnum\n # 递推\n for t in range(1, len(sentence)): # 句子中第 t 个词\n prob_pos, path_point = [], []\n for i in self.poslist: # i 为当前词的 pos\n max_prob, last_point = float('-inf'), ''\n emit = math.log(self.emit_prop[i].get(sentence[t], 1e-16) / self.emit_sum[i])\n for j in self.poslist: # j 为上一次的 pos\n tmp = dp.loc[j, t - 1] + emit\n tmp += math.log(self.trans_prop[j].get(i, 1e-16) / self.trans_sum[j])\n if tmp > max_prob:\n max_prob, last_point = tmp, j\n prob_pos.append(max_prob)\n path_point.append(last_point)\n dp[t], path[t] = prob_pos, path_point\n # 回溯\n prob_list = list(dp[len(sentence) - 1])\n cur_pos = self.poslist[prob_list.index(max(prob_list))]\n path_que = []\n path_que.append(cur_pos)\n for i in range(len(sentence) - 1, 0, -1):\n cur_pos = path[i].loc[cur_pos]\n path_que.append(cur_pos)\n # 返回结果\n postag = []\n for i in range(len(sentence)):\n postag.append(sentence[i] + '/' + path_que[-i - 1])\n return postag\n\n\nif __name__ == \"__main__\":\n # data_clean()\n hmm = HmmPosTag()\n hmm.train(\"./data/PeopleDaily_clean.txt\")\n hmm.predict(\"在 这 一 年 中 , 中国 的 改革 开放 和 现代化 建设 继续 向前 迈进 再次 获得 好 的 收成 \")\n\n# 1. 语料库中有 26 个基本词类标记\n# 形容词a、区别词b、连词c、副词d、叹词e、方位词f、语素g、前接成分h、成语i、\n# 简称j、后接成分k、习惯用语l、数词m、名词n、拟声词o、介词p、量词q、代词r、\n# 处所词s、时间词t、助词u、动词v、标点符号w、非语素字x、语气词y、状态词z、\n#\n#\n# 2. 语料库中还有 74 个扩充标记:对于语素,具体区分为 Ag Bg Dg Mg Ng Rg Tg Vg Yg\n#\n#\n# 3. 词性标注只标注基本词性,因此在数据清洗的过程中,将扩充标记归类到各个基本词类中,语素也归类到相应词类中\n","sub_path":"models/HmmPosTag.py","file_name":"HmmPosTag.py","file_ext":"py","file_size_in_byte":5916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"118933543","text":"'''\r\nCreated on 25-Feb-2014\r\n\r\n@author: GaneshKumar Munusamy\r\n'''\r\nfrom Age import with_HBP_AgeL, with_HBP_AgeM, with_HBP_AgeH\r\nimport activity\r\nimport lookup_table_sleep\r\n\r\n\r\ndef count_none(input_count):\r\n count = 0\r\n for field in input_count:\r\n if input_count[field] == \"None\":\r\n count = count+1\r\n return count \r\n\r\ndef check_bp(input_bp):\r\n checkBP = \"false\"\r\n for field in input_bp:\r\n if field == \"bloodPressures\":\r\n checkBP = \"true\" \r\n return checkBP \r\n\r\ndef check_activity(input_act):\r\n checkActivity = \"false\"\r\n \r\n if input_act['activities'] != -1:\r\n checkActivity = \"true\" \r\n return checkActivity\r\n\r\ndef highPress(input_HBP):\r\n HBP_Age_High = []\r\n HBP_Age_Mid = []\r\n if input_HBP['userinfo']['age'] < 20:\r\n HBP_Age_Low = with_HBP_AgeL(input_HBP)\r\n return HBP_Age_Low\r\n elif input_HBP['userinfo']['age'] < 50:\r\n HBP_Age_Mid = with_HBP_AgeM(input_HBP)\r\n return HBP_Age_Mid\r\n else:\r\n HBP_Age_High = with_HBP_AgeH(input_HBP)\r\n return HBP_Age_High\r\n\r\ndef call_bp(input_with_bp):\r\n highRec = []\r\n highRec.append(\"600\")\r\n if input_with_bp['bloodPressures'][0]['systolic'] > 140:\r\n highRec = highPress(input_with_bp)\r\n if not highRec.__contains__(\"601\") and input_with_bp['BMI'] > 35 and input_with_bp['userinfo']['age'] > 40 and input_with_bp['activities'][0]['duration'] < 20:\r\n highRec.append(\"607\")\r\n if not highRec.__contains__(\"601\") and input_with_bp['sleep'][0]['minutesAsleep'] < 360:\r\n highRec.append(\"606\")\r\n \r\n return highRec \r\n\r\ndef recommend_start(input_rec): \r\n \"\"\"Check for Blood Pressure and number of not none\r\n Call the functions accordingly\"\"\" \r\n recommendation = []\r\n Num_of_None = count_none(input_rec)\r\n if_bp = check_bp(input_rec)\r\n if_activity = check_activity(input_rec)\r\n if if_bp is \"true\":\r\n recommendation = call_bp(input_rec)\r\n \r\n \"\"\"Irrespective of Blood Pressure Value given\"\"\"\r\n if if_activity is \"true\":\r\n recommend_activity = activity.call_activity(input_rec)\r\n recommendation.append(recommend_activity)\r\n \r\n \"\"\"call the lookup table and search for recommendations\"\"\"\r\n length = recommendation.__len__()\r\n value = recommendation.count(\"600\")\r\n if length == value:\r\n recommendation = []\r\n recommendation.append(\"600\") \r\n else:\r\n for rec_value in recommendation:\r\n if rec_value == \"600\":\r\n recommendation.remove(\"600\")\r\n \r\n recommendation_list = lookup_table_sleep.lookup_value(recommendation)\r\n return recommendation_list\r\n \r\n ","sub_path":"analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":2731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"221183630","text":"import numpy as np\nimport pandas as pd\nfrom recommendcolumn.normalized import *\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn import preprocessing\n\n\ndef keyColumn_RandomForest(D, des):\n # parallel = 10\n D = np.array(D)\n target = 'quantity'\n rec_column = []\n feat_labels = []\n # obtain initial x,y\n for i in des:\n c = des.index(i)\n if target in i[0]:\n rec_column.append(1)\n y = D[:, c]\n for index, item in enumerate(y):\n if item == None:\n y[index] = y[index - 1]\n y = y.astype(np.int64)\n continue\n if 'STR' in i[1] or 'str' in i[1]:\n if len(D[0][c]) >= 120:\n rec_column.append(0.5)\n else:\n rec_column.append(0)\n else:\n rec_column.append(0)\n x = D[:]\n xdes = list(des)\n count = 0\n for i in range(len(rec_column)):\n if rec_column[i] == 0.5:\n j = i - count\n x = np.delete(x, j, axis=1)\n del xdes[j]\n count += 1\n for i in range(len(xdes)):\n feat_labels.append(xdes[i][0].split(\".\")[0])\n\n # normalized x\n for i in range(len(xdes)):\n if 'double' in xdes[i][1].lower() or 'float' in xdes[i][1].lower() or 'int' in xdes[i][1].lower():\n continue\n elif 'str' in xdes[i][1].lower() or 'text' in xdes[i][1].lower():\n DealWithStr(x, i)\n elif 'data' in xdes[i][1].lower() or 'time' in xdes[i][1].lower():\n DealWithTime(x, i)\n x_scale = preprocessing.scale(x)\n\n # normalized y\n y_scale = preprocessing.scale(y)\n y_scale = np.around(np.around(y_scale, decimals=2) * 100)\n\n # RandomForest obtain features\n forest = RandomForestClassifier(n_estimators=10, random_state=0, n_jobs=-1, max_depth=5)\n forest.fit(x_scale, y_scale)\n importances = forest.feature_importances_\n # xrows_10 = x_scale.shape[0] / 10\n # for i in range(1, 11):\n # tempx = x_scale[(i - 1) * xrows_10:i * xrows_10:]\n # tempy = y_scale[(i - 1) * xrows_10:i * xrows_10:]\n # # thread.start_new_thread(randomForest(tempx,tempy))\n # # global importances\n # importances = randomForest(tempx, tempy)\n indices = np.argsort(importances)[::-1]\n for f in range(x.shape[1]):\n print(\"%2d) %-*s %f\" % (f + 1, 30, feat_labels[indices[f]], importances[indices[f]]))\n return feat_labels, indices\n","sub_path":"recommendcolumn/keyColumn_RandomForest.py","file_name":"keyColumn_RandomForest.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"146589460","text":"from django.conf import settings\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse_lazy\n\nfrom re import compile\n\n#from bs4 import BeautifulSoup\n\n\nclass LoginRequiredMiddleware(object):\n \"\"\"\n Middleware que requer que um usuário esteja autenticado\n para acessar qualquer página fora reverse_lazy(LOGIN_URL_NAME).\n \"\"\"\n \n def get_login_url(self):\n return reverse_lazy(settings.LOGIN_URL_NAME)\n\n def get_exempts(self):\n exempts = [compile(self.get_login_url().lstrip('/'))]\n if hasattr(settings, 'LOGIN_EXEMPT_URLS'):\n exempts += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS]\n return exempts\n \n def process_request(self, request):\n assert hasattr(request, 'user'), \"The Login Required middleware\\\n requires authentication middleware to be installed. Edit your\\\n MIDDLEWARE_CLASSES setting to insert\\\n 'django.contrib.auth.middlware.AuthenticationMiddleware'. If\\\n that doesn't work, ensure your TEMPLATE_CONTEXT_PROCESSORS\\\n setting includes 'django.core.context_processors.auth'.\"\n\n if not request.user.is_authenticated():\n path = request.path.lstrip('/')\n if not any(m.match(path) for m in self.get_exempts()):\n return HttpResponseRedirect(\n self.get_login_url() + \"?next=\" + request.path\n )\n\nclass BeautifulMiddleware(object):\n \"\"\"\n Corrige espaços em branco nos HTMLs renderizados pelo Django.\n \"\"\"\n\n def process_response(self, request, response):\n if response.status_code == 200:\n if response['content-type'].startswith('text/html'):\n beauty = BeautifulSoup(response.content, 'html.parser')\n response.content = beauty.prettify()\n return response\n\n","sub_path":"enadum/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"358213009","text":"from .nodes import NODE_CLASSES, Regexes\nfrom . import utils\n\n\ndef compile_markdown(raw_input: str) -> str:\n # Build html tag for each node that is added in the classlist\n for node_cls in NODE_CLASSES:\n\n # Replace the raw md with correct html tag.\n for match in node_cls.get_matches(raw_input):\n html = node_cls.build_html(match)\n string_to_replace = node_cls.get_string_to_replace(match)\n raw_input = utils.replace_md_with_html(raw_input,\n string_to_replace, \n html)\n\n compiled_text = ''\n\n # Leftover parts must now be wrapped as normal text.\n for line in raw_input.splitlines():\n if not Regexes.not_body_tags.match(line):\n line = utils.wrap_as_text(line)\n print(line, Regexes.not_body_tags.match(line))\n\n if utils.tag_ok(line):\n compiled_text += line\n\n\n return compiled_text\n","sub_path":"victorhook_blog/victorhook_blog/markdown_compiler/compiler.py","file_name":"compiler.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"354901291","text":"# -*- coding:utf-8 -*-\nfrom PythonMiddleware.notify import Notify\nfrom PythonMiddleware.graphene import Graphene\nfrom PythonMiddlewarebase.operationids import operations\n\nimport datetime\nfrom time import sleep\nimport pymongo\nfrom collections import deque\nfrom threading import Thread, Lock\nfrom prometheus_client import CollectorRegistry, Gauge, pushadd_to_gateway\n\nfrom config import *\nfrom utils import Logging\nfrom handle_block import logger, parse_operations, handle_operations, init_gauges\nimport json\nfrom bson import json_util as jsonb\n\n#logger = Logging().getLogger()\n\nblock_info_q = deque() \npending_block_num_q = deque() \noperations_q = deque() \n\nblock_info_deque_lock = Lock()\npending_block_num_deque_lock = Lock()\nop_deque_lock = Lock()\n\ndef check_block():\n def one_block_check(block_num):\n logger.info('check block number: {}'.format(block_num))\n try:\n block = gph.rpc.get_block(block_num)\n #witness_id = block['witness']\n block_witness = gph.rpc.get_object(gph.rpc.get_object(block['witness'])['witness_account'])['name']\n except Exception as e:\n logger.error('get_object exception. block {}, error {}'.format(block_num, repr(e)))\n return\n block_time = block['timestamp']\n transactions = block[\"transactions\"]\n witness_sign = block['witness_signature']\n trx_total = 0\n ops_total = 0\n transactions_id = []\n if transactions:\n trx_total = len(transactions)\n for trx in transactions:\n transactions_id.append(trx[0])\n ops_total += len(trx[1][\"operations\"])\n block_data = {\n \"block_num\": block_num,\n \"time\": block_time,\n \"witness\": block_witness,\n \"witness_sign\": witness_sign,\n \"transactions_total\": trx_total,\n \"transactions_id\": transactions_id,\n \"operations_total\": ops_total\n }\n block_info_deque_lock.acquire()\n block_info_q.append(block_data)\n block_info_deque_lock.release()\n\n try:\n gph = Graphene(node=nodeaddress)\n #info = gph.info()\n #logger.info('info: {}'.format(info))\n\n conn = pymongo.MongoClient(mongodb_params['host'], mongodb_params['port'])\n conn_db = conn[mongodb_params['db_name']]\n\n sort_limit_result = conn_db.block.find().sort(\"block_num\", -1).limit(1)\n db_last_block_str = jsonb.dumps(sort_limit_result)\n logger.info(\"db_last_block_str: {}\".format(db_last_block_str))\n db_last_block = json.loads(db_last_block_str)\n\n if len(db_last_block) != 1:\n logger.error(\"conn_db.block.find().sort('block_num', -1).limit(1) exception\")\n conn.close()\n return\n \n start_num = db_last_block[0]['block_num']\n info = gph.info()\n logger.info('info: {}'.format(info))\n last_block_num = info['head_block_number']\n \n increase = int((last_block_num-start_num)/8)+10 # 尽可能处理listen之前新增的区块\n logger.info(\">>> start: {}, end: {}, step: {}\".format(start_num, last_block_num, increase))\n for index in range(start_num, last_block_num+increase):\n result = conn_db.block.find({'block_num':index})\n if result.count() != 0:\n logger.info('block({}) already exists in mongo db'.format(index))\n continue\n one_block_check(index)\n conn.close()\n except Exception as e:\n logger.error(\"except: '{}'\".format(repr(e)))\n \n# 监听区块\ndef listen_block():\n def on_block_callback(recv_block_id):\n info = gph.info()\n #logger.debug('info: {}'.format(info))\n head_block_id = info['head_block_id']\n block_num = info['head_block_number']\n logger.info('recv_block_id: {}, head_block_id {}, head_block_num {}'.format(recv_block_id, head_block_id, block_num))\n if recv_block_id == head_block_id:\n pending_block_num_deque_lock.acquire()\n pending_block_num_q.append(block_num)\n pending_block_num_deque_lock.release()\n logger.info(\"pending deque >>>: {}\".format(pending_block_num_q))\n\n try:\n block = gph.rpc.get_block(block_num)\n #witness_id = block['witness']\n block_witness = gph.rpc.get_object(gph.rpc.get_object(block['witness'])['witness_account'])['name']\n except Exception as e:\n logger.error('get_object exception. block {}, error {}'.format(block_num, repr(e)))\n block_time = block['timestamp']\n transactions = block[\"transactions\"]\n witness_sign = block['witness_signature']\n trx_total = 0\n ops_total = 0\n transactions_id = []\n if transactions:\n trx_total = len(transactions)\n for trx in transactions:\n transactions_id.append(trx[0])\n ops_total += len(trx[1][\"operations\"])\n block_data = {\n \"block_num\": block_num,\n \"time\": block_time,\n \"witness\": block_witness,\n \"witness_sign\": witness_sign,\n \"transactions_total\": trx_total,\n \"transactions_id\": transactions_id,\n \"operations_total\": ops_total\n }\n block_info_deque_lock.acquire()\n block_info_q.append(block_data)\n block_info_deque_lock.release()\n\n gph = Graphene(node=nodeaddress)\n from PythonMiddleware.instance import set_shared_graphene_instance\n set_shared_graphene_instance(gph)\n notify = Notify(\n on_block = on_block_callback,\n graphene_instance = gph\n )\n notify.listen()# 启动监听服务\n\n\ndef check_and_listen_block():\n logger.info(\"------- check block start ------\")\n check_block()\n logger.info(\"------- check block end ------\")\n listen_block()\n\n# 解析区块\ndef analysis_block():\n gph = Graphene(node=nodeaddress)\n from PythonMiddleware.instance import set_shared_graphene_instance\n set_shared_graphene_instance(gph)\n while 1:\n if pending_block_num_q:\n try:\n pending_block_num_deque_lock.acquire()\n block_num = pending_block_num_q.popleft()\n pending_block_num_deque_lock.release()\n logger.debug('pop block number: {}'.format(block_num))\n try:\n block_info = gph.rpc.get_block(block_num)\n time = block_info[\"timestamp\"]\n transactions = block_info[\"transactions\"]\n operations_list = parse_operations(gph, block_num, time, transactions)\n #logger.debug('block: {}, trx_list: {}'.format(block_num, operations_list))\n except Exception as e:\n logger.error('parse block exception. block {}, error {}'.format(block_num, repr(e)))\n if operations_list:\n op_deque_lock.acquire()\n operations_q.append(operations_list)\n op_deque_lock.release()\n except Exception as e:\n logger.error(\"pending_block_num_q: {}, except: '{}'\".format(pending_block_num_q, repr(e)))\n sleep(0.7)\n\n#将区块数据写入数据库中block表中\ndef block2db():\n while 1:\n if block_info_q:\n try:\n #global block_info_deque_lock\n block_info_deque_lock.acquire()\n block = block_info_q.popleft()\n block_info_deque_lock.release()\n #update mongodb\n conn = pymongo.MongoClient(mongodb_params['host'], mongodb_params['port'])\n conn_db = conn[mongodb_params['db_name']]\n try: \n conn_db.block.insert_one({\n 'block_num': block[\"block_num\"], \n 'time': block[\"time\"], \n 'witness': block[\"witness\"], \n 'witness_sign': block[\"witness_sign\"], \n 'transactions_id': str(block[\"transactions_id\"]), \n 'transactions_total': block[\"transactions_total\"], \n 'operations_total': block[\"operations_total\"]\n })\n except Exception as e:\n logger.error(\"block: {}, except: '{}'\".format(block[\"block_num\"], repr(e)))\n finally:\n conn.close()\n logger.info('block num: {} done.'.format(block[\"block_num\"]))\n except Exception as e:\n logger.error(\"except: '{}'\".format(repr(e)))\n sleep(0.7)\n\n#将区块解析过的数据写入到数据库中的op表和transaction表中\ndef data2db(): \n while 1:\n if operations_q:\n try:\n op_deque_lock.acquire()\n operations_list = operations_q.popleft()\n op_deque_lock.release()\n handle_operations(operations_list)\n\n # status = handle_operations(operations_list)\n # if not status:\n # op_deque_lock.acquire()\n # block_trx_ops = operations_q.appendleft(operations_list)\n # op_deque_lock.release()\n # logger.warn('consume status {}, trx list: {}'.format(status, operations_list))\n except Exception as e:\n logger.error(\"except: '{}'\".format(repr(e)))\n sleep(0.5)\n\nif __name__ == '__main__':\n init_gauges()\n thread_block_analysis = Thread(target=analysis_block)\n thread_block_analysis.start()\n\n thread_block2db = Thread(target=block2db)\n thread_block2db.start()\n\n thread_data2db = Thread(target=data2db)\n thread_data2db.start()\n\n thread_block = Thread(target=check_and_listen_block)\n thread_block.start()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"479829051","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n\ttotal = 0\n\tdef diameterOfBinaryTree(self, root):\n\t\t\"\"\"\n\t\t:type root: TreeNode\n\t\t:rtype: int\n\t\t\"\"\"\n\t\tif root == None:\n\t\t\treturn 0\n\t\tself.helper(root)\n\t\treturn self.total\n\t\n\tdef helper(self, root): # gives the depth of the root's subtree\n\t\tleftDepth = 0 if root.left == None else self.helper(root.left)\n\t\trightDepth = 0 if root.right == None else self.helper(root.right)\n\t\tlocalMax = leftDepth + rightDepth\n\t\tif localMax > self.total:\n\t\t\tself.total = localMax\n\t\treturn max(leftDepth, rightDepth) + 1 #返回左右2边里面最长的路径\n\t\t\n\t\t\n\t\t\t\n\t\t\n\t\t\t","sub_path":"interview/facebook/easy/LC543. Diameter of Binary Tree.py","file_name":"LC543. Diameter of Binary Tree.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"532855211","text":"import pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport time\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport matplotlib.pyplot as plt\r\ndata = pd.read_table(r\"C:\\Users\\Gavin\\Desktop\\T-drive Taxi Trajectories\\release\\taxi_log_2008_by_id\\1.txt\",encoding='utf-8',sep=\",\",engine='python',names=['id','时间','经度','纬度'])\r\ndf = pd.DataFrame(data)\r\nprint(df.shape)\r\ndf['时间'] = pd.to_datetime(df['时间'])\r\nprint(df.dtypes)\r\nprint('---------------------')\r\nprint(df.iloc[3])\r\ndf=df.set_index('时间')\r\nprint(df.iloc[2])\r\nlng = pd.DataFrame(data,columns = ['经度'])\r\nlat = pd.DataFrame(data,columns = ['纬度'])\r\ntime = pd.DataFrame(data,columns = ['时间'])\r\nprint(time)\r\n# 生成画布、3D图形对象、三维散点图\r\nfig = plt.figure()\r\nax = Axes3D(fig)\r\nax.scatter(lng,lat,time)\r\n\r\n# 设置坐标轴显示以及旋转角度\r\nax.set_xlabel('经度')\r\nax.set_ylabel('纬度')\r\nax.set_zlabel('时间')\r\n\r\nplt.show()\r\np","sub_path":"T1.py","file_name":"T1.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"119925650","text":"ar = []\ncounter = 0\nwith open(\"aoc8.txt\") as fin:\n for line in fin:\n line = line.strip().split(' ')\n instr = line[0]\n sign = 1 if line[1][0] == '+' else -1\n value = sign * int(line[1][1:])\n if instr == \"nop\":\n ar.append((1,0))\n elif instr == \"acc\":\n ar.append((1,value))\n else:\n ar.append((value, 0))\n counter += 1\nvisited = [False for _ in range(counter)]\ni = 0\naccum = 0\nwhile not visited[i]:\n visited[i] = True\n instr = ar[i]\n accum += instr[1]\n i += instr[0]\nprint(accum)\n","sub_path":"aoc8a.py","file_name":"aoc8a.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"646515407","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import interpolate\n\ndef loadFile(fileName):\n totalList = {}\n correctList = {}\n with open(fileName) as file:\n line = file.readline()\n while line:\n s = line.split(' ')\n print(s)\n total = int(s[2])\n correct = int(s[3]) \n v = int(s[0])\n\n if(v in totalList):\n totalList[v] += total\n else:\n totalList[v] = 0\n\n if(v in correctList):\n correctList[v] += correct\n else:\n correctList[v] = 0\n \n \n\n\n line = file.readline()\n return totalList, correctList\n\n############################## Execution ##################################\ntotal,correct = loadFile('corrGeneralT3.txt')\n############################################################################\n\nprint(total)\nprint(correct)\n\nlabels = []\nfor i in range(10,21):\n labels.append(str(i))\n\nx = np.arange(len(labels)) # the label locations\nwidth = 0.35 # the width of the bars\n\nfig, ax = plt.subplots()\nrects1 = ax.bar(x - width/2, total.values(), width, label='Total Tests', color='b')\nrects2 = ax.bar(x + width/2, correct.values(), width, label='Correct Responses', color='g')\n\n# Add some text for labels, title and custom x-axis tick labels, etc.\nax.set_ylabel('Tests')\nax.set_title('Correctness Tests')\nax.set_xticks(x)\nax.set_xticklabels(labels)\nax.legend()\n\n\ndef autolabel(rects,offsetX):\n \"\"\"Attach a text label above each bar in *rects*, displaying its height.\"\"\"\n for rect in rects:\n height = rect.get_height()\n ax.annotate('{}'.format(height),\n xy=(rect.get_x() + rect.get_width() / 2, height),\n xytext=(offsetX, 3), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='bottom')\n\n\nautolabel(rects1,-4)\nautolabel(rects2,4)\n\nfig.tight_layout()\nplt.savefig(\"correctness.svg\")\nplt.show()","sub_path":"Algorithms/generalK3/Correctness/plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"619833882","text":"#!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run fast-train\n\n# You are planning the train schedule and you want to know the minimum time of traveling between the stations.\n# \n# Each section of the rail between stations is given in the list.Each section is a tuple of distance and speed limit (both are integers).You can change the speed ( +1. -1 and ± 0 ) at the start and every minute after that.The train runs by the same amount as the speed value in a minute.\n# Note: This means that a train with a speed 2 will travel a distance 2 before another minute passes and its speed can be changed again.\n# \n# Starting speed is 0.Speed limit is set for each section of the rail. You don't exceed it.You must reach the target station at speed 1 (because it’s necessary to stop at the station).You should return the minimum time (minutes) as an integer.\n# \n# \n# \n# Input:A list of the section of the rail. Each section is a tuple of distance (as an integer) and speed limit (as an integer).\n# \n# Output:The minimum time (minutes) as an integer.\n# \n# How it is used:\n# For efficient acceleration and deceleration.\n# \n# Precondition:\n# distance > 0speed limit > 0len(section) > 0\n# \n# \n# END_DESC\n\nfrom typing import List\n\ndef fast_train(sections: List[List[int]]) -> int:\n return 0\n\nif __name__ == '__main__':\n print(\"Example:\")\n print(fast_train([(4, 3)]))\n\n assert fast_train([(4, 3)]) == 3\n assert fast_train([(9, 10)]) == 5\n assert fast_train([(5, 5), (4, 2)]) == 6\n print(\"Coding complete? Click 'Check' to earn cool rewards!\")","sub_path":"solutions/Mine/fast_train.py","file_name":"fast_train.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"374359683","text":"from math import sqrt\n\nt = int(input())\noutput = []\n\nfor i in range(t):\n n, v1, v2 = [int(i) for i in input().split()]\n\n time_lift = (2*n)/v2\n time_stairs = (sqrt(2)*n)/v1\n\n if time_lift < time_stairs:\n output.append('Elevator')\n else:\n output.append('Stairs')\n\nfor i in range(t):\n print(output[i])","sub_path":"practice_problems/inprg01/elevstrs.py","file_name":"elevstrs.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"459036135","text":"#!/usr/bin/env python\nimport sys\nimport math\nimport numpy\nimport rospy\nimport rosnode\nimport actionlib\nfrom std_msgs.msg import String\nfrom geometry_msgs.msg import Twist\nfrom geometry_msgs.msg import PointStamped\nfrom sensor_msgs.msg import CameraInfo\nfrom visual_servo_msgs.msg import VisualServoAction, VisualServoResult, VisualServoFeedback, TunableConstants\nfrom linemod_detector.msg import NamedPoint\n\ndef enum(**enums):\n\treturn type('Enum', (), enums)\n\nVisualServoStates = enum(SAFE_REGION=VisualServoFeedback.SAFE_REGION,\n ROTATE=VisualServoFeedback.ROTATE,\n MOVE_FORWARD=VisualServoFeedback.MOVE_FORWARD,\n STOP_AND_WAIT=VisualServoFeedback.STOP_AND_WAIT)\n\nclass VisualServo:\n\t\"\"\"A class to position the robot so that it can pick up an object with the manipulator\"\"\"\n\t\n\tdef __init__(self):\n\t\tself._safe_region_percentage = rospy.get_param('~safe_region_percentage', 0.1)\n\t\tself._camera_left_image_width = -1\n\t\tself._camera_left_image_height = -1\n\t\tself._camera_right_image_width = -1\n\t\tself._camera_right_image_height = -1\n\t\tself._target_window_halfwidth_rotate = rospy.get_param('~target_window_halfwidth_rotate', 3)\n\t\tself._target_window_halfwidth_move_forward = rospy.get_param('~target_window_halfwidth_move_forward', 6)\n\t\tself._target_window_halfheight_move_forward = rospy.get_param('~target_window_halfheight_move_forward', 8)\n\t\tself._camera_left_target_pixel_x = rospy.get_param('~camera_left_target_pixel_x', 317)\n\t\tself._camera_right_target_pixel_x = rospy.get_param('~camera_right_target_pixel_x', 150)\n\t\tself._camera_left_target_pixel_y = rospy.get_param('~camera_left_target_pixel_y', 256)\n\t\tself._camera_right_target_pixel_y = rospy.get_param('~camera_right_target_pixel_y', 256)\n\t\tself._camera_left_target_forward_vector_x = rospy.get_param('~camera_left_target_forward_vector_x', -16)\n\t\tself._camera_left_target_forward_vector_y = rospy.get_param('~camera_left_target_forward_vector_y', -255)\n\t\tself._camera_right_target_forward_vector_x = rospy.get_param('~camera_right_target_forward_vector_x', 16)\n\t\tself._camera_right_target_forward_vector_y = rospy.get_param('~camera_right_target_forward_vector_y', 255)\n\t\tself._loop_frequency = rospy.get_param('~loop_frequency', 10.0)\n\t\tself._new_state_wait_time = rospy.get_param('~new_state_wait_time', 1.0)\n\t\tself._new_state_wait_timer = 0.0\n\t\tself._no_input_stop_wait_time = rospy.get_param('~no_input_stop_wait_time', 0.5)\n\t\tself._stop_wait_timer = 0.0\n\t\tself._proportional_constant_drive_forward = rospy.get_param('~proportional_constant_drive_forward', 0.01)\n\t\tself._integral_constant_drive_forward = rospy.get_param('~integral_constant_drive_forward', 0.0)\n\t\tself._derivative_constant_drive_forward = rospy.get_param('~derivative_constant_drive_forward', 0.0)\n\t\tself._proportional_constant_rotate = rospy.get_param('~proportional_constant_rotate', 0.01)\n\t\tself._integral_constant_rotate = rospy.get_param('~integral_constant_rotate', 0.0)\n\t\tself._derivative_constant_rotate = rospy.get_param('~derivative_constant_rotate', 0.0)\n\t\tself._max_linear_velocity = rospy.get_param('~max_linear_velocity', 0.10)\n\t\tself._max_angular_velocity = rospy.get_param('~max_angular_velocity', 0.25)\n\t\tself._target_name = rospy.get_param('~target_name', 'red_puck')\n\t\tself.goto_state(VisualServoStates.SAFE_REGION)\n\t\tself.reset()\n\n\t\trospy.Subscriber('image_point', NamedPoint, self.object_point_callback, None, 1)\n\t\trospy.Subscriber('left_camera_info', CameraInfo, self.camera_left_info_callback, None, 1)\n\t\trospy.Subscriber('right_camera_info', CameraInfo, self.camera_right_info_callback, None, 1)\n\t\trospy.Subscriber('debug_update_constants', TunableConstants, self.debug_update_constants, None, 1)\n\t\tself._publisher = rospy.Publisher('servo_command', Twist)\n\n\t\tself._visual_servo_result = VisualServoResult()\n\t\tself._visual_servo_feedback = VisualServoFeedback()\n\t\tself._action_server = actionlib.SimpleActionServer('servo_action', VisualServoAction, self.run_visual_servo_action, False)\n\t\tself._action_server.start()\n\n\tdef reset(self):\n\t\tself._has_succeeded = False\n\t\tself._previous_time = False\n\t\tself._previous_point = False\n\t\tself.reset_pid_controller()\n\n\tdef debug_update_constants(self, tunable_constants):\n\t\tself._proportional_constant_drive_forward = tunable_constants.proportional_linear_constant\n\t\tself._integral_constant_drive_forward = tunable_constants.integral_linear_constant\n\t\tself._derivative_constant_drive_forward = tunable_constants.derivative_linear_constant\n\t\tself._proportional_constant_rotate = tunable_constants.proportional_angular_constant\n\t\tself._integral_constant_rotate = tunable_constants.integral_angular_constant\n\t\tself._derivative_constant_rotate = tunable_constants.derivative_angular_constant\n\t\tself._target_window_halfwidth_rotate = tunable_constants.target_window_halfwidth_rotate\n\t\tself._target_window_halfwidth_move_forward = tunable_constants.target_window_halfwidth_move_forward\n\t\tself._target_window_halfheight_move_forward = tunable_constants.target_window_halfheight_move_forward\n\t\tself._camera_left_target_pixel_x = tunable_constants.camera_left_target_pixel_x\n\t\tself._camera_left_target_pixel_y = tunable_constants.camera_left_target_pixel_y\n\t\tself._camera_right_target_pixel_x = tunable_constants.camera_right_target_pixel_x\n\t\tself._camera_right_target_pixel_y = tunable_constants.camera_right_target_pixel_y\n\n\n\tdef goto_state(self, new_state):\n\t\tif self._new_state_wait_timer <= 0.0:\n\t\t\tself._visual_servo_state = new_state\n\t\t\tself._new_state_wait_timer = self._new_state_wait_time\n\t\t\tself.reset_pid_controller()\n\n\tdef get_target_forward_line_pixel_x(self, pixel_y):\n\t\treturn (pixel_y - self._camera_left_target_pixel_y)*self._camera_left_target_forward_vector_x/self._camera_left_target_forward_vector_y + self._camera_left_target_pixel_x\n\n\tdef reset_pid_controller(self):\n\t\tself._previous_error = 0\n\t\tself._integral_error = 0\n\n\tdef update_pid_controller(self, error, delta_time):\n\t\tif delta_time < 0.000001:\n\t\t\tpid_controller_output = 0\n\t\telse:\n\t\t\tif self._visual_servo_state == VisualServoStates.SAFE_REGION or self._visual_servo_state == VisualServoStates.MOVE_FORWARD:\n\t\t\t\tk_p = self._proportional_constant_drive_forward\n\t\t\t\tk_i = self._integral_constant_drive_forward\n\t\t\t\tk_d = self._derivative_constant_drive_forward\n\t\t\telif self._visual_servo_state == VisualServoStates.ROTATE:\n\t\t\t\tk_p = self._proportional_constant_rotate\n\t\t\t\tk_i = self._integral_constant_rotate\n\t\t\t\tk_d = self._derivative_constant_rotate\n\t\t\tself._integral_error = self._integral_error + error*delta_time\n\t\t\tderivative = (error - self._previous_error)/delta_time\n\t\t\tpid_controller_output = k_p*error + k_i*self._integral_error + k_d*derivative\n\t\tself._previous_error = error\n\t\treturn pid_controller_output\n\n\tdef object_point_callback(self, data):\n\t\t# This function receives a centroid location of an object in pixel space\n\t\tif self._camera_left_image_width > 0 and \\\n self._camera_left_image_height > 0 and \\\n self._camera_right_image_width > 0 and \\\n self._camera_right_image_height > 0 and \\\n data.name==self._target_name:\n\t\t\trospy.loginfo(rospy.get_name() + \": received point for %s: %s\" % (data.name, data.point))\n\n\t\t\tself._previous_point = data.point\n\t\t\tself._previous_time = data.header.stamp\n\t\t\tself._stop_wait_timer = 0.0\n\n\t\t# If we were stopped and waiting for input, restart!\n\t\tif self._visual_servo_state == VisualServoStates.STOP_AND_WAIT:\n\t\t\tself.goto_state(VisualServoStates.SAFE_REGION)\n\n\tdef do_visual_servo(self):\n\t\t# This function does the visual servo work itself using the\n\t\t# centroid point received from object_point_callback(). It tries\n\t\t# to position the object such that the manipulator arm can pick it up\n\n\t\t# Early out if no object centroid point has been received yet\n\t\tif not self._previous_point or not self._previous_time:\n\t\t\treturn\n\n\t\tpoint = self._previous_point\n\t\tdelta_time = 1.0/self._loop_frequency\n\t\ttwist = Twist()\n\t\ttwist.angular.z = 0.0\n\t\ttwist.angular.y = 0.0\n\t\ttwist.angular.x = 0.0\n\t\ttwist.linear.x = 0.0\n\t\ttwist.linear.y = 0.0\n\t\ttwist.linear.z = 0.0\n\n\t\tif self._new_state_wait_timer > 0:\n\t\t\tself.reset_pid_controller()\n\t\t\tself._new_state_wait_timer = self._new_state_wait_timer - delta_time\n\n\t\tif self._new_state_wait_timer <= 0.0:\n\t\t\tself._stop_wait_timer = self._stop_wait_timer + delta_time\n\t\t\tif self._stop_wait_timer > self._no_input_stop_wait_time:\n\t\t\t\tself.goto_state(VisualServoStates.STOP_AND_WAIT)\n\t\t\t\tself._stop_wait_timer = 0.0\n\n\t\tif self._visual_servo_state == VisualServoStates.SAFE_REGION:\n\t\t\t# If the object is near the top of the image, move forward\n\t\t\tif point.y < self._camera_left_image_height*self._safe_region_percentage:\n\t\t\t\terror = self._camera_left_image_height*(self._safe_region_percentage+0.05) - point.y\n\t\t\t\tpid_controller_output = self.update_pid_controller(error, delta_time)\n\t\t\t\ttwist.angular.z = 0.0\n\t\t\t\ttwist.angular.y = 0.0\n\t\t\t\ttwist.angular.x = 0.0\n\t\t\t\ttwist.linear.x = pid_controller_output\n\t\t\t\ttwist.linear.y = 0.0\n\t\t\t\ttwist.linear.z = 0.0\n\t\t\t# Else if the object is below the target point, move backwards\n\t\t\telif point.y > self._camera_left_target_pixel_y+(self._camera_left_image_height*self._safe_region_percentage):\n\t\t\t\terror = point.y - self._camera_left_target_pixel_y+(self._camera_left_image_height*self._safe_region_percentage)\n\t\t\t\tpid_controller_output = self.update_pid_controller(error, delta_time)\n\t\t\t\ttwist.angular.z = 0.0\n\t\t\t\ttwist.angular.y = 0.0\n\t\t\t\ttwist.angular.x = 0.0\n\t\t\t\ttwist.linear.x = -pid_controller_output\n\t\t\t\ttwist.linear.y = 0.0\n\t\t\t\ttwist.linear.z = 0.0\n\t\t\telse:\n\t\t\t\tself.goto_state(VisualServoStates.ROTATE)\n\n\t\tif self._visual_servo_state == VisualServoStates.ROTATE:\n\t\t\ttarget_width = self.get_target_forward_line_pixel_x(point.y)\n\t\t\t# If the object is not at the target width, rotate until it is\n\t\t\tif point.x > target_width+self._target_window_halfwidth_rotate:\n\t\t\t\terror = point.x - target_width\n\t\t\t\tpid_controller_output = self.update_pid_controller(error, delta_time)\n\t\t\t\ttwist.angular.z = -pid_controller_output\n\t\t\t\ttwist.angular.y = 0.0\n\t\t\t\ttwist.angular.x = 0.0\n\t\t\t\ttwist.linear.x = 0.0\n\t\t\t\ttwist.linear.y = 0.0\n\t\t\t\ttwist.linear.z = 0.0\n\t\t\telif point.x < target_width-self._target_window_halfwidth_rotate:\n\t\t\t\terror = target_width - point.x\n\t\t\t\tpid_controller_output = self.update_pid_controller(error, delta_time)\n\t\t\t\ttwist.angular.z = pid_controller_output\n\t\t\t\ttwist.angular.y = 0.0\n\t\t\t\ttwist.angular.x = 0.0\n\t\t\t\ttwist.linear.x = 0.0\n\t\t\t\ttwist.linear.y = 0.0\n\t\t\t\ttwist.linear.z = 0.0\n\t\t\telse:\n\t\t\t\tself.goto_state(VisualServoStates.MOVE_FORWARD)\n\n\t\tif self._visual_servo_state == VisualServoStates.MOVE_FORWARD:\n\t\t\t# Make sure the object is still aligned with the forward line\n\t\t\ttarget_width = self.get_target_forward_line_pixel_x(point.y)\n\t\t\tif point.x > target_width+self._target_window_halfwidth_move_forward or point.x < target_width-self._target_window_halfwidth_move_forward:\n\t\t\t\tself.goto_state(VisualServoStates.ROTATE)\n\t\t\telse:\n\t\t\t\t# If the object is not aligned at the right location along the forward vector in the image, move forward or backwards\n\t\t\t\tif point.y < (self._camera_left_target_pixel_y-self._target_window_halfheight_move_forward):\n\t\t\t\t\terror = self._camera_left_target_pixel_y-self._target_window_halfheight_move_forward-point.y\n\t\t\t\t\tpid_controller_output = self.update_pid_controller(error, delta_time)\n\t\t\t\t\ttwist.angular.z = 0.0\n\t\t\t\t\ttwist.angular.y = 0.0\n\t\t\t\t\ttwist.angular.x = 0.0\n\t\t\t\t\ttwist.linear.x = pid_controller_output\n\t\t\t\t\ttwist.linear.y = 0.0\n\t\t\t\t\ttwist.linear.z = 0.0\n\t\t\t\telif point.y > (self._camera_left_target_pixel_y+self._target_window_halfheight_move_forward):\n\t\t\t\t\terror = point.y-(self._camera_left_target_pixel_y+self._target_window_halfheight_move_forward)\n\t\t\t\t\tpid_controller_output = self.update_pid_controller(error, delta_time)\n\t\t\t\t\ttwist.angular.z = 0.0\n\t\t\t\t\ttwist.angular.y = 0.0\n\t\t\t\t\ttwist.angular.x = 0.0\n\t\t\t\t\ttwist.linear.x = -pid_controller_output\n\t\t\t\t\ttwist.linear.y = 0.0\n\t\t\t\t\ttwist.linear.z = 0.0\n\t\t\t\t# Else the object should be aligned at the proper location in the image\n\t\t\t\telse:\n\t\t\t\t\tself._has_succeeded = True\n\t\t\t\t\ttwist.angular.z = 0.0\n\t\t\t\t\ttwist.angular.y = 0.0\n\t\t\t\t\ttwist.angular.x = 0.0\n\t\t\t\t\ttwist.linear.x = 0.0\n\t\t\t\t\ttwist.linear.y = 0.0\n\t\t\t\t\ttwist.linear.z = 0.0\n\n\t\tif self._visual_servo_state == VisualServoStates.STOP_AND_WAIT:\n\t\t\t# This handles cases where no input is received from the system\n\t\t\t# for a while. In this case, slow the robot down to a stop and\n\t\t\t# wait for the input to start up again. This employs a Hermitian\n\t\t\t# spline (h00)\n\t\t\ttwist = self._previous_twist\n\t\t\tself._stop_wait_timer = self._stop_wait_timer + delta_time\n\t\t\tif self._stop_wait_timer > 1.0:\n\t\t\t\tself._stop_wait_timer = 1.0\n\t\t\tspline_scalar = (1+2*self._stop_wait_timer)*(1-self._stop_wait_timer)*(1-self._stop_wait_timer)\n\t\t\ttwist.angular.z = spline_scalar*twist.angular.z\n\t\t\ttwist.angular.y = spline_scalar*twist.angular.y\n\t\t\ttwist.angular.x = spline_scalar*twist.angular.x\n\t\t\ttwist.linear.x = spline_scalar*twist.linear.x\n\t\t\ttwist.linear.y = spline_scalar*twist.linear.y\n\t\t\ttwist.linear.z = spline_scalar*twist.linear.z\n\n\t\t# Clamp the twist to very small velocities so the wheels have time\n\t\t# to steer in the right direction\n\t\tif self._new_state_wait_timer > 0.0:\n\t\t\ttwist.angular.z = numpy.clip(twist.angular.z, -0.001, 0.001)\n\t\t\ttwist.angular.y = numpy.clip(twist.angular.y, -0.001, 0.001)\n\t\t\ttwist.angular.x = numpy.clip(twist.angular.x, -0.001, 0.001)\n\t\t\ttwist.linear.x = numpy.clip(twist.linear.x, -0.001, 0.001)\n\t\t\ttwist.linear.y = numpy.clip(twist.linear.y, -0.001, 0.001)\n\t\t\ttwist.linear.z = numpy.clip(twist.linear.z, -0.001, 0.001)\n\t\telse:\n\t\t\t# Clamp the twist values so we don't... kill... anyone....\n\t\t\ttwist.angular.z = numpy.clip(twist.angular.z,\n\t\t\t\t-self._max_angular_velocity, self._max_angular_velocity)\n\t\t\ttwist.angular.y = 0\n\t\t\ttwist.angular.x = 0\n\t\t\ttwist.linear.x = numpy.clip(twist.linear.x,\n\t\t\t\t-self._max_linear_velocity, self._max_linear_velocity)\n\t\t\ttwist.linear.y = numpy.clip(twist.linear.y,\n\t\t\t\t-self._max_linear_velocity, self._max_linear_velocity)\n\t\t\ttwist.linear.z = numpy.clip(twist.linear.z,\n\t\t\t\t-self._max_linear_velocity, self._max_linear_velocity)\n\n\t\t# Do not update the previous twist if we are stopping and waiting\n\t\t# so we can ramp the twist down slowly to a stop\n\t\tif not self._visual_servo_state == VisualServoStates.STOP_AND_WAIT:\n\t\t\tself._previous_twist = twist\n\n\t\tself._publisher.publish(twist)\n\n\t\t# Set the action server error feedback to the distance between the centroid and the target location\n\t\tself._visual_servo_feedback.error = math.sqrt((point.x-self._camera_left_target_pixel_x)*(point.x-self._camera_left_target_pixel_x)+(point.y-self._camera_left_target_pixel_y)*(point.y-self._camera_left_target_pixel_y))\n\t\tself._visual_servo_feedback.state = self._visual_servo_state\n\n\tdef get_state_name(self):\n\t\tif self._visual_servo_state == VisualServoStates.SAFE_REGION:\n\t\t\treturn \"SAFE REGION\"\n\t\telif self._visual_servo_state == VisualServoStates.ROTATE:\n\t\t\treturn \"ROTATE\"\n\t\telif self._visual_servo_state == VisualServoStates.MOVE_FORWARD:\n\t\t\treturn \"MOVE FORWARD\"\n\t\telif self._visual_servo_state == VisualServoStates.STOP_AND_WAIT:\n\t\t\treturn \"STOP AND WAIT\"\n\n\tdef camera_left_info_callback(self, data):\n\t\tself._camera_left_image_width = data.width;\n\t\tself._camera_left_image_height = data.height;\n\n\tdef camera_right_info_callback(self, data):\n\t\tself._camera_right_image_width = data.width;\n\t\tself._camera_right_image_height = data.height;\n\n\tdef run_visual_servo_action(self, goal):\n\t\tupdate_rate = rospy.Rate(self._loop_frequency)\n\t\twhile not rospy.is_shutdown():\n\t\t\tself.do_visual_servo()\n\t\t\tif self._has_succeeded:\n\t\t\t\tself._visual_servo_result.success = True\n\t\t\t\tself._action_server.set_succeeded(result=self._visual_servo_result)\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tself._action_server.publish_feedback(self._visual_servo_feedback)\n\t\t\tif self._action_server.is_preempt_requested():\n\t\t\t\tbreak\n\t\t\tupdate_rate.sleep()\n\n\t\t# Catch all error handling. This should not run, but seems good to have\n\t\tif self._action_server.is_active():\n\t\t\tself._visual_servo_result.success = False\n\t\t\tself._action_server.set_aborted(self._visual_servo_result, \"Shutdown\")\n\n\t\tself.reset()\n\nif __name__ == '__main__':\n\trospy.init_node('visual_servo')\n\tvisual_servo = VisualServo()\n\t#visual_servo.run_visual_servo_action(True)\n\trospy.spin()\n","sub_path":"ros_workspace/src/visual_servo/nodes/visual_servo_node.py","file_name":"visual_servo_node.py","file_ext":"py","file_size_in_byte":16364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"291984380","text":"import numpy as np\nfrom numpy.random import randint\nfrom matplotlib import pyplot as plt\nimport time\nfrom PyQt5 import QtGui, QtCore\n#from applicartionIHM3 import MonAppli\n\n\nclass Boule(): # une boule (blanche ou colorée), ses caractéristiques (physiques et cinétiques)\n def __init__(self, x, y, r=0.3, m=1): # r le rayon, m la masse\n self.x = x\n self.y = y\n self.r = r\n self.m = m\n self.coord = np.array([self.x, self.y])\n self.vx = 0\n self.vy = 0\n self.vitesse = np.array([self.vx, self.vy])\n # self.ax, self.ay = 0,0\n\n def evolution(self, dt,k, eps = 0.5): # on suppose le mouvement rectiligne uniforme,\n \"\"\"\n on suppose le mouvement des boules rectiligne uniforme, en l'absence de collisions (bords ou autres boules).\n La position est fonction affine du temps\n entrée : float\n sortie : array -> nouvelles coordonnées de la boule\n \"\"\"\n if self.vx**2 + self.vy**2 < eps :\n self.vx = 0\n self.vy = 0\n return 0\n else :\n self.vx = k*self.vx\n self.vy = k * self.vy\n self.x += dt * self.vx\n self.y += dt * self.vy\n return 1\n\n def rebond(self, bord):\n \"\"\"\n simule un rebond sur une paroi droite\n entrée : string caractérisant la paroi sur laquelle il y a rebonb\n sortie : la nouvelle vitesse de la boule, après rebond\n \"\"\"\n if bord in ['N', 'S']:\n self.vy = - self.vy\n elif bord in ['O', 'E']:\n self.vx = - self.vx\n return self.vitesse\n\n def tombe(self):\n self.x, self.y, self.vx, self.z = -0.5,-0.5,0,0\n self.color = 'k'\n\n def coll(self, boule2):\n alpha = np.linspace (0,360,100)\n alpha = np.pi * alpha /180\n d = abs ((self.x + self.r - boule2.x)**2 + boule2.y**2 )\n angle = 0\n for a in alpha :\n da = abs ((self.x + self.r*np.cos (a) - boule2.x)**2 + (self.y + self.r*np.sin (a)- boule2.y)**2 )\n if d > da :\n angle, d = a , da # pour le point tangent au 2 boule, angle formé par Ox et la droite passant par le centre de la 1ere boule et le point tangent\n #angle_collision = (angle_b1 + angle)/2\n v1 = (self.vx**2 + self.vy**2)**0.5\n v2 = (boule2.vx ** 2 + boule2.vy ** 2) ** 0.5\n if v1 == 0 :\n if boule2.vx == 0:\n if boule2.vy < 0:\n angle_b1 = -np.pi / 2\n else:\n angle_b1 = np.pi / 2\n elif boule2.vy == 0:\n if boule2.vx > 0 :\n angle_b1 = np.pi\n else :\n angle_b1 = -np.pi\n else:\n if boule2.vy > 0 and boule2.vx > 0:\n angle_b1 = np.arctan(boule2.vy / boule2.vx) # angle_b1 direction de la boule mobile\n elif boule2.vy < 0 and boule2.vx > 0:\n angle_b1 = (- np.arctan(abs(boule2.vy / boule2.vx))) % (2 * np.pi)\n elif boule2.vy > 0 and boule2.vx < 0:\n angle_b1 = np.pi - np.arctan(abs(boule2.vy / boule2.vx))\n else:\n angle_b1 = np.pi + np.arctan(abs(boule2.vy / boule2.vx))\n angle = (angle + np.pi )% (2*np.pi)\n d_angle = (abs(angle_b1 - angle)) #\n v1_p = v2*np.cos(d_angle)\n v2_p = v2*np.sin (d_angle)\n boule2.vx, boule2.vy, self.vx, self.vy = v2_p*np.cos ((2*angle_b1 - angle)%2*np.pi), v2_p*np.sin ((2*angle_b1- angle)%2*np.pi), v1_p*np.cos (angle ), v1_p*np.sin (angle)\n else :\n if self.vx == 0:\n if self.vy < 0:\n angle_b1 = -np.pi / 2\n else:\n angle_b1 = np.pi / 2\n elif self.vy == 0:\n if self.vx > 0 :\n angle_b1 = np.pi\n else :\n angle_b1 = -np.pi\n else:\n if self.vy > 0 and self.vx > 0 :\n angle_b1 = np.arctan(self.vy / self.vx)\n elif self.vy<0 and self.vx > 0 :\n angle_b1 = (- np.arctan(abs(self.vy / self.vx))) % 2 * np.pi\n elif self.vy > 0 and self.vx< 0 :\n angle_b1 = np.pi - np.arctan(abs(self.vy / self.vx))\n else :\n angle_b1 = np.pi + np.arctan(abs(self.vy / self.vx))\n d_angle = abs(angle_b1 - angle) % (np.pi /2) #appatient à [0; pi/2]\n v1_p = v1*np.sin(d_angle)\n v2_p = v1*np.cos (d_angle)\n boule2.vx, boule2.vy, self.vx, self.vy = v2_p*np.cos (angle), v2_p*np.sin (angle), v1_p*np.cos ((2*angle_b1 - angle)%(2*np.pi)), v1_p*np.sin ((2*angle_b1 -angle)%(2*np.pi))\n print (\"angle :\", d_angle*180/np.pi, self.vx,self.vy,v1_p, v2_p)\n\n\nclass Boule_coloree(\n Boule): # on définit la classe représentant les boules colorées, classe qui hérite de la classe boule\n image = QtGui.QImage(\"rouge.jpg\")\n def __init__(self, x, y, r = 0.03):\n super().__init__(x, y)\n self.color = ['red', 'green', 'orange', 'blue'][randint(1, 4)]\n # une couleur au hasard pour chaque boule colorée\n\n def dessin(self, qp):\n qp.setPen(QtCore.Qt.red)\n qp.drawEllipse(10+self.x,20+ 1000- self.y, 12, 7)\n\n def dessinimage(self, qp):\n #qp.drawImage(QtCore.QRect(self.x - 10, self.y - 10, 20, 20), self.image)\n qp.drawImage(QtCore.QRect(10+40+ self.x , 701 - self.y + 10 + 76.2, 20, 20 ), self.image) #10+76.2+51.3+ 90 +621 - self.y,20,20), self.image) #à tester\n\nclass Boule_blanche(Boule): # on définit la classe représentant les boules colorées,\n image = QtGui.QImage(\"blanche.jpg\")\n def __init__(self, x, y, r = 0.03): #classe qui hérite de la classe boule\n super().__init__(x, y)\n self.color = 'yellow' # les boules blanches sont représentées en jaune par soucis de lisibilité\n\n def impulsion(self, cap_V0, norme_V0):\n \"\"\"Met en mouvement la boule blanche.\n Caractéristique propre aux boules blanches, elle sont propulsées par un coup de queue,\n représenté ici par une vitesse initiale non nulle v0\n entrée : array -> vitesse donnée à la boule blanche\n Modification effective de la vitesse de cette boule\n \"\"\"\n self.vy = norme_V0 * np.cos(cap_V0 * np.pi / 180) #v0[0]\n self.vx = norme_V0 * np.sin(cap_V0 * np.pi / 180) #v0[1]\n\n def dessin(self, qp):\n qp.setPen(QtCore.Qt.red)\n qp.drawEllipse(10+self.x, 20+ self.bn- self.y, 12, 7)\n\n def dessinimage(self, qp):\n #qp.drawImage(QtCore.QRect(self.x - 10, self.y - 10, 20, 20), self.image)\n qp.drawImage(QtCore.QRect(10+ 40+self.x ,701- self.y + 10 + 76.2, 20, 20), self.image) #10+76.2 + 51.3 + 90+ 621- self.y, 20, 20), self.image)\n\nclass Plateau(list): # le plateau est un espace délimité, composé d'une liste de boules\n def __init__(self, l=10, L=10, nb=1, nc=4, k = 0.98, mode = 0):\n super().__init__(self)\n self.bs, self.bn, self.bo, self.be = 0, l, 0, L\n self.nc, self.nb = nc, nb # nombre de boules colorées, et blanches\n self.n = nb + nc # nombre total de boules\n self.k = k\n self.mode = mode\n #self.T = np.array ([1 for i in range (self.n)])\n\n if self.mode == 1 : #Le joueur choisit où placer chaque boule\n for i in range(nb): # nomre de boules blanches sur le tapis\n print(\"placement d'une boule blanche\")\n self.append(Boule_blanche(float(input(\"abscisse\")), float(input(\"ordonnee\"))))\n for i in range(nc): # nombre de boules colorées sur le tapis\n print(\"placement d'une boule coloree\")\n self.append(Boule_coloree(float(input(\"abscisse\")), float(input(\"ordonnee\"))))\n\n elif self.mode == 2 : # Mode billard français\n self.append(Boule_blanche(0.2 * self.be, 0.8 * self.be, r = self.bo * 0.03/2.54))\n #self.append(Boule_blanche ( 100, 300, r=self.bo * 0.03 / 2.54))\n self.append(Boule_blanche(0.2* self.be, 0.3 * self.be, r = self.bo * 0.03/2.54))\n self.append(Boule_coloree(0.8 * self.be, 0.55 * self.be, r = self.bo * 0.03/2.54))\n self.n = 3\n\n elif self.mode == 3: # Mode billard anglais\n pass\n\n elif self.mode == 0 : #Les boules sont toutes placées aléatoirement\n for i in range(nb): # nomre de boules blanches sur le tapis\n self.append(Boule_blanche(randint(self.be), randint(self.bn)))\n for i in range(nc): # nombre de boules colorées sur le tapis\n self.append(Boule_coloree(randint(self.be), randint(self.bn)))\n\n def proche_bord(self, posx, posy, i):\n \"\"\"\n Si une boule est proche d'un bord, et qu'on constate que la boule se rapproche de ce bord,\n on appelle la fonction rebond, en précisant sur quel paroi il a lieu\n entrée : posx : liste des abscisses de chaque boule, posy : liste des ords de chaque boule, i : int\n \"\"\"\n if self[i].x < 0.02*self.be: # on est proche d'un bord\n if (len(posx[0]) <= 1) or (posx[i][-2] > self[i].x): # on vérifie qu'on est pas en tout début de simulation,\n Boule.rebond(self[i], 'O') # ou que l'on est pas déjà en train de repartir du bord\n elif self[i].x > self.be *(1- 0.02):\n if len(posx[0]) <= 1 or posx[i][-2] < self[i].x:\n Boule.rebond(self[i], 'E')\n elif self[i].y < 0.2*self.bn:\n if len(posx[0]) <= 1 or posy[i][-2] > self[i].y:\n Boule.rebond(self[i], 'S')\n elif self[i].y > self.bn * (1- 0.02):\n if len(posx[0]) <= 1 or posy[i][-2] < self[i].y:\n Boule.rebond(self[i], 'N')\n\n def collisions(self):\n \"\"\"\"\n Détection de chaque collision imminente entre les boules, et simulation de la déviation de trajectoire associée\n On mesure la distance entre chaque centre de boule. Si elle est trop proche, il y a collision : échange de quantité de mvt\n \"\"\"\n col = []\n for i in range(len(self) - 1):\n for j in range(i + 1, len(self)): # on teste la collision de chaque couple de boules une fois\n if ((self[i].x - self[j].x) ** 2 + (self[i].y - self[j].y) ** 2) ** 0.5 <= self[i].r + self[j].r:\n col.append([i, j]) # boules trop proches, leur trajectoire va être déviée par la collision\n for [i, j] in col:\n Boule.coll (self[i],self[j])\n #self[i].vx, self[i].vy, self[j].vx, self[j].vy = self[j].vx + (self[j].vy)/3, self[j].vy, self[i].vx + (self[i].vy)/3, self[i].vy\n # les boules échangent leur quantité de mouvement quand elles entrent en collision (toutes de masse identiques ici)\n\n def un_coup(self, dt,c,joueur=1):\n \"\"\"on simule un coup de queue :\n on met en mouvement la/les boules blanches, et on traite collisions entre boules et avec la paroi.\n On trace, la trajectoire de chaque boule, ainsi que sa position de départ (en noir) et d'arrivée (en rouge)\n \"\"\"\n print (\"c'est au joueur {} de jouer\".format (joueur))\n T = np.array ([1 for i in range (self.n)])\n Boule_blanche.impulsion(self[joueur], int(input(\"cap\")), float(input(\"Vitesse\"))) # 1 boule blanche\n t = 0\n #plt.figure(1)\n #plt.xlim((-0.5, self.bord_est+ 0.5))\n #plt.ylim((-0.5, self.bord_nord + .5))\n posx, posy = [[] for i in range(self.n)], [[] for i in\n range(self.n)] # pour garder en mémoire les positions passées\n for i in range(self.n):\n posx[i].append(self[i].x)\n posy[i].append(self[i].y)\n # plt.ion() , et surtout la précédente\n #for i in range (self.n):\n #plt.scatter(posx[i][0], posy[i][0], s=90, color='k') # point de départ de chaque boule, en noir\n #plt.scatter(posx[joueur][0], posy[joueur][0], s=90, color='y') # point de départ de chaque boule, en noir\n while any (T): # t < 15: # 15 est arbitraire et modulable\n for i in range(self.n):\n self.proche_bord(posx, posy, i) # on gère les rebonds sur les bords\n self.collisions() # on gère les collisions entre boules\n t += dt\n for i in range(self.n): # while self.T != np.array ([0 for i in range self.n]):\n T[i] = Boule.evolution(self[i], dt,self.k, 0.05*self.be) # détermination de la trajectoire de chaque boule, à l'instant t+1\n posx[i].append(self[i].x)\n posy[i].append(self[i].y)\n #MA = MonAppli ()\n # MA.ui.con.update()\n #if self.mode != 2:\n # for i in range (self.n):\n # self.proche_trou (self[i],i)\n #if len(posx[0]) > 1:\n #for i in range(self.n):\n #plt.plot([posx[i][-2], posx[i][-1]], [posy[i][-2], posy[i][-1]], color=self[i].color)\n #plt.title('trajectoire des boules, coup {}'.format(c))\n #time.sleep(1) #demander à Théo\n for i in range(self.n):\n #plt.scatter(posx[i], posy[i], s=60,\n # color=self[i].color) # ensemble des positions de chaque boule, à chaque instant t (pas de dt)\n #plt.scatter(posx[i][-1], posy[i][-1], s=60, color='r') # point d'arrivée de chaque boule, en rouge\n self[i].vx, self[i].vy = 0,0\n #plt.show()\n\nclass Partie ():\n def __init__ (self, nb_coups, dt, ll = 10, LL=10):\n self.nb_coups = nb_coups\n self.dt = dt\n self.c = 0 # on s'arrête à nb_coups\n #self.plato = plat\n self.points = [0,0] #en position 0, le joueur 2\n self.l = ll\n self.L= LL\n self.plat = Plateau(mode=2, l=self.l, L=self.L)\n\n def jouer (self) :\n i = 1\n while self.c < self.nb_coups :\n #plt.figure ()\n self.c+=1\n TEST = [self.plat[i%2 -1].vx,self.plat[i%2 -1].vy, self.plat[i%2 -2].vx, self.plat[i%2 -2].vy]\n Plateau.un_coup (self.plat, self.dt, self.c,i %2)\n if TEST[0] - self.plat[i%2 -1].vx == 0 and TEST [1] - self.plat[i%2 -1].vy and TEST[2] - self.plat[i%2 -2].vx == 0 and TEST [3] - self.plat[i%2 -3].vy ==0 :\n print (\"Vous avez marqué un point\")\n self.points [i %2] += 1\n else :\n print (\"Pas de chance... Au joueur suivant\")\n i += 1\n print (\"Joueur 1 : {} points /n Joueur 2 : {} points \".format (self.points[1], self.points[0]))\n if self.points[0] != self.points[1]:\n if self.points [0] > self.points [1]:\n g = 2\n elif self.points [0] > self.points [1]:\n g = 1\n print (\"Le joueur {} a gagné ! Félicitations !\".format (g))\n else :\n print (\"Egalité ! Bravo à vous deux !\")\n\nif __name__ == '__main__':\n p = Partie (3,0.1)\n Partie.jouer (p)\n #dt = 0.1 #0.2\n #nb_coups = 2\n #c = 0\n #plat = Plateau(mode = 0)\n #for _ in range(nb_coups):# on simule nb_coups coups\n # plt.figure ()\n # c += 1\n # Plateau.un_coup(plat, dt)\n #plt.show()\n\n# trous --------------->>\n# ralentissement des balles OK\n# positionnement initial -------->>\n# en temps réel\n#\n#préciser comment éxécuter le code\n#graph des classes adapté\n\n# !! Vmax = 4*R_b/dt\n#100 * Cte = Vmax - eps","sub_path":"Anciens codes/projet_7_Matthieu.py","file_name":"projet_7_Matthieu.py","file_ext":"py","file_size_in_byte":15644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"415853802","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom datetime import datetime, date\nimport cerberus\nimport unittest\nimport pickle\n\nclass SanheUnittest(unittest.TestCase):\n def setUp(self):\n schema = {\n \"a_date\": {\n \"type\": \"date\", \n \"after\": date(2000, 1, 1), \"before\": date(2015, 1, 1),\n },\n \"a_datetime\": {\n \"type\": \"datetime\",\n \"after\": datetime(2000, 1, 1), \"before\": datetime(2015, 1, 1),\n },\n \"a_bytes\": {\n \"type\": \"bytes\",\n \"minsize\": 100, \"maxsize\": 1000,\n },\n }\n self.v = cerberus.Validator(schema)\n \n def test_date(self):\n \"\"\"If date can pass the test, then datetime also should.\n \"\"\"\n self.assertFalse(self.v.validate({\"a_date\": \"2010-01-01\"}))\n self.assertTrue(self.v.validate({\"a_date\": date(2010, 1, 1)}))\n self.assertFalse(self.v.validate({\"a_date\": date(1990, 1, 1)}))\n self.assertEqual(self.v.errors[\"a_date\"], \n \"min value is datetime.date(2000, 1, 1)\")\n self.assertFalse(self.v.validate({\"a_date\": date(2020, 1, 1)}))\n self.assertEqual(self.v.errors[\"a_date\"], \n \"max value is datetime.date(2015, 1, 1)\")\n \n def test_bytes(self):\n self.assertFalse(self.v.validate({\"a_bytes\": \"abcdefg\"}))\n self.assertTrue(self.v.validate({\"a_bytes\": b\"abcdefg\" * 100}))\n \n value = pickle.dumps({i: i for i in range(1)})\n self.assertFalse(self.v.validate({\"a_bytes\": value}))\n self.assertEqual(self.v.errors[\"a_bytes\"],\n \"min size is 100 bytes\")\n \n value = pickle.dumps({i: i for i in range(1000)})\n self.assertFalse(self.v.validate({\"a_bytes\": value}))\n self.assertEqual(self.v.errors[\"a_bytes\"],\n \"max size is 1000 bytes\")\n\nif __name__ == \"__main__\":\n unittest.main()","sub_path":"sanhe_tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"3007083","text":"# script to make test data for treeserve, format below (all numbers except filename and filetype)\n#filename (Base64 encoded), size, userid, groupid, access, modification, creation, filetype (d or f), inode, linkcount, devid (last 3 not used)\nimport base64\nfrom random import randint\nimport gzip\nimport time\n#content = \"Lots of content here\"\n#with gzip.open('file.txt.gz', 'wb') as f:\n# f.write(content)\n\n#h = base64.b64encode(bytes('Hello World'))\nfile = open(\"testfile.dat\",\"w\") \n#file = gzip.open(\"testfile.dat.gz\", 'wb')\n# path, nodetype, group, user\nfilenames = [[\"/lustre/test\",\"d\", \"1\", \"1\"],[\"/lustre/test/one\",\"d\", \"1\", \"1\"], [\"/lustre/test/two\",\"d\", \"1\", \"1\"], [\"/lustre/test/one/another.txt\",\"f\", \"1\", \"1\"], [\"/lustre/test/one/yetanother.txt\",\"f\", \"1\", \"1\"], [\"/lustre/test/one/another.bam\",\"f\", \"1\", \"1\"], [\"/lustre/test/one/another.zip\",\"f\", \"2\", \"1\"], [\"/lustre/test/one/three\",\"d\", \"2\", \"1\"],[\"/lustre/test/one/three/yetanother.zip\",\"f\", \"2\", \"1\"],[\"/lustre/test/one/yetanother.zip\",\"f\", \"2\", \"1\"]]\nlength = len(filenames)\nfor filename in filenames: \n \n size = 10 #randint(2,10) #100\n groupid = filename[2]\n userid = filename[3]\n \n \n access = int(time.time()) + 300\n modification = int(time.time()) + 200\n creation = int(time.time()) + 100\n filetype = filename[1] \n inode = 1\n linkcount = 1\n devid = 1\n\n l = base64.b64encode(bytes(filename[0]))+\"\t\"+str(size)+\"\t\"+str(userid) + \"\t\" + str(groupid) + \"\t\" + str(access) + \"\t\" + str(modification) + \"\t\" + str(creation) + \"\t\"+ filetype + \"\t\" + str(inode) + \"\t\" + str(linkcount) + \"\t\" + str(devid) \n\n\n\n \n file.write(l + \"\\n\") \n\n\n\n\n \nfile.close() \n\n\n","sub_path":"maketestfile.py","file_name":"maketestfile.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"220280383","text":"\"\"\"Results relating to item connections.\"\"\"\nimport srctools\nimport utils\nimport instance_traits\nfrom conditions import (\n make_flag, make_result, make_result_setup,\n resolve_value, local_name,\n CONNECTIONS,\n)\nfrom conditions.instances import GLOBAL_INPUT_ENTS\nfrom srctools import Property, Entity, Output\n\nfrom typing import Optional, Dict, Tuple\n\nCOND_MOD_NAME = 'I/O'\n\nLOGGER = utils.getLogger(__name__, alias='cond.connections')\n\n# Traits set on item_cube.\nCUBE_TYPES = [\n 'cube_standard',\n 'cube_companion',\n 'cube_reflect',\n 'cube_ball',\n 'cube_franken',\n]\n\n@make_result_setup('AddOutput')\ndef res_add_output_setup(res: Property):\n output = res['output']\n input_name = res['input']\n inst_in = res['inst_in', '']\n inst_out = res['inst_out', '']\n targ = res['target']\n only_once = srctools.conv_bool(res['only_once', None])\n times = 1 if only_once else srctools.conv_int(res['times', None], -1)\n delay = res['delay', '0.0']\n parm = res['parm', '']\n\n if output.startswith('<') and output.endswith('>'):\n out_id, out_type = output.strip('<>').split(':', 1)\n out_id = out_id.casefold()\n out_type = out_type.strip().casefold()\n else:\n out_id, out_type = output, 'const'\n\n return (\n out_type,\n out_id,\n targ,\n input_name,\n parm,\n delay,\n times,\n inst_in,\n inst_out,\n )\n\n\n@make_result('AddOutput')\ndef res_add_output(inst: Entity, res: Property):\n \"\"\"Add an output from an instance to a global or local name.\n\n Values:\n - output: The output name.Can be or \n to lookup that item type.\n - target: The name of the target entity\n - input: The input to give\n - parm: Parameters for the input\n - delay: Delay for the output\n - only_once: True to make the input last only once (overrides times)\n - times: The number of times to trigger the input\n \"\"\"\n (\n out_type,\n out_id,\n targ,\n input_name,\n parm,\n delay,\n times,\n inst_in,\n inst_out,\n ) = res.value\n\n LOGGER.info('Conn: {}', res.value)\n\n if out_type in ('activate', 'deactivate'):\n try:\n connection = CONNECTIONS[out_id]\n except KeyError:\n LOGGER.warning('\"{}\" has no connections!', out_id)\n return\n if out_type[0] == 'a':\n inst_out, output = connection.out_act\n else:\n inst_out, output = connection.out_deact\n else:\n output = resolve_value(inst, out_id)\n inst_out = resolve_value(inst, inst_out)\n\n inst.add_out(Output(\n resolve_value(inst, output),\n local_name(inst, resolve_value(inst, targ)),\n resolve_value(inst, input_name),\n resolve_value(inst, parm),\n srctools.conv_float(resolve_value(inst, delay)),\n times=times,\n inst_out=resolve_value(inst, inst_out) or None,\n inst_in=resolve_value(inst, inst_in) or None,\n ))\n\n# Locking Input/Output items.\n# This makes for example pedestal buttons lock down until the target\n# item shuts itself off.\n\n# targetname -> inst, out_name, out_output, out_relay\nLOCKABLE_ITEMS = {} # type: Dict[str, Tuple[Entity, Optional[str], str, str]]\n\n\n@make_result('MarkLocking')\ndef res_locking_output(inst: Entity, res: Property):\n \"\"\"Marks an output item for locked connections.\n\n The parameter is an `instance:name;Output` value, which is fired when the\n item resets. This must be executed before `LockingIO`.\n\n This only applies if `$connectioncount` is 1.\n \"\"\"\n # Items with more than one connection have AND logic in the mix - it makes\n # it unsafe to lock the input item.\n if inst.fixup['$connectioncount'] != '1':\n return\n\n if res.has_children():\n name, output = Output.parse_name(res['output'])\n relay_name = res['rl_name', None]\n else:\n name, output = Output.parse_name(res.value)\n relay_name = None\n\n LOCKABLE_ITEMS[inst['targetname']] = inst, name, output, relay_name\n\n\n@make_flag('LockingIO')\ndef res_locking_input(inst: Entity, res: Property):\n \"\"\"Executed on the input item, and evaluates to True if successful.\n\n The parameter is an `instance:name;Input` value, which resets the item.\n This must be executed after the `MarkLocking` results have run.\n \"\"\"\n from vbsp import IND_ITEM_NAMES, IND_PANEL_NAMES, VMF\n in_name, in_inp = Output.parse_name(res.value)\n\n targets = {\n out.target\n for out in\n inst.outputs\n # Skip toggle or indicator panel items.\n if out.target not in IND_ITEM_NAMES\n }\n # No outputs, or 2+ - we can't convert in that case\n if len(targets) != 1:\n return False\n\n target, = targets\n try:\n targ_inst, targ_out_name, targ_out, out_relay = LOCKABLE_ITEMS[target]\n except KeyError:\n # Some other item...\n return False\n\n # Remove the indicator panel instances.\n ind_panels = {\n out.target\n for out in\n inst.outputs\n # Skip toggle or indicator panel items.\n if out.target in IND_PANEL_NAMES\n }\n for pan_inst in VMF.by_class['func_instance']:\n if pan_inst['targetname'] in ind_panels:\n pan_inst.remove()\n\n # Add an output pointing in the opposite direction.\n if out_relay is None:\n targ_inst.add_out(Output(\n out=targ_out,\n inst_out=targ_out_name,\n targ=inst['targetname'],\n inp=in_inp,\n inst_in=in_name,\n ))\n else:\n from conditions.instances import add_global_input\n add_global_input(\n inst,\n in_name,\n in_inp,\n rl_name=out_relay,\n output=targ_out,\n )\n return True\n\nLINKED_CUBES = {} # type: Dict[int, Tuple[Entity, Optional[str], str]]\n\n\n@make_result('_MarkLinkedCube')\ndef res_linked_cube(inst: Entity, res: Property):\n \"\"\"Marks a cube to link it to a dropper.\n\n This assumes some things about the item.\n \"\"\"\n time = inst.fixup.int('$timer_delay')\n # Portal 2 bug - when loading existing maps, timers are set to 3...\n if not (3 < time <= 30):\n # Infinite or 3-second - this behaviour is disabled..\n return\n\n if time in LINKED_CUBES:\n raise Exception(\n 'Two cubes have the same '\n '\"linkage\" value set ({})!'.format(\n time,\n )\n )\n\n resp_out_name, resp_out = Output.parse_name(res.value)\n\n LINKED_CUBES[time] = (\n inst,\n resp_out_name, resp_out,\n )\n\n\n@make_result('LinkedCubeDropper')\ndef res_linked_cube_dropper(drp_inst: Entity, res: Property):\n \"\"\"Link a cube and dropper together, to preplace the cube at a location.\"\"\"\n time = drp_inst.fixup.int('$timer_delay')\n # Portal 2 bug - when loading existing maps, timers are set to 3...\n if not (3 < time <= 30):\n # Infinite or 3-second - this behaviour is disabled..\n return\n\n try:\n cube_inst, resp_out_name, resp_out = LINKED_CUBES[time]\n except KeyError:\n raise Exception('Unknown cube \"linkage\" value ({}) in dropper!'.format(\n time,\n ))\n\n # Force the dropper to match the cube..\n if '$cube_type' in cube_inst.fixup:\n # Trust instvar if set (custom items for example)\n drp_inst.fixup['$cube_type'] = cube_inst.fixup['$cube_type']\n else:\n cube_traits = instance_traits.get(cube_inst)\n for ind, cube_type in enumerate(CUBE_TYPES):\n if cube_type in cube_traits:\n drp_inst.fixup['$cube_type'] = ind\n break\n else:\n LOGGER.warning('Cube \"{}\" has no cube type traits!', cube_inst['targetname'])\n\n # Set auto-drop to False (so there isn't two cubes),\n # and auto-respawn to True (so it actually functions).\n drp_inst.fixup['$disable_autodrop'] = '1'\n drp_inst.fixup['$disable_autorespawn'] = '0'\n\n fizz_out_name, fizz_out = Output.parse_name(res['FizzleOut'])\n\n # Output to destroy the cube when the dropper is triggered externally.\n drp_inst.add_out(Output(\n inst_out=fizz_out_name,\n out=fizz_out,\n targ=local_name(cube_inst, 'cube'),\n inp='Dissolve',\n only_once=True,\n ))\n\n # Cube items don't have proxies, so we need to use AddOutput\n # after it's created (@relay_spawn_3's time).\n try:\n relay_spawn_3 = GLOBAL_INPUT_ENTS['@relay_spawn_3']\n except KeyError:\n relay_spawn_3 = GLOBAL_INPUT_ENTS['@relay_spawn_3'] = cube_inst.map.create_ent(\n classname='logic_relay',\n targetname='@relay_spawn_3',\n origin=cube_inst['origin'],\n )\n\n respawn_inp = list(res.find_all('RespawnIn'))\n # There's some voice-logic specific to companion cubes.\n respawn_inp.extend(res.find_all(\n 'RespawnCcube' if\n drp_inst.fixup['$cube_type'] == '1'\n else 'RespawnCube'\n ))\n\n for inp in respawn_inp:\n resp_in_name, resp_in = inp.value.split(':', 1)\n\n out = Output(\n out='OnFizzled',\n targ=drp_inst,\n inst_in=resp_in_name,\n inp=resp_in,\n only_once=True,\n )\n\n relay_spawn_3.add_out(Output(\n out='OnTrigger',\n targ=local_name(cube_inst, 'cube'),\n inp='AddOutput',\n param=out.gen_addoutput(),\n only_once=True,\n delay=0.01,\n ))\n","sub_path":"src/conditions/connections.py","file_name":"connections.py","file_ext":"py","file_size_in_byte":9504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"105322701","text":"import os\nimport tkinter as tk\nfrom tkinter import font\nfrom KEY_BNC.KEY_BNC import data_dirs\n\ndef show_splash(title, source_name, **formats):\n data_path = os.path.join(data_dirs[0], data_dirs[1], source_name)\n my_text = ''\n with open(data_path, encoding=\"utf8\") as f:\n my_text = f.read()\n\n root = tk.Tk()\n root.title(title)\n root.geometry(\"500x300\")\n textbox = tk.Text(root, width=40, wrap=tk.WORD, font=(\"Times New Roman\", 12))\n\n tscrollbar = tk.Scrollbar(root)\n tscrollbar.pack(side=tk.RIGHT, fill=tk.Y)\n tscrollbar.config(command=textbox.yview)\n\n textbox.pack(fill=tk.BOTH, expand=tk.YES)\n textbox.delete(1.0, tk.END)\n textbox.insert(\"1.0\", my_text)\n\n # Formatting\n for format_name in formats:\n for start, end in formats[format_name]:\n textbox.tag_add(format_name, start, end)\n\n textbox.tag_config('h1', font=(\"Times New Roman\", 14, font.BOLD), justify=tk.CENTER)\n textbox.tag_config('h2', font=(\"Times New Roman\", 13, font.BOLD))\n textbox.tag_config('bold', font=(\"Times New Roman\", 12, font.BOLD))\n\n textbox.config(yscrollcommand=tscrollbar.set, state=tk.DISABLED)\n\n root.update_idletasks()\n root.wm_attributes(\"-topmost\", 1)\n\n ## Run application\n root.mainloop()\n\ndef encoding_warning(file_names):\n num_skipped = len(file_names['ignored'])\n num_opened = len(file_names['guessed'])\n\n text = 'Warning:'\n if num_opened > 0:\n text += \"\\n{} files were opened but may contain errors as they are not encoded as UTF8.\".format(num_opened)\n if num_skipped > 0:\n text += \"\\n{} files were skipped. Please make sure that they are TXT files.\".format(num_skipped)\n if num_opened > 0 :\n text += \"\\n\\nOpened files:\\n{}\".format(\"\\n\".join(file_names['guessed']))\n if num_skipped > 0 :\n text += \"\\n\\nSkipped files:\\n{}\".format(\"\\n\".join(file_names['ignored']))\n\n root = tk.Tk()\n root.title(\"Warning\")\n root.geometry(\"500x300\")\n\n tk.Button(root, text=\"Close\", activebackground=\"white\", bg=\"white\", command=lambda: root.destroy()).pack(side=tk.BOTTOM)\n\n textbox = tk.Text(root, width=40)\n\n tscrollbar = tk.Scrollbar(root)\n tscrollbar.pack(side=tk.RIGHT, fill=tk.Y)\n tscrollbar.config(command=textbox.yview)\n\n textbox.pack(fill=tk.BOTH)\n textbox.insert(tk.END, text)\n textbox.config(yscrollcommand=tscrollbar.set, state=tk.DISABLED)\n\n root.update_idletasks()\n root.wm_attributes(\"-topmost\", 1)\n\n ## Run appliction\n root.mainloop()\n","sub_path":"KEY_BNC/windows.py","file_name":"windows.py","file_ext":"py","file_size_in_byte":2503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"90415307","text":"import scipy.io as sio\nimport glob, os\nimport numpy as np\n\nmain_fol = 'G:\\data\\V7\\HCP'\nall_subj_fol = glob.glob(f'{main_fol}{os.sep}*{os.sep}cm{os.sep}')\nth='_histmatch_th'\natlas='yeo7_200'\nfor fol in all_subj_fol:\n sn = fol.split(os.sep)[-3]\n\n idx = np.load(f'{fol}{atlas}_cm_ord_lookup.npy')\n id = np.argsort(idx)\n\n axsi_file = rf'{fol}\\add_{atlas}_cm_ord{th}.npy'\n axsi_mat = np.asarray(np.load(axsi_file),dtype='float64')\n axsi_mat = axsi_mat[id]\n axsi_mat = axsi_mat[:, id]\n\n num_of_tracts_file = rf'{fol}\\num_{atlas}_cm_ord{th}.npy'\n num_of_tracts_mat = np.asarray(np.load(num_of_tracts_file),dtype='float64')\n num_of_tracts_mat = num_of_tracts_mat[id]\n num_of_tracts_mat = num_of_tracts_mat[:, id]\n\n fa_file = rf'{fol}\\fa_{atlas}_cm_ord{th}.npy'\n fa_mat = np.asarray(np.load(fa_file),dtype='float64')\n fa_mat = fa_mat[id]\n fa_mat = fa_mat[:, id]\n\n mat_file_name = rf'{fol}{sn}_{atlas}{th}.mat'\n sio.savemat(mat_file_name, {'axsi': axsi_mat,'number_of_tracts':num_of_tracts_mat,'fa':fa_mat})\n\n\n\n","sub_path":"HCP_network_analysis/HCP_cm/save_cm_as_mat_file.py","file_name":"save_cm_as_mat_file.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"79831719","text":"from JumpScale import j\nfrom fabric.api import settings\nimport re \nimport netaddr\n\nclass NetworkingErro(Exception):\n pass\n\nclass UnixNetworkManager(object):\n\n def __init__(self, manager):\n self.manager = manager\n self._nics = None\n \n def _nicExists(self, nic):\n if nic not in self.nics:\n raise NetworkingErro('Invalid NIC')\n\n def ipGet(self, device):\n \"\"\"\n Get IP of devie\n Result (ip, netmask, gateway)\n \"\"\"\n self._nicExists(device)\n cmd = 'echo `ip a | grep %s | sed -n 2p | xargs | cut -d \" \" -f 2`' % device\n res = self.manager.connection.run(cmd)\n ipmask = netaddr.IPNetwork(res)\n netmask = str(ipmask.netmask)\n ip = str(ipmask.ip) \n return (ip, netmask)\n \n def ipSet(self, device, ip=None, netmask=None, gw=None, inet='dhcp', commit=False):\n \"\"\"\n Return all interfaces that has this ifname\n \"\"\"\n self._nicExists(device)\n \n if inet not in ['static', 'dhcp']:\n raise ValueError('Invalid inet .. use either dhcp or static')\n \n if inet == 'static' and (not ip or not netmask):\n raise ValueError('ip, and netmask, are required in static inet.')\n \n file = '/etc/network/interfaces.d/%s' % device\n content = 'auto %s\\n' % device\n\n if inet == 'dhcp':\n content += 'iface %s inet dhcp\\n' % device\n else:\n content += 'iface %s inet static\\naddress %s\\nnetmask %s\\n' % (device, ip, netmask)\n if gw:\n content += 'gateway %s\\n' % gw\n \n self.manager.connection.file_write(file, content)\n \n if commit:\n self.commit(device)\n else:\n j.logger.log('Do NOT FORGET TO COMMIT', 2)\n\n def ipReset(self, device, commit=False):\n self._nicExists(device)\n file = '/etc/network/interfaces.d/%s' % device\n self.manager.connection.file_write(file, '')\n \n if commit:\n self.commit()\n else:\n j.logger.log('Do NOT FORGET TO COMMIT', 2)\n\n @property\n def nics(self):\n if self._nics is None:\n ifaces = self.manager.connection.run('ls --color=never -1 /sys/class/net')\n self._nics = ifaces.split('\\r\\n')\n return self._nics\n\n\n def nsGet(self):\n file = self.manager.connection.file_read('/etc/resolv.conf')\n results = []\n\n for line in file.split('\\n'): \n nameserver = re.search(r'\\b(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\\b',line)\n if nameserver:\n nameserver = nameserver.string.replace('nameserver', '').strip()\n results.append(nameserver)\n return results\n\n def nsSet(self, nameservers=[], commit=False):\n if not nameservers:\n raise ValueError('You need to provide at least one DNS server')\n if not isinstance(nameservers, list):\n raise ValueError('nameservers must be a list')\n \n content = '#EDITED BY JUMPSCALE NETWORK MANAGER\\n'\n content += '#DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN\\n'\n \n for ns in nameservers:\n content += 'nameserver %s\\n' % ns\n self.manager.connection.file_write('/etc/resolv.conf', content)\n\n if commit:\n self.commit()\n else:\n j.logger.log('Do NOT FORGET TO COMMIT', 2)\n\n def commit(self, device=None):\n #- make sure loopback exist\n content = 'auto lo\\niface lo inet loopback\\n'\n self.manager.connection.file_write('/etc/network/interfaces.d/lo', content)\n \n with settings(abort_exception=NetworkingErro):\n self.manager.connection.upstart_restart('networking')\n if device:\n j.logger.log('Restarting interface %s' % device, 2)\n self.manager.connection.run('ifdown %s && ifup %s' % (device, device))\n j.logger.log('DONE', 2)","sub_path":"lib/JumpScale/lib/ssh/unix/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":4028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"491000578","text":"#! /usr/bin/env python\n#encoding: utf-8\n\n# book, movie, music\n# at most 10 movies can be allocated\nclass Collection:\n\tdef __init__(self, client):\n\t\tself.client=client\n\t\n\tdef getItems(self, id, cat, start_index=1, max_results=50):\n\t\tdat={'cat':cat, 'start-index':start_index, 'max-results':max_results}\n\t\treturn self.client.get('/people/%d/collection' % id, 'feed', dat)\n\t\n\t# status = {watched, wish}\n\tdef getMovies(self, id, status):\n\t\tdat={'cat':'movie', 'max-results':50, 'status':status}\n\t\treturn self.client.get('/people/%d/collection' % id, 'feed', dat)\n\t\n\tdef getItemsAll(self, id, cat, maxN=500):\n\t\tfeeds=self.getItems(id, cat)\n\t\tif feeds is None: return []\n\t\trst=[item for item in feeds.entries]\n\t\tmaxN=min(int(feeds.feed.opensearch_totalresults), maxN)\n\t\tstart=51\n\t\twhile start>> def iseven(x):\n ... return x % 2 == 0\n >>> list(remove(iseven, [1, 2, 3, 4]))\n [1, 3]\n \"\"\"\n return filter(lambda x: not predicate(x), coll)\n\n\ndef accumulate(binop, seq):\n \"\"\" Repeatedly apply binary function f to a sequence, accumulating results\n\n >>> from operator import add, mul\n >>> list(accumulate(add, [1, 2, 3, 4, 5]))\n [1, 3, 6, 10, 15]\n >>> list(accumulate(mul, [1, 2, 3, 4, 5]))\n [1, 2, 6, 24, 120]\n\n Accumulate is similar to ``reduce`` and is good for making functions like\n cumulative sum:\n\n >>> from functools import partial, reduce\n >>> sum = partial(reduce, add)\n >>> cumsum = partial(accumulate, add)\n\n See Also:\n itertools.accumulate : In standard itertools for Python 3.2+\n \"\"\"\n result = next(iter(seq))\n yield result\n for elem in itertools.islice(seq, 1, None):\n result = binop(result, elem)\n yield result\n\n\ndef groupby(f, coll):\n \"\"\" Group a collection by a key function\n\n >>> names = ['Alice', 'Bob', 'Charlie', 'Dan', 'Edith', 'Frank']\n >>> groupby(len, names)\n {3: ['Bob', 'Dan'], 5: ['Alice', 'Edith', 'Frank'], 7: ['Charlie']}\n\n >>> iseven = lambda x: x % 2 == 0\n >>> groupby(iseven, [1, 2, 3, 4, 5, 6, 7, 8])\n {False: [1, 3, 5, 7], True: [2, 4, 6, 8]}\n\n See Also:\n ``countby``\n \"\"\"\n d = dict()\n for item in coll:\n key = f(item)\n if key not in d:\n d[key] = []\n d[key].append(item)\n return d\n\n\ndef merge_sorted(*iters, **kwargs):\n \"\"\" Merge and sort a collection of sorted collections\n\n >>> list(merge_sorted([1, 3, 5], [2, 4, 6]))\n [1, 2, 3, 4, 5, 6]\n\n >>> ''.join(merge_sorted('abc', 'abc', 'abc'))\n 'aaabbbccc'\n \"\"\"\n key = kwargs.get('key', identity)\n iters = map(iter, iters)\n pq = Queue.PriorityQueue()\n\n def inject_first_element(it, tiebreaker=None):\n try:\n item = next(it)\n pq.put((key(item), item, tiebreaker, it))\n except StopIteration:\n pass\n\n # Initial population\n for i, it in enumerate(iters):\n inject_first_element(it, i)\n\n # Repeatedly yield and then repopulate from the same iterator\n while not pq.empty():\n _, item, tb, it = pq.get()\n yield item\n inject_first_element(it, tb)\n\n\ndef interleave(seqs, pass_exceptions=()):\n \"\"\" Interleave a sequence of sequences\n\n >>> list(interleave([[1, 2], [3, 4]]))\n [1, 3, 2, 4]\n\n >>> ''.join(interleave(('ABC', 'XY')))\n 'AXBYC'\n\n Both the individual sequences and the sequence of sequences may be infinite\n\n Returns a lazy iterator\n \"\"\"\n iters = map(iter, seqs)\n while iters:\n newiters = []\n for itr in iters:\n try:\n yield next(itr)\n newiters.append(itr)\n except (StopIteration,) + tuple(pass_exceptions):\n pass\n iters = newiters\n\n\ndef unique(seq, key=identity):\n \"\"\" Return only unique elements of a sequence\n\n >>> tuple(unique((1, 2, 3)))\n (1, 2, 3)\n >>> tuple(unique((1, 2, 1, 3)))\n (1, 2, 3)\n\n Uniqueness can be defined by key keyword\n\n >>> tuple(unique(['cat', 'mouse', 'dog', 'hen'], key=len))\n ('cat', 'mouse')\n \"\"\"\n seen = set()\n for item in seq:\n tag = key(item)\n if tag not in seen:\n seen.add(tag)\n yield item\n\n\ndef intersection(*seqs):\n \"\"\" Lazily evaluated intersection of sequences\n\n >>> list(intersection([1, 2, 3], [2, 3, 4]))\n [2, 3]\n \"\"\"\n return (item for item in seqs[0]\n if all(item in seq for seq in seqs[1:]))\n\n\ndef isiterable(x):\n \"\"\" Is x iterable?\n\n >>> isiterable([1, 2, 3])\n True\n >>> isiterable('abc')\n True\n >>> isiterable(5)\n False\n \"\"\"\n try:\n iter(x)\n return True\n except TypeError:\n return False\n\n\ndef isdistinct(seq):\n \"\"\" All values in sequence are distinct\n\n >>> isdistinct([1, 2, 3])\n True\n >>> isdistinct([1, 2, 1])\n False\n\n >>> isdistinct(\"Hello\")\n False\n >>> isdistinct(\"World\")\n True\n \"\"\"\n return len(seq) == len(set(seq))\n\n\ndef take(n, seq):\n \"\"\" The first n elements of a sequence\n\n >>> list(take(2, [10, 20, 30, 40, 50]))\n [10, 20]\n \"\"\"\n return itertools.islice(seq, n)\n\n\ndef drop(n, seq):\n \"\"\" The sequence following the first n elements\n\n >>> list(drop(2, [10, 20, 30, 40, 50]))\n [30, 40, 50]\n \"\"\"\n return itertools.islice(seq, n, None)\n\n\ndef first(seq):\n \"\"\" The first element in a sequence\n\n >>> first('ABC')\n 'A'\n \"\"\"\n return next(iter(seq))\n\n\ndef nth(n, seq):\n \"\"\" The nth element in a sequence\n\n >>> nth(1, 'ABC')\n 'B'\n \"\"\"\n try:\n return seq[n]\n except TypeError:\n return next(itertools.islice(seq, n, None))\n\n\ndef last(seq):\n \"\"\" The last element in a sequence\n\n >>> last('ABC')\n 'C'\n \"\"\"\n try:\n return seq[-1]\n except TypeError:\n old = None\n it = iter(seq)\n while True:\n try:\n old = next(it)\n except StopIteration:\n return old\n\n\nsecond = partial(nth, 1)\nrest = partial(drop, 1)\n\n\nno_default = '__no__default__'\n\n\ndef get(ind, seq, default=no_default):\n \"\"\" Get element in a sequence or dict\n\n Provides standard indexing\n\n >>> get(1, 'ABC') # Same as 'ABC'[1]\n 'B'\n\n Pass a list to get multiple values\n\n >>> get([1, 2], 'ABC') # ('ABC'[1], 'ABC'[2])\n ('B', 'C')\n\n Works on any value that supports indexing/getitem\n For example here we see that it works with dictionaries\n\n >>> phonebook = {'Alice': '555-1234',\n ... 'Bob': '555-5678',\n ... 'Charlie':'555-9999'}\n >>> get('Alice', phonebook)\n '555-1234'\n\n >>> get(['Alice', 'Bob'], phonebook)\n ('555-1234', '555-5678')\n\n Provide a default for missing values\n\n >>> get(['Alice', 'Dennis'], phonebook, None)\n ('555-1234', None)\n \"\"\"\n if isinstance(ind, list):\n return tuple(get(i, seq, default) for i in ind)\n if default is no_default:\n return seq[ind]\n else:\n try:\n return seq[ind]\n except (KeyError, IndexError):\n return default\n\n\ndef concat(seqs):\n \"\"\" Concatenate zero or more iterables, any of which may be infinite.\n\n An infinite sequence will prevent the rest of the arguments from\n being included.\n\n We use chain.from_iterable rather than chain(*seqs) so that seqs\n can be a generator.\n\n >>> list(concat([[], [1], [2, 3]]))\n [1, 2, 3]\n\n See also:\n itertools.chain.from_iterable equivalent\n \"\"\"\n return itertools.chain.from_iterable(seqs)\n\n\ndef concatv(*seqs):\n \"\"\" Variadic version of concat\n\n >>> list(concatv([], [\"a\"], [\"b\", \"c\"]))\n ['a', 'b', 'c']\n\n See also:\n itertools.chain\n \"\"\"\n return concat(seqs)\n\n\ndef mapcat(f, seqs):\n \"\"\" Apply f to each sequence in seqs, concatenating results\n\n >>> list(mapcat(lambda s: [c.upper() for c in s],\n ... [[\"a\", \"b\"], [\"c\", \"d\", \"e\"]]))\n ['A', 'B', 'C', 'D', 'E']\n \"\"\"\n return concat(map(f, seqs))\n\n\ndef cons(el, seq):\n \"\"\" Add el to beginning of (possibly infinite) sequence seq.\n\n >>> list(cons(1, [2, 3]))\n [1, 2, 3]\n \"\"\"\n yield el\n for s in seq:\n yield s\n\n\ndef interpose(el, seq):\n \"\"\" Introduce element between each pair of elements in seq\n\n >>> list(interpose(\"a\", [1, 2, 3]))\n [1, 'a', 2, 'a', 3]\n \"\"\"\n return rest(mapcat(lambda x: [el, x], seq))\n\n\ndef frequencies(seq):\n \"\"\" Find number of occurrences of each value in seq\n\n >>> frequencies(['cat', 'cat', 'ox', 'pig', 'pig', 'cat']) #doctest: +SKIP\n {'cat': 3, 'ox': 1, 'pig': 2}\n\n See Also:\n countby\n groupby\n \"\"\"\n d = dict()\n for item in seq:\n try:\n d[item] += 1\n except KeyError:\n d[item] = 1\n return d\n\n\ndef reduceby(keyfn, binop, seq, init):\n \"\"\" Perform a simultaneous groupby and reduction\n\n The computation:\n\n >>> result = reduceby(keyfn, binop, seq, init) # doctest: +SKIP\n\n is equivalent to the following:\n\n >>> def reduction(group): # doctest: +SKIP\n ... return reduce(binop, group, init) # doctest: +SKIP\n\n >>> groups = groupby(keyfn, seq) # doctest: +SKIP\n >>> result = valmap(reduction, groups) # doctest: +SKIP\n\n But the former does not build the intermediate groups, allowing it to\n operate in much less space. This makes it suitable for larger datasets\n that do not fit comfortably in memory\n\n >>> from operator import add, mul\n >>> data = [1, 2, 3, 4, 5]\n >>> iseven = lambda x: x % 2 == 0\n >>> reduceby(iseven, add, data, 0)\n {False: 9, True: 6}\n >>> reduceby(iseven, mul, data, 1)\n {False: 15, True: 8}\n\n >>> projects = [{'name': 'build roads', 'state': 'CA', 'cost': 1000000},\n ... {'name': 'fight crime', 'state': 'IL', 'cost': 100000},\n ... {'name': 'help farmers', 'state': 'IL', 'cost': 2000000},\n ... {'name': 'help farmers', 'state': 'CA', 'cost': 200000}]\n >>> reduceby(lambda x: x['state'], # doctest: +SKIP\n ... lambda acc, x: acc + x['cost'],\n ... projects, 0)\n {'CA': 1200000, 'IL': 2100000}\n \"\"\"\n d = {}\n for item in seq:\n key = keyfn(item)\n if key not in d:\n d[key] = init\n d[key] = binop(d[key], item)\n return d\n\n\ndef iterate(f, x):\n \"\"\" Repeatedly apply a function f onto an original input\n\n Yields x, then f(x), then f(f(x)), then f(f(f(x))), etc..\n\n >>> def inc(x): return x + 1\n >>> counter = iterate(inc, 0)\n >>> next(counter)\n 0\n >>> next(counter)\n 1\n >>> next(counter)\n 2\n\n >>> double = lambda x: x * 2\n >>> powers_of_two = iterate(double, 1)\n >>> next(powers_of_two)\n 1\n >>> next(powers_of_two)\n 2\n >>> next(powers_of_two)\n 4\n >>> next(powers_of_two)\n 8\n\n \"\"\"\n while True:\n yield x\n x = f(x)\n","sub_path":"toolz/itertoolz/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":10324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"33110363","text":"# Time complexity: O(n)\n# Space complexity: O(n)\n# Works on leetcode: yes\n# Approach: We save the frequency of the integers in a dictionary and iterate through it. Now we have 2 cases - 1. If k=0,\n# then we check if the freq of integer is more than 1, add it to count 2. Check if integer+k is in the dictionary to add it \n# to count.\nclass Solution:\n def findPairs(self, nums: List[int], k: int) -> int:\n if not nums or k<0:\n return 0\n mapping = collections.Counter(nums)\n count = 0\n for key,val in mapping.items():\n if k==0:\n if val>1 :\n count +=1 \n \n elif (key+k) in mapping:\n count +=1 \n return count \n ","sub_path":"Problem2.py","file_name":"Problem2.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"242616171","text":"__author__ = 'palonso0'\nimport pandas as pd\nimport json\nfrom collections import defaultdict\nfrom bokeh.plotting import figure, output_file, show,ColumnDataSource\nfrom bokeh.models import HoverTool\n\n\ncell = pd.read_csv('C:\\\\Desarrollo_Pablo\\\\Estad\\\\RSSI_ERI_Z6.csv',sep=';',decimal='.')\n\n\ncelda=cell['celda'].tolist()\nrssi_media=cell['RSSI_media'].tolist()\npersistencia=cell['persistencia'].tolist()\n\nsource = ColumnDataSource(\n data=dict(\n x=persistencia,\n y=rssi_media,\n desc=celda,\n )\n )\n\n# output to static HTML file\noutput_file(\"C:\\\\Desarrollo_Pablo\\\\Estad\\\\rssi.html\")\n\nTOOLS = [HoverTool()]\n\nhover = HoverTool(\n tooltips=[\n (\"PERSISTENCIA (DIAS):\", \"@x\"),\n (\"RSSI MEDIA\", \"@y\"),\n (\"CELDA\", \"@desc\"),\n ])\n\np = figure(plot_width=800, plot_height=800, title='Persistencia RSSI', tools=[hover])\n\np.xaxis.axis_label = 'PERSISTENCIA (DIAS)'\np.yaxis.axis_label = 'RSSI MEDIA'\n\n# add a circle renderer with a size, color, and alpha\np.circle('x', 'y', size=20, color=\"navy\", alpha=0.5,source=source)\n\n# show the results\nshow(p)\n\n\n","sub_path":"PreparaListasGrafica.py","file_name":"PreparaListasGrafica.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"436725784","text":"#! /usr/bin/env python\n\nfrom __future__ import division\n# import modules needed\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom timeit import default_timer as timer\n# Files imported\nfrom Cylinder_Geometry import Cylinder_Geometry\n# import SimFunctions #not used anymore\n\n\n\n############\n# References#\n############\n# 1. Internal Combustion Engines: Applied Thermal Sciences 2nd edition\n# author(s): Ferguson, Colin R.; Kirkpatrick, Allan T.\n# 2.\n\n# NOTES!\n# All units are SI standard (ex. kelvin, kilogram, meter, second, joules, pascals)\n\nclass System:\n def __init__(self):\n # properties\n self.ambient_temp = 300 # K\n self.ambient_pressure = 101325 # Pa\n\n # self.composition\n self.geom = Cylinder_Geometry()\n self.bore = 0.095 # m\n self.stroke = 0.0634 # m\n self.connecting_rod_length = 0.1074 # m\n self.compression_ratio = 13.5\n self.swept_volume = 0.0004494 # m^3\n self.clearance_volume = 0.00003808 # m^3\n self.total_volume = self.swept_volume + self.clearance_volume\n\n # intake\n self.intake_diameter = 0.02\n self.intake_area = math.pi * (self.intake_diameter ** 2) / 4\n\n # Valve Timing\n self.rpm = 5000\n self.intake_open = 40\n self.intake_close = 120\n self.exhaust_open = 535\n self.exhaust_close = 0\n self.spark_advance = -55\n self.ignition_start = 360 + self.spark_advance\n self.combustion_duration = 40\n self.AFR = 14.5 # mass ratio\n self.volumetric_efficiency = 0.8\n\n # fuel\n self.fuelType = 'gasoline'\n self.LHVgasoline = 44.40e6 # J/kg\n self.air_density = 1.225 # kg/m^3\n #\t#q_combustion appears off by 1000 times...units?\n self.Q_combustion = self.volumetric_efficiency * self.swept_volume * self.air_density * (\n 1 / self.AFR) * self.LHVgasoline\n\n # setup lists\n self.crank_angle = []\n self.volume = []\n self.time = []\n self.pressure = [self.ambient_pressure] ### THIS NEEDS TO HAVE AN INTAKE SIM\n self.temp = [self.ambient_temp]\n self.intake_valve = [0]\n self.exhaust_valve = [0]\n self.xb = [0]\n\n # discretization\n self.step = 0.1\n\n #############functions#####################\n def instantVolume(self, crank_angle):\n # cylinder volume at specific crank angle\n #print (crank_angle)\n instVol = self.clearance_volume + ((1 - self.geom.piston_position(crank_angle)) * self.swept_volume)\n return instVol\n\n def angle2time(self, angle_1, angle_2):\n # time difference between two crank angles\n dt = (angle_2 - angle_1) / (self.rpm * 60)\n return dt\n\n def gammaAir(self, temp):\n # gamma of air at specific temperature\n # source...\n return 1.40 - (7.18e-5 * temp)\n\n def airProperties(self, property):\n # properties of air at ~278 K\n self.basic_properties = {\n 'gamma': 1.4,\n 'cv': 0.714,\n 'cp': 1,\n 'R': 287.058,\n 'density': 1.225\n }\n return self.basic_properties[property]\n\n def areaCylinder(self, crank_angle):\n # surface area of cylinder at instant\n piston_area = math.pi * (self.bore ** 2) * 0.25\n wall_area = math.pi * self.bore * self.stroke * (1 - self.geom.piston_position(crank_angle))\n return wall_area + (piston_area * 2)\n\n # heat transfer coefficient function needs checking out, its throwing errors\n def heatTransferCoefficientWoschni(self, dQin=0):\n # equation 8.39 from Ferguson\n mean_piston_speed = 2 * self.stroke * self.rpm * (1 / 60)\n if self.intake_valve[-1] > 0 or self.exhaust_valve[-1] > 0:\n U = 6.18 * mean_piston_speed\n elif self.intake_valve[-1] == 0 and self.exhaust_valve[-1] == 0:\n V1 = self.volume[-2]\n gam = self.gammaAir(self.temp[-1])\n # state properties at intake valve closing\n P0 = self.state_intake_close[0]\n T0 = self.state_intake_close[1]\n V0 = self.state_intake_close[2]\n Vd = self.swept_volume # displacement volume\n dPc = ((gam - 1) / V1) * dQin # instantaneous pressure rise due to combustion\n U = (2.28 * mean_piston_speed) + (0.00324 * T0 * (Vd * dPc) * (1 / (V0 * P0)))\n P = self.pressure[-1] * 0.001 # convert to KPa for this instance\n T = self.temp[-1]\n b = self.bore\n # convective heat transfer coefficient (woschni)\n hg = 3.26 * (P ** 0.8) * (U ** 0.8) * (b ** -0.2) * (T ** -0.55)\n return hg\n\n def woschniHeatLoss(self, dQin=0):\n # equation 8.27 from Ferguson\n d_theta = self.crank_angle[-1] - self.crank_angle[-2]\n # convective heat transfer coefficient (function of theta)\n # hg=self.heatTransferCoefficientWoschni(dQin)\n hg = 3000 # fix function so it's not hard coded\n Aw = self.areaCylinder(self.crank_angle[-1])\n Tgas = self.temp[-1]\n Twall = 380 # 380 kelvin=225 Fahrenheit\n N = self.rpm / 120 # convert to power cycles per second\n # delta Q transferred to cylinder wall through convection\n dQout = d_theta * hg * Aw * (Tgas - Twall) / N\n return dQout\n\n def pressureUpdate(self, dQin=0, dQw=0):\n # equation 8.26 from Ferguson\n V2 = self.volume[-1]\n V1 = self.volume[-2]\n dV = V2 - V1\n P1 = self.pressure[-1]\n T1 = self.temp[-1]\n gam = self.gammaAir(T1)\n return P1 + (((gam - 1) / V1) * dQin) - dQw - (gam * (P1 / V1) * (dV))\n\n def tempUpdate(self, dQin=0, dQw=0):\n # Ferguson\n # 2 equations together\n V2 = self.volume[-1]\n V1 = self.volume[-2]\n T1 = self.temp[-1]\n Cv = 0.714 # calculate from JANAF or NASA coefficients (buttsworth matlab files)\n gam = self.gammaAir(T1)\n return (T1 * ((V1 / V2) ** (gam - 1))) + ((dQin - dQw) / Cv)\n\n def combustionStep(self, theta):\n # equation 2.22 from Ferguson (Single Wiebe)\n a = 6\n m = 1.75 # these constants can change alot\n combustion_duration = self.combustion_duration\n combustion_start = self.ignition_start\n xb = 1 - math.exp(-a * ((((theta) - combustion_start) / combustion_duration) ** (m + 1)))\n return xb\n\n #############Simulation#####################\n def simulation(self, rpm):\n # self explanatory\n\n self.sim_start_time = timer()\n\n self.rpm = rpm\n step = self.step\n theta = np.arange(0, 720, step)\n\n for i in theta:\n # Calculated for each step\n self.crank_angle.append(i)\n self.volume.append(self.instantVolume(i))\n self.time.append(self.angle2time(0, i))\n\n #########\n # intake stroke\n # equations (keeping it simple for now)\n if i > 0 and i <= 180:\n self.pressure.append(self.ambient_pressure)\n self.temp.append(self.ambient_temp)\n self.intake_valve.append(1)\n self.exhaust_valve.append(0)\n\n if i == self.intake_close:\n # saves state properties at intake valve closing for characteristic...\n # gas velocity used in woschni heat transfer coefficient calc above.\n self.state_intake_close = [self.pressure[-1], self.temp[-1], self.volume[-1]]\n\n ##########\n # compression stroke\n elif i > 180 and i <= 360:\n # valves still closed\n self.intake_valve.append(0)\n self.exhaust_valve.append(0)\n\n # compression w/o heat addition\n if i < self.ignition_start:\n # update state properties\n dQin = 0\n self.temp.append(self.tempUpdate(dQin))\n self.pressure.append(self.pressureUpdate(dQin))\n\n if i == self.intake_close:\n # saves state properties at intake valve closing for characteristic...\n # gas velocity used in woschni heat transfer coefficient calc above.\n self.state_intake_close = [self.pressure[-1], self.temp[-1], self.volume[-1]]\n\n # compression w/heat addition\n elif i >= self.ignition_start:\n # calculate burnt fraction\n self.xb.append(self.combustionStep(i))\n dxb = self.xb[-1] - self.xb[-2]\n dQin = dxb * self.Q_combustion # delta heat added to system through combustion\n # update state properties\n self.temp.append(self.tempUpdate(dQin))\n self.pressure.append(self.pressureUpdate(dQin))\n\n else:\n print ('Mistake in compression')\n\n ###############\n # Expansion Stroke\n elif i > 360 and i <= 540:\n # Convective heat transfer to walls\n dQw = self.woschniHeatLoss()\n\n # expansion w/heat addition\n if i > 360 and i <= (self.ignition_start + self.combustion_duration):\n # calculate burnt fraction\n self.xb.append(self.combustionStep(i))\n dxb = self.xb[-1] - self.xb[-2]\n dQin = dxb * self.Q_combustion # delta heat added to system through combustion\n # update state properties\n self.temp.append(self.tempUpdate(dQin, dQw))\n self.pressure.append(self.pressureUpdate(dQin))\n self.intake_valve.append(0)\n self.exhaust_valve.append(0)\n\n # expansion w/o heat addition\n elif i > (self.ignition_start + self.combustion_duration) and i <= self.exhaust_open:\n dQin = 0\n # update state properties\n self.temp.append(self.tempUpdate(dQin, dQw))\n self.pressure.append(self.pressureUpdate(dQin))\n self.intake_valve.append(0)\n self.exhaust_valve.append(0)\n\n # expansion w/ exhaust valve open\n elif i > self.exhaust_open and i <= 540:\n dQin = 0\n # update state properties\n self.temp.append(self.tempUpdate(dQin, dQw))\n self.pressure.append(self.pressureUpdate(dQin))\n self.intake_valve.append(0)\n self.exhaust_valve.append(1)\n\n else:\n print ('mistake in expansion')\n\n ###############\n # Exhaust Stroke\n elif i > 540 and i <= 720:\n self.temp.append(self.temp[-1])\n self.pressure.append(self.pressure[-1])\n self.intake_valve.append(0)\n self.exhaust_valve.append(1)\n\n self.sim_end_time = timer()\n return self.brakeTorque() * -0.1\n\n ######################################\n # simulation data processing functions\n\n def plotPV(self):\n plt.plot(self.volume, self.pressure)\n plt.title('P-V Diagram')\n plt.xlabel('Volume [m^3]')\n plt.ylabel('Pressure [Pa]')\n plt.show()\n\n def plotIt(self, yoMama):\n # temp, pres, volume, crank angle\n if yoMama == 'pressure':\n plt.plot(self.crank_angle, self.pressure)\n plt.plot([360, 360], [0, max(self.pressure) + 1E6])\n plt.title('pressure')\n plt.xlabel('crank angle [degrees]')\n plt.ylabel('pressure [Pa]')\n elif yoMama == 'temperature':\n plt.plot(self.crank_angle, self.temp)\n plt.title('temperature')\n plt.xlabel('crank angle [degrees]')\n plt.ylabel('Temperature [K]')\n elif yoMama == 'volume':\n plt.plot(self.crank_angle, self.volume)\n plt.title('volume')\n plt.xlabel('crank angle [degrees]')\n plt.ylabel('Volume [m^3]')\n elif yoMama == 'intake_valve':\n plt.plot(self.crank_angle, self.intake_valve)\n else:\n return \"Sumthin Wrong\"\n plt.show()\n\n def timeElapsed(self):\n return self.sim_end_time - self.sim_start_time\n\n def IMEPnet(self):\n return np.mean(self.pressure)\n\n def FMEP(self):\n return 200000\n\n def BMEP(self):\n return self.IMEPnet() - self.FMEP()\n\n def brakeTorque(self):\n # units [N*m]=[J]\n return self.BMEP() * self.swept_volume\n\n def power(self, units='watts'):\n # units [Watts]=[J/s]=[Nm/s]\n power = self.brakeTorque() * self.rpm * (1 / 60) * 2 * math.pi\n if units == 'W' or units == 'w' or units == 'Watts' or units == 'watts':\n return power\n elif units == 'KW' or units == 'kw' or units == 'Kw' or units == 'kW' or units == 'Kilowatts' or units == 'kilowatts':\n return power / 1000\n else:\n print ('Specify units, use watts or kilowatts.')\n\n\nclass RunSim:\n def __init__(self):\n cv = System()\n\n def runIt(self, range):\n l = np.arange(range[0], range[1], range[2])\n\n self.p = []\n self.t = []\n for i in l:\n self.t.append(cv.simulation(i))\n\n # plt.plot(l,self.p)\n plt.plot(l, self.t)\n plt.show()\n\n\nif __name__ == \"__main__\":\n print('nothing yet')\n i=9000\n #for i in range(1000,12000,1000):\n geom = Cylinder_Geometry\n # print geom.piston_position(0)\n cv = System()\n # print cv.gammaAir(300)\n cv.simulation(i)\n # print len(cv.crank_angle)\n # print len(cv.volume)\n # print len(cv.temp)\n # print len(cv.pressure)\n # print cv.timeElapsed()\n cv.plotPV()\n ##cv.plotIt('temperature')\n cv.plotIt('pressure')\n # cv.plotIt('volume')\n print (cv.IMEPnet())\n # print cv.BMEP()\n print (\"Brake Torque at\", i, \"rmp is\", cv.brakeTorque(), \"N-m\")\n print (\"Power at\", i, \"rmp is\", cv.power(), \"watts\")\n\n# rs=RunSim()\n# range=[2000,8000,100]\n# print rs.runIt(range)\n\n# things to add\n# calculator to find cv at each temp (see buttsworth.py and pdf)\n# JANAF, NASA\n# add heat loss to wall (woschni or annand)\n# friction losses\n# volumetric efficiency\n# ignition duration/combustion duration(rate time constant)\n# use Arrhenius equation\n","sub_path":"pypow/thermodynamics/simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":14499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"221814918","text":"from django.shortcuts import get_object_or_404\nfrom django.views.generic import list_detail\n\nfrom bookreader.models import Repository, Book\n\ndef browse(request, **kwargs):\n kwargs.setdefault('template_object_name','repository')\n kwargs.setdefault('queryset', Repository.objects.all())\n return list_detail.object_list(request, **kwargs)\n\ndef view(request, object_id, **kwargs):\n repository = get_object_or_404(Repository, pk=object_id)\n \n kwargs.setdefault('template_object_name','collection')\n kwargs.setdefault('template_name', 'bookreader/repository_detail.html')\n kwargs.setdefault('queryset', repository.collections.all())\n kwargs.setdefault('extra_context', {})\n kwargs['extra_context']['repository'] = repository\n \n return list_detail.object_list(request, **kwargs)\n \ndef books(request, object_id, **kwargs):\n repository = get_object_or_404(Repository, pk=object_id)\n \n kwargs.setdefault('template_object_name','book')\n kwargs.setdefault('template_name', 'bookreader/repository_books.html')\n kwargs.setdefault('queryset', Book.objects.filter(collection__repository=repository))\n kwargs.setdefault('extra_context', {})\n kwargs['extra_context']['repository'] = repository\n \n return list_detail.object_list(request, **kwargs)\n ","sub_path":"virtual/lib/python3.6/site-packages/bookreader/views/repository.py","file_name":"repository.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"5092856","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nimport rospy\nfrom std_msgs.msg import Int16\nimport random\nimport roslib\nimport sys\nimport cv2\nimport numpy as np\nimport statistics\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge, CvBridgeError\nrun = 1\n#Corgi State\nP1 = [470,120]\nP2 = [470,70]\nP3 = [500,120]\nP4 = [500,70]\n#Crop border\n\nlower_red = np.array([0, 0, 200])\nupper_red = np.array([5, 255, 255])\n\nlower_green = np.array([40,20,100])\nupper_green = np.array([100,255,255])\n\nlower_pink = np.array([255, 255, 255])\nupper_pink = np.array([255, 255, 255])\n#Magenta Increase 30 \"H\" range \ndef trafficgreen(frame):\n global run\n y1=70\n y2=120\n x1=370\n x2=420\n kernel = np.ones((5,5),np.float32)/25\n crop_frame = frame[ P2[1]:P1[1] , P1[0]:P3[0] ]\n res = cv2.filter2D(frame,-1,kernel)\n hsv = crop_frame \n mask = cv2.inRange(hsv, lower_red, upper_red)\n mask2 = cv2.inRange(hsv, lower_green, upper_green)\n red_traffic = cv2.bitwise_and(crop_frame,crop_frame,mask=mask)\n green_traffic = cv2.bitwise_and(crop_frame,crop_frame,mask=mask2)\n \n if (np.sum(red_traffic)/255) > 80 :\n run = 3\n return red_traffic\n elif (np.sum(green_traffic)/255) > 50 :\n run = 2\n return green_traffic\n else :\n\t run = 1\n return frame\n\ndef Detect_Terminal(frame):\n global run\n height = int(frame.shape[0])\n weight = int(frame.shape[1])\n crop_img = frame[int((height*0.4)):int((height*0.6)), 0:weight]\n hsv = cv2.cvtColor(crop_img, cv2.COLOR_BGR2HSV) \n pink_mask = cv2.inRange(hsv, lower_pink, upper_pink)\n res = cv2.bitwise_and(crop_img,crop_img,mask=pink_mask) \n number1 = np.sum(pink_mask)\n number2 = np.sum(res)\n if number1 60 and rows > 60 :\n cv_image=cv2.cvtColor(cv_image, cv2.COLOR_BGR2HSV)\n cv2.circle(cv_image, (P1[0],P1[1]), 5, (255, 255, 255), -1)\n cv2.circle(cv_image, (P2[0],P2[1]), 5, (255, 255, 255), -1)\n cv2.circle(cv_image, (P3[0],P3[1]), 5, (255,255, 255), -1)\n cv2.circle(cv_image, (P4[0],P4[1]), 5, (255, 255, 255), -1)\n image=trafficgreen(cv_image)\n res = Detect_Terminal(cv_image)\n # cv_image=cv2.cvtColor( cv_image, cv2.COLOR_BGR2GRAY)\n # image=cv2.cvtColor( image, cv2.COLOR_BGR2GRAY)\n cv_image=cv2.resize(cv_image,(0,0),fx=0.5,fy=0.5)\n print(run)\n status = run\n try:\n self.image_pub_Purple.publish(self.bridge.cv2_to_imgmsg(res,\"mono8\"))\n self.image_pub_light.publish(self.bridge.cv2_to_imgmsg(cv_image,\"bgr8\"))\n self.image_pub_crop.publish(self.bridge.cv2_to_imgmsg(image,\"bgr8\"))\n self.pub.publish(status)\n except CvBridgeError as e:\n print(e)\n\ndef main(args):\n rospy.init_node('image_traffice', anonymous=True)\n ic = image_converter()\n try:\n rospy.spin()\n except KeyboardInterrupt:\n print(\"Shutting down\")\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n main(sys.argv)\n","sub_path":"catkin_ws/src/steamcup/src/rr_traffic_light.py","file_name":"rr_traffic_light.py","file_ext":"py","file_size_in_byte":3625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"537596526","text":"from tkinter import Frame\nfrom tkinter import Button\nfrom tkinter import Label\nfrom tkinter import Entry\nfrom tkinter import filedialog\n\nfrom master_roster.create_master_roster import Master_Roster\nfrom master_roster.create_master_availability import Master_Availability\n\nclass AllocateCrewsScreen(Frame):\n \"\"\"\n Allocate crews screen\n \"\"\"\n\n def __init__(self, parent, controller, background_col, foreground_col, font):\n \"\"\"\n Initialise the allocating crews screen\n \"\"\"\n Frame.__init__(self, parent, bg=background_col)\n self.controller = controller\n self.parent = parent\n\n self.instruction_label = Label(self, text='Allocate crews to turns', bg=background_col, fg=foreground_col, font=font)\n self.driver_avail_label = Label (self, text='Driver availability folder: ', bg=background_col, fg=foreground_col, font=font)\n self.driver_avail_entry = Entry(self, width=50)\n self.driver_avail_button = Button (self, text='Browse', width=6, command=lambda: self.controller.browse_directory(self.driver_avail_entry))\n self.fireman_avail_label = Label (self, text='Fireman availability folder: ', bg=background_col, fg=foreground_col, font=font)\n self.fireman_avail_entry = Entry(self, width=50)\n self.fireman_avail_button = Button (self, text='Browse', width=6, command=lambda: self.controller.browse_directory(self.fireman_avail_entry))\n self.trainee_avail_label = Label (self, text='Trainee availability folder: ', bg=background_col, fg=foreground_col, font=font)\n self.trainee_avail_entry = Entry(self, width=50)\n self.trainee_avail_button = Button (self, text='Browse', width=6, command=lambda: self.controller.browse_directory(self.trainee_avail_entry))\n self.blank_roster_label = Label (self, text='Working roster location: ', bg=background_col, fg=foreground_col, font=font)\n self.blank_roster_entry = Entry(self, width=50)\n self.blank_roster_button = Button (self, text='Browse', width=6, command=lambda: self.controller.browse_file(self.blank_roster_entry))\n self.create_timetable_button = Button (self, text='Allocate crews to roster', width=24, command=lambda: self.master_roster(self.blank_roster_entry.get(),self.driver_avail_entry.get(),self.fireman_avail_entry.get(),self.trainee_avail_entry.get()))\n self.back_button = Button (self, text='Back', width=19, command=lambda: self.controller.show_frame('HomeScreen'))\n\n self.instruction_label.grid(row=0, column=0, sticky='W', padx=25, pady=20, columnspan=2)\n self.driver_avail_label.grid(row=1, column=0, sticky='W', padx=25, pady=0)\n self.driver_avail_entry.grid(row=1, column=1, sticky='E', padx=0, pady=0)\n self.driver_avail_button.grid(row=1, column=2, sticky='W', padx=0, pady=0)\n self.fireman_avail_label.grid(row=2, column=0, sticky='W', padx=25, pady=0)\n self.fireman_avail_entry.grid(row=2, column=1, sticky='E', padx=0, pady=0)\n self.fireman_avail_button.grid(row=2, column=2, sticky='W', padx=0, pady=0)\n self.trainee_avail_label.grid(row=3, column=0, sticky='W', padx=25, pady=0)\n self.trainee_avail_entry.grid(row=3, column=1, sticky='E', padx=0, pady=0)\n self.trainee_avail_button.grid(row=3, column=2, sticky='W', padx=0, pady=0)\n self.blank_roster_label.grid(row=4, column=0, sticky='W', padx=25, pady=20)\n self.blank_roster_entry.grid(row=4, column=1, sticky='E', padx=0, pady=0)\n self.blank_roster_button.grid(row=4, column=2, sticky='W', padx=0, pady=0)\n self.create_timetable_button.grid(row=5, column=1, sticky='E', padx=0, pady=15)\n self.back_button.grid(row=6, column=0, sticky='W', padx=25, pady = 20)\n\n def master_roster(self,working_roster_path,driver_availability_folder,fireman_availability_folder,trainee_availability_folder):\n \"\"\"\n Master function to control:\n - creating master availability\n - create master roster by allocating availability to turns\n \"\"\"\n availability_folders = {\n 'Driver':driver_availability_folder,\n 'Fireman':fireman_availability_folder,\n 'Trainee':trainee_availability_folder\n }\n master_roster = Master_Roster()\n master_availability = Master_Availability()\n working_roster_import_test = master_roster.import_data(working_roster_path)\n if working_roster_import_test:\n availability_import_test,file_name,expected_columns = master_roster.create_master_roster(availability_folders,master_availability)\n if availability_import_test:\n master_roster_save_location = filedialog.asksaveasfilename(title='Choose a save location',defaultextension='.xlsx')\n self.controller.show_frame('WaitScreen')\n export_test = master_roster.export_data(filepath=master_roster_save_location,sheet_name='master_roster')\n if export_test:\n self.controller.frames['MasterAvailabilityScreen'].update_master_availability(master_availability)\n self.controller.show_frame('MasterAvailabilityScreen')\n else:\n self.controller.show_frame('ErrorScreenExport')\n else:\n self.controller.frames['ErrorScreen'].update_error_messages(file_name,expected_columns)\n self.controller.show_frame('ErrorScreen')\n else:\n self.controller.frames['ErrorScreen'].update_error_messages(working_roster_path,master_roster.expected_columns)\n self.controller.show_frame('ErrorScreen')","sub_path":"user_interface/allocate_crews_screen.py","file_name":"allocate_crews_screen.py","file_ext":"py","file_size_in_byte":5630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"294829257","text":"import telebot\r\nfrom telebot import types\r\n\r\nfrom geolocation.main import GoogleMaps\r\nimport requests\r\n\r\nimport os\r\nimport logging\r\nfrom bandsintown import Client\r\nfrom limiter import RateLimiter\r\nfrom math import ceil\r\n\r\nimport peeweedb as pw\r\n \r\nimport itunes_api as it\r\nimport mymusicgraph as mg\r\nimport mybandsintown as bit\r\n\r\n# concertMusicBot\r\n\r\n#token = '419104336:AAEEFQD2ipnAv9B4ti-UZogq-9wGi9wYpfA'\r\n\r\n# Черновичок\r\n#token = '403882463:AAGFabioSaA1uY5Iku7v-lXVJegeIoP-J3E'\r\n\r\n# lostMapMusicBot\r\ntoken = '460978562:AAGf9KzIv2RQuBQ-nwDpWnm2D3BYy8IB5rw'\r\n\r\nbot = telebot.TeleBot(token)\r\ngoogle_maps = GoogleMaps(api_key='AIzaSyCd9HpQnS40Bl2E1OxQBxJp8vmcP6PXpLo')\r\nclient = Client('technopark_ruliiiit')\r\n\r\nlogging.basicConfig(format=u'%(filename)s[LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s] %(message)s',\r\n filename=\"sample.log\", level=logging.INFO)\r\n\r\nlimiter = RateLimiter()\r\n\r\n#emoji\r\npushpin = u'\\U0001F4CC'\r\nleft_arrow = u'\\U00002B05'\r\nright_arrow = u'\\U000027A1'\r\n\r\nguitar = u'\\U0001F3B8'\r\nnotes = u'\\U0001F3B6'\r\nsax = u'\\U0001F3B7'\r\nmicrophone = u'\\U0001F3A4'\r\nfire = u'\\U0001F525'\r\nheadphone = u'\\U0001F3A7'\r\nparty = u'\\U0001F389'\r\n\r\ntown = u'\\U0001F307'\r\nsettings = u'\\U0001F527'\r\ncross = u'\\U0000274C'\r\npiano = u'\\U0001F3B9'\r\nheart = u'\\U00002764'\r\nheart_eyes = u'\\U0001F60D'\r\nstar = u'\\U00002B50'\r\nshadow = u'\\U0001F465'\r\n\r\npw.add_tables()\r\n\r\ngenres = { # Blues/Jazz\r\n 'Blues': 2,\r\n 'Jazz': 11,\r\n 'R&B/Soul': 15,\r\n 'Swing': 1055,\r\n #'Blues-Rock': 1147, убрать лажу\r\n 'Lounge': 1054,\r\n\r\n 'Classical': 5,\r\n 'Country': 6,\r\n 'Latino': 12,\r\n 'Reggae': 24,\r\n 'Folk': 10,\r\n\r\n 'Hip-Hop/Rap': 18,\r\n 'Pop': 14,\r\n\r\n # Electronic\r\n 'Ambient': 1056,\r\n 'Electronica': 1058,\r\n 'House': 1060,\r\n 'Jungle/Drum’n’bass': 1049,\r\n 'Techno': 1050,\r\n 'Trance': 1051,\r\n\r\n # Rock\r\n 'Alternative': 20,\r\n 'Pop-Rock': 1133,\r\n 'Rock & Roll': 1157,\r\n 'Metal': 1153,\r\n 'Indie Rock': 1004,\r\n 'Punk': 1006,\r\n 'Rock': 21}\r\n\r\n\r\n@bot.message_handler(commands=['start'])\r\ndef starting(message):\r\n user_id = message.from_user.id\r\n if pw.is_exist(user_id):\r\n options_keyboard(message)\r\n else:\r\n msg = bot.send_message(message.chat.id, 'Hello, dear music fan! What city are you from?')\r\n bot.register_next_step_handler(msg, find_city)\r\n\r\n\"\"\" TODO fix location\r\ndef find_city(message):\r\n try:\r\n if message.content_type == 'location':\r\n coord = message.location\r\n lat = coord.latitude\r\n lng = coord.longitude\r\n location = google_maps.search(lat=lat, lng=lng).first()\r\n city = location.city\r\n city = city.decode('utf-8')\r\n address = city\r\n else:\r\n address = message.text\r\n location = google_maps.search(location=address)\r\n if location.all():\r\n my_location = location.first()\r\n city = my_location.city\r\n city = city.decode('utf-8')\r\n else:\r\n logging.error(\"(\" + str(message.chat.id) + \") (find_city) troubles with google api\")\r\n msg = bot.send_message(message.chat.id, 'Write city again, please!')\r\n bot.register_next_step_handler(msg, find_city)\r\n except:\r\n logging.error(\"(\" + str(message.chat.id) + \") (find_city) City not found\")\r\n msg = bot.send_message(message.chat.id, 'Try again')\r\n bot.register_next_step_handler(msg, starting)\r\n else:\r\n if address != city:\r\n yes_or_no(message, city)\r\n else:\r\n user_id = message.from_user.id\r\n pw.add_user(user_id, city)\r\n if message.content_type == 'location':\r\n bot.send_message(message.chat.id, \"What's up in \" + city + '?')\r\n options_keyboard(message)\r\n\"\"\"\r\ndef find_city(message):\r\n address = message.text\r\n try:\r\n location = google_maps.search(location=address)\r\n except:\r\n logging.error(\"(\" + str(message.chat.id) + \") (find_city) Troubles with google api or invalid city\")\r\n msg = bot.send_message(message.chat.id, 'Try again')\r\n bot.register_next_step_handler(msg, find_city)\r\n else:\r\n if location.all():\r\n my_location = location.first()\r\n city = my_location.city\r\n city = city.decode('utf-8')\r\n\r\n if address != city:\r\n yes_or_no(message, city)\r\n else:\r\n user_id = message.from_user.id\r\n pw.add_user(user_id, city)\r\n options_keyboard(message)\r\n else:\r\n msg = bot.send_message(message.chat.id, 'Write city again, please!')\r\n bot.register_next_step_handler(msg, find_city)\r\n\r\n\r\ndef yes_or_no(message, city):\r\n keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)\r\n keyboard.add(*[types.KeyboardButton(name) for name in ['Yes', 'No']])\r\n msg = bot.send_message(message.chat.id, 'Did you mean ' + str(city) + '?', reply_markup=keyboard)\r\n user_id = message.from_user.id\r\n pw.add_user(user_id, city)\r\n bot.register_next_step_handler(msg, find_city_final)\r\n\r\n\r\ndef find_city_final(message):\r\n if message.text == 'Yes':\r\n options_keyboard(message)\r\n if message.text == 'No':\r\n msg = bot.send_message(message.from_user.id, 'Write city again, please!')\r\n bot.register_next_step_handler(msg, find_city)\r\n\r\n\r\n@bot.message_handler(regexp=left_arrow + 'Back')\r\ndef options_keyboard(message):\r\n keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)\r\n keyboard.add(*[types.KeyboardButton(name) for name in ['Search Artist' + star, 'Search by genre' + piano,\r\n 'Search by similar' + shadow, 'Preview' + notes,\r\n 'Settings' + settings]])\r\n bot.send_message(message.chat.id, party, reply_markup=keyboard)\r\n\r\n\r\n@bot.message_handler(regexp='Settings' + settings)\r\ndef bot_menu(message):\r\n keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)\r\n keyboard.add(*[types.KeyboardButton(name) for name in [left_arrow + 'Back', 'Change city' + town, 'Follow' + heart_eyes,\r\n 'Show favorites' + heart, 'Delete favorites' + cross]])\r\n bot.send_message(message.chat.id, 'Here you can change your data', reply_markup=keyboard)\r\n\r\n\r\n@bot.message_handler(regexp='Change city' + town)\r\ndef change_city(message):\r\n msg = bot.send_message(message.chat.id, 'Write city or send your location, please!')\r\n bot.register_next_step_handler(msg, find_city)\r\n\r\n\r\n@bot.message_handler(regexp='Search Artist' + star)\r\ndef artist(message):\r\n msg = bot.send_message(message.chat.id, 'Write artist please')\r\n bot.register_next_step_handler(msg, search_by_artist)\r\n\r\n\r\ndef search_by_artist(message):\r\n artist_name = message.text\r\n try:\r\n artist_request = client.get(artist_name)\r\n except:\r\n logging.error(\"(\" + str(message.chat.id) + \") (search_by_artist) Bandsintown invalid symbols error in artist named \\\"\" + artist_name + \"\\\"\")\r\n bot.send_message(message.chat.id, 'Artist name is invalid')\r\n else:\r\n if 'errors' not in artist_request: \r\n artist_id = artist_request['id']\r\n user_id = message.chat.id\r\n artist = artist_request['name']\r\n city = pw.get_city(user_id)\r\n if pw.is_artist_exist(artist_id): \r\n message_to_bandsintown(page=0, user_id=user_id, artist_id=artist_id, city=city)\r\n else: \r\n events = client.events(artist)\r\n if events: \r\n pw.add_artist(artist_id, artist, events)\r\n message_to_bandsintown(0, user_id, artist_id, city)\r\n else: \r\n bot.send_message(message.chat.id, artist + ' is not currently on tour')\r\n else:\r\n logging.error(\"(\" + str(message.chat.id) + \") (search_by_artist) \\\"\" + artist_name + \"\\\"\" + \" is unknown artist name\")\r\n bot.send_message(message.chat.id, 'Artist name is invalid')\r\n options_keyboard(message)\r\n\r\n\r\ndef message_to_bandsintown(page, user_id, artist_id, city, new_event=0):\r\n if not new_event:\r\n new = pw.get_event(artist_id)\r\n if new:\r\n new_event = eval(new)\r\n else:\r\n new_event = []\r\n if new_event:\r\n bot.send_message(user_id, create_message_page(page, new_event, city)['message'],\r\n parse_mode='Markdown',\r\n disable_web_page_preview=True,\r\n reply_markup=pages_keyboard(0, artist_id, city)) # нулевая страница\r\n \r\n bot.send_message(user_id, create_photo(artist_id),\r\n parse_mode='Markdown',\r\n disable_notification=True)\r\n else:\r\n logging.error(\"(\" + str(user_id) + \") (message_to_bandsintown) This artist is in DB, but not on tour\")\r\n bot.send_message(user_id, 'This artist is not currently on tour')\r\n\r\n\r\ndef create_message_page(page, events_old, city):\r\n lines = 5\r\n answer = {}\r\n events = []\r\n if city != 'None':\r\n for event_old in events_old:\r\n if event_old['venue']['city'] == city:\r\n events.append(event_old)\r\n else:\r\n events = events_old\r\n if events:\r\n total_lines = len(events)\r\n message = \"Artist: \" + events[0]['artists'][0]['name'] + \"\\n\\n\"\r\n for event in range(0 + (lines * page), lines + (lines * page)):\r\n if event < total_lines:\r\n message += \"*\" + events[event]['title'] + \"* \\n\"\r\n message += \"Event date: \" + events[event]['formatted_datetime'] + \"\\n\"\r\n if events[event]['ticket_url']:\r\n message += \"[Buy tickets](\" + events[event]['ticket_url'] + \")\\n\\n\"\r\n else:\r\n message += \"[Buy tickets](\" + events[event]['facebook_rsvp_url'] + \")\\n\\n\"\r\n answer['message'] = message\r\n answer['page_max'] = ceil(total_lines / lines)\r\n else:\r\n message = events_old[0]['artists'][0]['name'] + ' has no concerts in ' + city\r\n answer['message'] = message\r\n answer['page_max'] = 0\r\n return answer\r\n\r\n\r\ndef create_photo(artist_id):\r\n events = eval(pw.get_event(artist_id))\r\n return \"[\" + pushpin + \"](\" + events[0]['artists'][0]['thumb_url'] + \")\"\r\n\r\n\r\ndef pages_keyboard(page, artist_id, city): \r\n keyboard = types.InlineKeyboardMarkup()\r\n btns = []\r\n page_max = create_message_page(page, eval(pw.get_event(artist_id)), city)['page_max']\r\n if page > 0: \r\n btns.append(types.InlineKeyboardButton(text=left_arrow,\r\n callback_data='{arrow}_{page}_{artist}_{city}'.format(arrow=left_arrow,\r\n page=page - 1,\r\n artist=artist_id,\r\n city= city)))\r\n if page < page_max - 1: \r\n btns.append(types.InlineKeyboardButton(text = right_arrow,\r\n callback_data = '{arrow}_{page}_{artist}_{city}'.format(arrow = right_arrow,\r\n page = page + 1,\r\n artist = artist_id,\r\n city= city)))\r\n if page_max == 0: btns.append(types.InlineKeyboardButton(text = 'Show All Concerts',\r\n callback_data = '{show}_{page}_{artist}_{city}'.format(show = 'More',\r\n page = 0,\r\n artist = artist_id,\r\n city= None)))\r\n keyboard.add(*btns)\r\n return keyboard\r\n\r\n\r\n@bot.callback_query_handler(func=lambda call: call.data)\r\ndef pages(call):\r\n called = call.data.split('_')[0]\r\n if (called == left_arrow) or (called == right_arrow) or (called == 'More'):\r\n page = call.data.split('_')[1]\r\n artist = call.data.split('_')[2]\r\n city = call.data.split('_')[3]\r\n if not limiter.can_send_to(call.message.chat.id):\r\n return\r\n bot.edit_message_text(\r\n chat_id=call.message.chat.id,\r\n message_id=call.message.message_id,\r\n text=create_message_page(int(page), eval(pw.get_event(int(artist))), city)['message'],\r\n parse_mode='Markdown',\r\n reply_markup=pages_keyboard(int(page), int(artist), city),\r\n disable_web_page_preview=True)\r\n\r\n\r\n@bot.message_handler(regexp='Search by genre' + piano)\r\ndef genre(message):\r\n keyboard = types.ReplyKeyboardMarkup()\r\n keyboard.add(*[types.KeyboardButton(genre) for genre in ['Rock', 'Electronic', 'Pop', 'Blues/Jazz',\r\n 'Hip-Hop/Rap', 'Others']])\r\n bot.send_message(message.chat.id, \"Chose style\", reply_markup=keyboard)\r\n\r\n\r\n@bot.message_handler(regexp='Rock')\r\ndef rock(message):\r\n keyboard = types.ReplyKeyboardMarkup()\r\n keyboard.add(*[types.KeyboardButton(genre) for genre in ['Rock', 'Metal', 'Pop-Rock', 'Punk', 'Rock & Roll',\r\n 'Alternative']])\r\n msg = bot.send_message(message.chat.id, guitar + fire, reply_markup=keyboard)\r\n bot.register_next_step_handler(msg, search_by_genre)\r\n\r\n\r\n@bot.message_handler(regexp='Electronic')\r\ndef electronic(message):\r\n keyboard = types.ReplyKeyboardMarkup()\r\n keyboard.add(*[types.KeyboardButton(genre) for genre in ['Electronica', \"Jungle/Drum'n'Bass\", 'Techno',\r\n 'Trance', 'House', 'Ambient']])\r\n msg = bot.send_message(message.chat.id, headphone, reply_markup=keyboard)\r\n bot.register_next_step_handler(msg, search_by_genre)\r\n\r\n\r\n@bot.message_handler(regexp='Pop')\r\ndef style(message):\r\n search_by_genre(message)\r\n\r\n\r\n@bot.message_handler(regexp='Blues/Jazz')\r\ndef blues(message):\r\n keyboard = types.ReplyKeyboardMarkup()\r\n keyboard.add(*[types.KeyboardButton(genre) for genre in ['R&B/Soul', 'Jazz', 'Blues', 'Swing',\r\n 'Lounge']])\r\n msg = bot.send_message(message.chat.id, sax + notes, reply_markup=keyboard)\r\n bot.register_next_step_handler(msg, search_by_genre)\r\n\r\n\r\n@bot.message_handler(regexp='Hip-Hop/Rap')\r\ndef style(message):\r\n search_by_genre(message)\r\n\r\n\r\n@bot.message_handler(regexp='Others')\r\ndef style(message):\r\n keyboard = types.ReplyKeyboardMarkup()\r\n keyboard.add(*[types.KeyboardButton(genre) for genre in ['Country', 'Folk', 'Classical',\r\n 'Latino', 'Reggae']])\r\n msg = bot.send_message(message.chat.id, microphone, reply_markup=keyboard)\r\n bot.register_next_step_handler(msg, search_by_genre)\r\n\r\n\r\ndef search_by_genre(message):\r\n genre = message.text\r\n genre_id = genres[genre]\r\n my_artists = it.get_genre_by_artist_id(genre_id)\r\n to_join = list(my_artist['name'] for my_artist in my_artists)\r\n bot.send_message(message.chat.id, \"\\n\".join(to_join))\r\n for my_artist in my_artists:\r\n artist_id = my_artist['id']\r\n user_id = message.chat.id\r\n artist = my_artist['name']\r\n city = pw.get_city(user_id)\r\n if pw.is_artist_exist(artist_id): \r\n message_to_bandsintown(page=0, user_id=user_id, artist_id=artist_id, city=city)\r\n else: \r\n events = client.events(artist)\r\n if events: \r\n pw.add_artist(artist_id, artist, events)\r\n message_to_bandsintown(0, user_id, artist_id, city)\r\n else: \r\n bot.send_message(message.chat.id, artist + ' is not currently on tour')\r\n options_keyboard(message)\r\n\r\n\r\n@bot.message_handler(regexp='Search by similar' + shadow)\r\ndef similar(message):\r\n msg = bot.send_message(message.chat.id, 'Write artist, please')\r\n bot.register_next_step_handler(msg, search_by_similar)\r\n\r\n\r\ndef search_by_similar(message):\r\n artist_name = message.text\r\n my_artists = mg.get_similar_artists(artist_name)\r\n if my_artists == 'errors':\r\n logging.error(\"(\" + str(message.chat.id) + \") (search_by_similar) \\\"\" + artist_name + \"\\\"\" + \" is unknown artist name\")\r\n bot.send_message(message.chat.id, \"I don't know this artist\")\r\n else:\r\n to_join = list(my_artist['name'] for my_artist in my_artists)\r\n bot.send_message(message.chat.id, \"\\n\".join(to_join))\r\n for my_artist in my_artists:\r\n artist_id = my_artist['id']\r\n user_id = message.chat.id\r\n artist = my_artist['name']\r\n city = pw.get_city(user_id)\r\n if pw.is_artist_exist(artist_id): \r\n message_to_bandsintown(page=0, user_id=user_id, artist_id=artist_id, city=city)\r\n else: \r\n events = client.events(artist)\r\n if events: \r\n pw.add_artist(artist_id, artist, events)\r\n message_to_bandsintown(0, user_id, artist_id, city)\r\n else: \r\n bot.send_message(message.chat.id, artist + ' is not currently on tour')\r\n options_keyboard(message)\r\n\r\n\r\n@bot.message_handler(regexp='Follow' + heart_eyes)\r\ndef fan_of_handler(message):\r\n msg = bot.send_message(message.chat.id, 'Write artist, please')\r\n bot.register_next_step_handler(msg, fan_of)\r\n\r\n\r\ndef fan_of(message):\r\n artist_name = message.text\r\n try:\r\n artist_request = client.get(artist_name)\r\n except:\r\n logging.error(\"(\" + str(message.chat.id) + \") (fan_of) Bandsintown invalid symbols error in artist named \\\"\" + artist_name + \"\\\"\")\r\n bot.send_message(message.chat.id, 'Artist name is invalid')\r\n else:\r\n if 'errors' not in artist_request:\r\n artist_id = artist_request['id']\r\n user_id = message.from_user.id\r\n artist_name = artist_request['name']\r\n events = client.events(artist_name)\r\n if not events:\r\n events = '[]'\r\n pw.add_relation(user_id, artist_id, artist_name, events)\r\n bot.send_message(message.chat.id, artist_name + ' added in favorites')\r\n else:\r\n logging.error(\"(\" + str(message.chat.id) + \") (fan_of) \\\"\" + artist_name + \"\\\"\" + \" is unknown artist name\")\r\n bot.send_message(message.chat.id, 'Artist name is invalid')\r\n\r\n\r\n@bot.message_handler(regexp='Show favorites' + heart)\r\ndef favorites(message):\r\n artists = pw.get_relations(message.chat.id)\r\n artist_message = \"\"\r\n if artists:\r\n i = 1\r\n for artist in artists:\r\n artist_message += str(i) + \") \" + artist + \"\\n\"\r\n i += 1\r\n else:\r\n logging.error(\"(\" + str(message.chat.id) + \") (favorites) Favorites list is empty\")\r\n artist_message = 'Favorites list is empty'\r\n bot.send_message(message.chat.id, artist_message, parse_mode='Markdown')\r\n\r\n\r\n@bot.message_handler(regexp='Delete favorites' + cross)\r\ndef delete_handler(message):\r\n msg = bot.send_message(message.chat.id, 'Write artist, please')\r\n bot.register_next_step_handler(msg, delete)\r\n\r\n\r\ndef delete(message):\r\n artist_name = message.text\r\n try:\r\n artist_request = client.get(artist_name)\r\n except:\r\n logging.error(\"(\" + str(message.chat.id) + \") (delete) Bandsintown invalid symbols error in artist named \\\"\" + artist_name + \"\\\"\")\r\n bot.send_message(message.chat.id, 'Artist name is invalid')\r\n else:\r\n if 'errors' not in artist_request:\r\n artist_id = artist_request['id']\r\n user_id = message.from_user.id\r\n artist_name = artist_request['name']\r\n result = pw.del_relation(user_id, artist_id)\r\n if result:\r\n bot.send_message(message.chat.id, artist_name + ' deleted from favorites')\r\n else:\r\n bot.send_message(message.chat.id, artist_name + \" isn't in favorites\")\r\n else:\r\n logging.error(\"(\" + str(message.chat.id) + \") (delete) \\\"\" + artist_name + \"\\\"\" + \" is unknown artist name\")\r\n bot.send_message(message.chat.id, 'Artist name is invalid')\r\n\r\n\r\n@bot.message_handler(regexp='Preview' + notes)\r\ndef preview(message):\r\n msg = bot.send_message(message.chat.id, 'Write artist, please')\r\n bot.register_next_step_handler(msg, snippet_search)\r\n\r\n\r\ndef snippet_search(message):\r\n artist_name = message.text\r\n datas = requests.get(\"https://itunes.apple.com/search?term=\"+ artist_name +\"&entity=musicTrack&limit=3\").json()['results']\r\n if datas:\r\n for data in datas:\r\n response = requests.get(data['previewUrl'])\r\n with open('out.m4a', 'a+b') as music:\r\n music.write(response.content)\r\n music.seek(0)\r\n bot.send_audio(message.chat.id, music, performer=data['artistName'], duration=data[\"trackTimeMillis\"] / 1000,\r\n title=data['trackName'])\r\n os.remove('out.m4a')\r\n else:\r\n logging.error(\"(\" + str(message.chat.id) + \") (snippet_search) \\\"\" + artist_name + \"\\\"\" + \" is unknown artist name\")\r\n bot.send_message(message.chat.id, 'Artist name is invalid')\r\n\r\n\r\ndef telegram_polling():\r\n try:\r\n bot.polling(none_stop=True, timeout=60) #constantly get messages from Telegram\r\n except:\r\n logging.error(\"Internet timeout error\")\r\n bot.stop_polling()\r\n time.sleep(10)\r\n telegram_polling()\r\n\r\nif __name__ == '__main__': \r\n telegram_polling()","sub_path":"music_bot.py","file_name":"music_bot.py","file_ext":"py","file_size_in_byte":22159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"164159715","text":"import discord\nfrom discord.ext import commands\n\nfrom database import DatabaseIdol, DatabaseDeck\n\n\nclass Wishlist(commands.Cog):\n def __init__(self, bot):\n \"\"\"Initial the cog with the bot.\"\"\"\n self.bot = bot\n\n #### Commands ####\n\n @commands.command(description='Add an idol to your wish list.'\n 'Please add \"\" if it has spaces\\n'\n 'Take the first corresponding idol.'\n 'See list command for all idols.\\n'\n 'Example:\\n'\n ' *wish rm'\n ' *wish heejin loona'\n ' *wish joy \"red velvet\"')\n async def wish(self, ctx, name, group=None):\n name = name.strip()\n\n if group:\n group = group.strip()\n\n id_idol = None\n\n if group:\n id_idol = DatabaseIdol.get().get_idol_group_id(name, group)\n else:\n ids = DatabaseIdol.get().get_idol_ids(name)\n if ids:\n id_idol = ids[0]\n\n if not id_idol:\n await ctx.message.add_reaction(u\"\\u274C\")\n await ctx.send(f'Idol **{name}**{\" from *\" + group + \"* \" if group else \"\"} not found.')\n return\n\n nb_wish = DatabaseDeck.get().get_nb_wish(ctx.guild.id, ctx.author.id)\n max_wish = DatabaseDeck.get().get_max_wish(ctx.guild.id, ctx.author.id)\n\n if nb_wish >= max_wish:\n # Red cross\n await ctx.message.add_reaction(u\"\\u274C\")\n await ctx.send('Your wish list is full!')\n return\n\n if DatabaseDeck.get().add_to_wishlist(ctx.guild.id, id_idol, ctx.author.id):\n # Green mark\n await ctx.message.add_reaction(u\"\\u2705\")\n else:\n # Red cross\n await ctx.message.add_reaction(u\"\\u274C\")\n await ctx.send('You already have this idol in your wish list.')\n\n @commands.command(description='Remove an idol from your wish list. Please add \"\" if it has spaces\\n'\n 'Take the first corresponding idol. See list command for all idols.\\n'\n 'Example:\\n'\n ' *wishremove rm'\n ' *wishremove heejin loona'\n ' *wishremove joy \"red velvet\"')\n async def wishremove(self, ctx, name, group=None):\n name = name.strip()\n\n if group:\n group = group.strip()\n\n id_idol = None\n\n if group:\n id_idol = DatabaseIdol.get().get_idol_group_id(name, group)\n else:\n ids = DatabaseIdol.get().get_idol_ids(name)\n if ids:\n id_idol = ids[0]\n\n if not id_idol:\n await ctx.message.add_reaction(u\"\\u274C\")\n await ctx.send(f'Idol **{name}**{\" from *\" + group + \"* \" if group else \"\"} not found.')\n return\n\n if DatabaseDeck.get().remove_from_wishlist(ctx.guild.id, id_idol, ctx.author.id):\n # Green mark\n await ctx.message.add_reaction(u\"\\u2705\")\n else:\n # Red cross\n await ctx.message.add_reaction(u\"\\u274C\")\n await ctx.send('You don\\'t have this idol in your wish list.')\n\n @commands.command(aliases=['wl'], description='Show your wishlist.')\n async def wishlist(self, ctx):\n ids = DatabaseDeck.get().get_wishlist(ctx.guild.id, ctx.author.id)\n\n description = ''\n username = ctx.author.name if ctx.author.nick is None else ctx.author.nick\n\n nb_wish = DatabaseDeck.get().get_nb_wish(ctx.guild.id, ctx.author.id)\n max_wish = DatabaseDeck.get().get_max_wish(ctx.guild.id, ctx.author.id)\n\n for id_idol in ids:\n current_image = DatabaseDeck.get().get_idol_current_image(ctx.guild.id, id_idol)\n idol = DatabaseIdol.get().get_idol_information(id_idol, current_image)\n id_owner = DatabaseDeck.get().idol_belongs_to(ctx.guild.id, id_idol)\n emoji = ''\n\n if id_owner:\n if id_owner == ctx.author.id:\n emoji = u\"\\u2705\"\n else:\n emoji = u\"\\u274C\"\n description += f'**{idol[\"name\"]}** *{idol[\"group\"]}* {emoji}\\n'\n\n await ctx.send(embed=discord.Embed(title=f'Wish list of {username} ({nb_wish}/{max_wish})',\n description=description))\n","sub_path":"src/wishlist.py","file_name":"wishlist.py","file_ext":"py","file_size_in_byte":4519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"116821891","text":"import datetime\nfrom time import time\nimport lightgbm as lgb\nimport numpy as np\nimport pandas as pd\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import KFold\nfrom ..util import log\nfrom sklearn.model_selection import train_test_split\nimport optuna\nfrom optuna.samplers import TPESampler\n\nclass CrossLgbRegression(object):\n def __init__(self, params=None, n_fold=5):\n self.models = []\n self.feature_importances_ = pd.DataFrame()\n self.n_fold = n_fold\n self.params_ = {\n 'objective': 'regression',\n 'metric': 'mse',\n 'boosting': 'gbdt',\n 'learning_rate': 0.01,\n 'num_leaves': 2 ** 5,\n 'bagging_fraction': 0.95,\n 'bagging_freq': 1,\n 'bagging_seed': 66,\n 'feature_fraction': 0.7,\n 'feature_fraction_seed': 66,\n 'max_bin': 100,\n 'max_depth': 5,\n 'verbose': -1\n }\n if params is not None:\n self.params_ = params\n self.Early_Stopping_Rounds = 150\n self.N_round = 5000\n self.Verbose = 10\n\n def get_params(self):\n return self.params_\n\n def set_params(self, params):\n self.params_ = params\n\n def optuna_tuning(self, X, y):\n X_train, X_valid, y_train, y_valid = train_test_split(X, y, stratify=y, test_size=0.2, random_state=42)\n\n def objective(trial):\n param_grid = {\n 'num_leaves': trial.suggest_int('num_leaves', 2 ** 3, 2 ** 9),\n 'num_boost_round': trial.suggest_int('num_boost_round', 100, 8000),\n 'max_depth': trial.suggest_int('max_depth', 3, 9),\n 'objective': 'regression',\n 'metric': 'mse',\n 'boosting': 'gbdt',\n 'learning_rate': 0.01,\n 'bagging_fraction': 0.95,\n 'bagging_freq': 1,\n 'bagging_seed': 66,\n 'feature_fraction': 0.7,\n 'feature_fraction_seed': 66,\n 'max_bin': 100,\n 'verbose': -1\n }\n trn_data = lgb.Dataset(X_train, label=y_train, categorical_feature=\"\")\n val_data = lgb.Dataset(X_valid, label=y_valid, categorical_feature=\"\")\n clf = lgb.train(param_grid, trn_data, valid_sets=[trn_data, val_data], verbose_eval=False,\n early_stopping_rounds=self.Early_Stopping_Rounds)\n pred_val = clf.predict(X_valid)\n mse_ = mean_squared_error(y_valid, pred_val)\n\n return mse_\n\n train_time = 1 * 10 * 60 # h * m * s\n study = optuna.create_study(direction='minimize', sampler=TPESampler(), study_name='LgbRegressor')\n study.optimize(objective, timeout=train_time)\n\n log('Number of finished trials: ', len(study.trials))\n log('Best trial:')\n trial = study.best_trial\n\n log('\\tValue: {}'.format(trial.value))\n log('\\tParams: ')\n for key, value in trial.params.items():\n log('\\t\\t{}: {}'.format(key, value))\n\n self.params_['num_leaves'] = trial.params['num_leaves']\n self.params_['max_depth'] = trial.params['max_depth']\n self.N_round = trial.params['num_boost_round']\n\n def fit(self, X, y, Early_Stopping_Rounds=None, N_round=None, Verbose=None, tuning=True):\n log(X.shape)\n\n if tuning:\n log(\"[+]tuning params\")\n self.optuna_tuning(X, y)\n\n if Early_Stopping_Rounds is not None:\n self.Early_Stopping_Rounds = Early_Stopping_Rounds\n if N_round is not None:\n self.N_round = N_round\n if Verbose is not None:\n self.Verbose = Verbose\n\n folds = KFold(n_splits=self.n_fold, shuffle=True, random_state=889)\n MSEs = []\n self.feature_importances_['feature'] = X.columns\n\n for fold_n, (train_index, valid_index) in enumerate(folds.split(X)):\n\n start_time = time()\n print('Training on fold {}'.format(fold_n + 1))\n\n trn_data = lgb.Dataset(X.iloc[train_index],\n label=y.iloc[train_index], categorical_feature=\"\")\n val_data = lgb.Dataset(X.iloc[valid_index],\n label=y.iloc[valid_index], categorical_feature=\"\")\n clf = lgb.train(self.params_, trn_data, num_boost_round=self.N_round, valid_sets=[trn_data, val_data],\n verbose_eval=self.Verbose,\n early_stopping_rounds=self.Early_Stopping_Rounds)\n self.models.append(clf)\n self.feature_importances_['fold_{}'.format(fold_n + 1)] = clf.feature_importance()\n val = clf.predict(X.iloc[valid_index])\n mse_ = mean_squared_error(y.iloc[valid_index], val)\n print('MSE: {}'.format(mse_))\n MSEs.append(mse_)\n print('Fold {} finished in {}'.format(fold_n + 1, str(datetime.timedelta(\n seconds=time() - start_time))))\n self.feature_importances_['average'] = self.feature_importances_[\n [x for x in self.feature_importances_.columns if x != \"feature\"]].mean(axis=1)\n self.feature_importances_ = self.feature_importances_.sort_values(by=\"average\", ascending=False)\n self.feature_importances_.index = range(len(self.feature_importances_))\n\n def predict(self, test):\n for idx, clf in enumerate(self.models):\n if idx == 0:\n result = clf.predict(test) / self.n_fold\n else:\n result += clf.predict(test) / self.n_fold\n return result","sub_path":"autox/models/regressor.py","file_name":"regressor.py","file_ext":"py","file_size_in_byte":5686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"318588814","text":"# Copyright 2018 Agile Geeks\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software\n# and associated documentation files (the \"Software\"), to deal in the Software without restriction,\n# including without limitation the rights to use, copy, modify, merge, publish, distribute,\n# sublicense, and/or sell copies of the Software, and to permit persons to whom the Software\n# is furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in all copies or substantial\n# portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT\n# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\n# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfrom __future__ import (\n unicode_literals,\n print_function,\n division\n)\nimport re\nfrom .generic import GenericValidator\n\n\nclass Validator(GenericValidator):\n \"\"\"\n For rules see /docs/VIES-VAT Validation Routines-v15.0.doc\n \"\"\"\n\n def __init__(self):\n self.regexp = re.compile(r'^\\d{8}[a-z]$', re.IGNORECASE)\n\n def validate(self, vat_number):\n if super(Validator, self).validate(vat_number) is False:\n return False\n\n vat_number = str(vat_number)\n if int(vat_number[0]) not in [0, 1, 3, 4, 5, 9]:\n return False\n if vat_number[:2] == str('12'):\n return False\n\n odd_digit_mapping = {\n 0: 1,\n 1: 0,\n 2: 5,\n 3: 7,\n 4: 9,\n 5: 13,\n 6: 15,\n 7: 17,\n 8: 19,\n 9: 21\n }\n a1 = 0\n for i in range(8):\n if i % 2 == 0:\n a1 = a1 + odd_digit_mapping [ int(vat_number[i]) ]\n else:\n a1 = a1 + + int(vat_number[i])\n\n r = a1 % 26\n\n last_char_mapping = {\n 0: 'A',\n 1: 'B',\n 2: 'C',\n 3: 'D',\n 4: 'E',\n 5: 'F',\n 6: 'G',\n 7: 'H',\n 8: 'I',\n 9: 'J',\n 10: 'K',\n 11: 'L',\n 12: 'M',\n 13: 'N',\n 14: 'O',\n 15: 'P',\n 16: 'Q',\n 17: 'R',\n 18: 'S',\n 19: 'T',\n 20: 'U',\n 21: 'V',\n 22: 'W',\n 23: 'X',\n 24: 'Y',\n 25: 'Z'\n }\n\n last_char = vat_number[8]\n last_char = last_char.upper()\n\n return last_char_mapping[r] == last_char\n","sub_path":"pyVat/validators/cy.py","file_name":"cy.py","file_ext":"py","file_size_in_byte":2872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"115239987","text":"#!/usr/bin/python\n\nif __name__ == '__main__':\n dictionary = dict()\n \n dictionary['God'] = '김성진'\n dictionary['StudyMaster'] = '최원권'\n dictionary['ice'] = '버킷'\n\n print('dictionary[\\'God\\'] = ' + dictionary['God'])\n print('dictionary[\\'StudyMaster\\'] = ' + dictionary['StudyMaster'])\n print('dictionary[\\'ice\\'] = ' + dictionary['ice'])\n","sub_path":"B/k311093/week2/hw_3.py","file_name":"hw_3.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"422426715","text":"\"\"\"\r\n###PART ONE###\r\n\"\"\"\r\n\r\nimport turtle # Import the turtle module\r\nimport random # Import the random module\r\n\r\nTom = turtle.Turtle() # Create a new turtle named Tom\r\nTom.speed(0) # Set Tom's movement speed to the fastest\r\nTom.pencolor(\"red\") # Set the color of the line Tom draws behind him\r\nTom.penup() # Lift the pen so that Tom doesn't draw when we move him\r\n\r\nscreen = Tom.getscreen() # Set a variable screen to the screen Tom is using\r\nscreen.bgpic(\"obstacle_course.gif\") # Set the background image\r\n\r\nobstacles = [] # Create an empty list of obstacles (will be filled later)\r\ntries = 3 # Give the player three tries to get through the course\r\ngridsize = 50 #the screen will be a grid, this will be the size of each grid\r\n\r\npos = (0, -2) # Set the player's position\r\ngoal = (0, 2) # Set the goal's position\r\n\r\n# Give the player instructions on how to move\r\nprint(\"Type commands to move Tom through the obstacle course.\")\r\nprint(\"Watch out for the hidden obstacles!\")\r\nprint(\"You have \" + (str)(tries) + \" tries to make it through.\")\r\nprint(\"Type 'up', 'down', 'left', or 'right' to move Tom.\")\r\nprint(\"Type 'quit' to quit.\")\r\n\r\n\"\"\"\r\n###PART TWO###\r\n\"\"\"\r\n\r\n# Place five obstacles in the grid at random positions\r\n\r\n\r\n\"\"\"\r\n###PART THREE###\r\n\"\"\"\r\n\r\n# Move the turtle to a specific grid cell\r\n\r\n\r\n\"\"\"\r\n###PART FOUR###\r\n\"\"\"\r\n\r\n# Show the player that they hit an obstacle\r\ndef showobstacle(coordinates):\r\n # Create a new turtle, and position it at the obstacle cell\r\n hit = turtle.Turtle()\r\n hit.hideturtle()#We want the turtle to draw an X, we dont want to see it\r\n hit.pencolor(\"red\")\r\n hit.speed(0)\r\n hit.penup()\r\n\r\n hit.setheading(45)\r\n hit.fd(25)\r\n hit.rt(180)\r\n # Draw an X on the obstacle cell\r\n hit.pendown()\r\n hit.fd(50)\r\n hit.rt(180)\r\n hit.fd(25)\r\n hit.lt(90)\r\n hit.fd(25)\r\n hit.rt(180)\r\n hit.fd(50)\r\n\r\nmoveto(pos, Tom) # Set Tom to the starting position for the maze\r\nTom.setheading(90) # Turn Tom to face upwards\r\nTom.pendown() # Put the pen down to start drawing a line again\r\n\r\n\"\"\"\r\n###PART FIVE###\r\n\"\"\"\r\n\r\n# Repeat the following until the player reaches the goal\r\nwhile(pos != goal): # So long as Tom isn't at the goal\r\n command = input(\"Direction: \") # Prompt the player for input\r\n x = pos[0]\r\n y = pos[1]\r\n # Set x and y to the new coordinates, if they're within the grid\r\n if(command == \"right\" and x < 2):\r\n Tom.setheading(0)\r\n x += 1\r\n elif(command == \"up\" and y < 2):\r\n \r\n y += 1\r\n elif(command == \"left\" and x > -2):\r\n Tom.setheading(180)\r\n \r\n elif(command == \"down\" and y > -2):\r\n Tom.setheading(270)\r\n y -= 1\r\n elif(command == \"quit\"):\r\n break\r\n else:\r\n # Tell the player if they put in an invalid command\r\n print(\"Not a valid command\")\r\n\r\n # Set the position to the new coordinates, and move there\r\n pos = (x, y)\r\n moveto(pos, Tom)\r\n\r\n \"\"\"\r\n ###PART SIX###\r\n \"\"\"\r\n\r\n # If the new position was in the list of obstacles, tell the player\r\n \r\n \r\n# If the player is at the goal, congratulate them for winning\r\nif(pos == goal):\r\n print(\"Nice job! You got to the goal!\")\r\nelse:\r\n print(\"Game over!\")\r\n \r\nturtle.bye() # Set the turtle window to close\r\n","sub_path":"turtle_minefield_student.py","file_name":"turtle_minefield_student.py","file_ext":"py","file_size_in_byte":3323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"235408270","text":"from pathlib import Path\nfrom typing import List\n\nimport cv2\nimport numpy as np\n\nfrom videoflow.core import ConsumerNode\n\n\nclass ImageFileWriter(ConsumerNode):\n def __init__(self, image_file_base_name: str, swap_channels: bool = True):\n self._index = 0\n self._file_base_path = Path(image_file_base_name)\n self._dir_path = self._file_base_path.parent\n self._extension = self._file_base_path.suffix\n self._base_name = self._file_base_path.stem\n self._swap_channels = swap_channels\n super().__init__()\n\n def open(self):\n self._dir_path.mkdir(parents=True, exist_ok=True)\n\n def consume(self, items: List[np.array]) -> None:\n \"\"\"\n Receives the images to save them into files.\n\n - Arguments:\n - items: list of np.array of dimension (height, width, 3)\n \"\"\"\n for item in items:\n image_name = f'{self._base_name}{self._index}{self._extension}'\n image_file_path = self._dir_path / image_name\n if self._swap_channels:\n item = item[..., ::-1]\n cv2.imwrite(str(image_file_path), item)\n self._index += 1\n","sub_path":"videoflow_contrib/consumers/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"52257705","text":"class BinarySearchTree:\n def __init__(self, value):\n self.value = value\n self.left = None\n self.right = None\n\n def insert(self, value, leaf=None):\n leaf = leaf if leaf is not None else self.value\n if value > leaf:\n # go right\n if self.right is None:\n self.right = BinarySearchTree(value)\n else:\n # make self.right new value, and recall insert\n new_leaf = self.right.value\n self.right.insert(value, new_leaf)\n else:\n # go left\n if self.left is None:\n self.left = BinarySearchTree(value)\n else:\n # make self.left new value, and recall insert\n\n new_leaf = self.left.value\n self.left.insert(value, new_leaf)\n # contains works in a seperate terminal, not in VSC for some reason\n\n def contains(self, target, leaf=None):\n leaf = leaf if leaf is not None else self.value\n print(\"current leaf is: \", leaf)\n print(\"we are looking for: \", target)\n if leaf is not None:\n if target > leaf:\n # if target is greater than leaf, go right\n leaf = self.right.value\n self.contains(target, leaf)\n elif target < leaf:\n # target is less than leaf\n leaf = self.left.value\n self.contains(target, leaf)\n else:\n if target == leaf:\n print(\"we have a winner: \", leaf)\n return True\n\n else:\n return False\n else:\n return False\n\n def get_max(self, leaf=None):\n leaf = leaf if leaf is not None else self.value\n if self.right is not None:\n leaf = self.right.value\n self.get_max(leaf)\n else:\n return leaf\n","sub_path":"binary_search_tree/binary_search_tree.py","file_name":"binary_search_tree.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"138019826","text":"import requests\n# for timestamp info\nfrom time import strftime, localtime\nfrom datetime import datetime\n\n# Flask imports\nfrom flask import Flask, render_template, request, redirect, url_for\nfrom flask_sqlalchemy import SQLAlchemy\n\n# app\napp = Flask(__name__)\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n API_KEY = '0cecf8365f48c0900489013ff0623926'\n\n # when user first time hits site, showing him Kraków Weather\n try:\n user_input = request.form.get('user_city')\n city = user_input.capitalize()\n except:\n city = 'Krakow'\n # getting api\n url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&units=metric&appid={API_KEY}'\n\n response = requests.get(url).json()\n\n # If name of city is wrong spell or unknown\n if response.get('cod') != 200:\n message = response.get('message', '')\n return f'Error getting {city.title()} ERROR = {message}'\n\n weather = {\n 'city': city,\n 'temperature': response['main']['temp'],\n 'humidity': response['main']['humidity'],\n 'wind': response['wind']['speed'],\n 'description': response['weather'][0]['description'],\n 'icon': response['weather'][0]['icon'],\n }\n\n time = strftime('%A %H:%M', localtime())\n temp_float = weather.get('temperature')\n temp_int = round(temp_float)\n\n # Forecast for next 5 days/nights\n\n # This api is showing forecast for five days so i couldnt use first one\n url_forecast = f'http://api.openweathermap.org/data/2.5/forecast?q={city}&units=metric&appid={API_KEY}'\n\n forecast_response = requests.get(url_forecast).json()\n\n # gettiing dict with temperature, date and icon for forecast\n def day_forecast():\n \"\"\"\"\n This function is taking API respone and looping trough all elements finding data for night temp, specified its acually 12:00 PM,\n and taking from this data: temperature and date\n\n Returning two list:\n First contains dicts and each dict contians info about temperautre and timestamp and weather icon\n Second contains week days\n \"\"\"\n temp_day = []\n for i in forecast_response['list']:\n foo = '12:00:00'\n if foo in i['dt_txt']:\n dictor = {\n 'date': i['dt'],\n 'temp': i['main']['temp'],\n 'icon': i['weather'][0]['icon'],\n 'date_txt': i['dt_txt']\n }\n temp_day.append(dictor)\n\n # This for loop is selecting all DT from respoonse and making list of it\n temport = []\n for d in temp_day:\n temport.append(d['date'])\n\n # This loop converting timestamp DT format to week days names and making list of it\n dates_formated = []\n for value in temport:\n dates_formated.append(\n datetime.utcfromtimestamp(value).strftime('%A'))\n return [temp_day, dates_formated]\n\n def night_forecast():\n \"\"\"\"\n This function is taking API respone and looping trough all elements finding data for night temp, specified its acually 3:00 AM,\n and taking from this data: temperature and date\n\n Returning list that contains dicts and each dict contians info about temperautre and timestamp\n \"\"\"\n\n temp_night = []\n for i in forecast_response['list']:\n foo = '03:00:00'\n if foo in i['dt_txt']:\n dictor = {\n 'date': i['dt_txt'],\n 'temp': i['main']['temp'],\n }\n temp_night.append(dictor)\n return temp_night\n\n day_forecast = day_forecast()\n\n night_forecast = night_forecast()\n\n return render_template('index.html', weather=weather, temp=temp_int, time=time,\n day_forecast=day_forecast, night_forecast=night_forecast)\n\n\n@app.route('//')\ndef city_forecast(city, date):\n\n API_KEY = '0cecf8365f48c0900489013ff0623926'\n\n # it explain itself(taking user input and making it capital letter)\n city = city.capitalize()\n\n # gettiing dict with temperature, date and icon for forecast every 3 hours\n url_forecast = f'http://api.openweathermap.org/data/2.5/forecast?q={city}&units=metric&appid={API_KEY}'\n\n forecast_response = requests.get(url_forecast).json()\n\n def detail_forecast():\n lst_details = []\n for item in forecast_response['list']:\n if date in item['dt_txt']:\n if '12:00' in item['dt_txt']:\n weather_detail = {\n 'city': city,\n 'date': item['dt_txt'],\n 'temperature': item['main']['temp_max'],\n 'feels_like': item['main']['feels_like'],\n 'humidity': item['main']['humidity'],\n 'wind': item['wind']['speed'],\n 'description': item['weather'][0]['description'],\n 'icon': item['weather'][0]['icon'],\n 'pressure': item['main']['pressure']\n }\n lst_details.append(weather_detail)\n return lst_details\n\n detail_forecast = detail_forecast()\n\n def hour_day_forecast():\n temp_hour = []\n for i in forecast_response['list']:\n foo = date\n if foo in i['dt_txt']:\n dictor = {\n 'date': i['dt_txt'],\n 'temp': i['main']['temp'],\n 'icon': i['weather'][0]['icon'],\n }\n temp_hour.append(dictor)\n return temp_hour\n\n hour_day_forecast = hour_day_forecast()\n\n def forecast_hours():\n hour_lst = []\n for hour in hour_day_forecast:\n hour_lst.append(hour['date'][11:16])\n return hour_lst\n\n forecast_hours = forecast_hours()\n\n def forecast_temperatures():\n temps_lst = []\n for temper in hour_day_forecast:\n rounded_temp = round(temper['temp'], 1)\n temps_lst.append(str(rounded_temp) + ' °C')\n return temps_lst\n\n forecast_temperatures = forecast_temperatures()\n\n time = strftime('%A %H:%M', localtime())\n\n return render_template('city_forecast.html', date=date, detail_forecast=detail_forecast, time=time,\n forecast_hours=forecast_hours, forecast_temperatures=forecast_temperatures)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"165565600","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"MiniAnalysis\")\n\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring('/store/mc/RunIIFall15MiniAODv2/TT_TuneCUETP8M1_13TeV-powheg-pythia8/MINIAODSIM/PU25nsData2015v1_76X_mcRun2_asymptotic_v12_ext4-v1/00000/FED166CC-2ED2-E511-8211-901B0E542962.root')\n)\nprocess.ak10PFJetsL1FastL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak10PFL1FastL2L3'),\n src = cms.InputTag(\"ak10PFJets\")\n)\n\n\nprocess.ak10PFJetsL1FastL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak10PFL1FastL2L3Residual'),\n src = cms.InputTag(\"ak10PFJets\")\n)\n\n\nprocess.ak10PFJetsL1L2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak10PFL1L2L3'),\n src = cms.InputTag(\"ak10PFJets\")\n)\n\n\nprocess.ak10PFJetsL1L2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak10PFL1L2L3Residual'),\n src = cms.InputTag(\"ak10PFJets\")\n)\n\n\nprocess.ak10PFJetsL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak10PFL2L3'),\n src = cms.InputTag(\"ak10PFJets\")\n)\n\n\nprocess.ak10PFJetsL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak10PFL2L3Residual'),\n src = cms.InputTag(\"ak10PFJets\")\n)\n\n\nprocess.ak1PFJetsL1FastL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak1PFL1FastL2L3'),\n src = cms.InputTag(\"ak1PFJets\")\n)\n\n\nprocess.ak1PFJetsL1FastL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak1PFL1FastL2L3Residual'),\n src = cms.InputTag(\"ak1PFJets\")\n)\n\n\nprocess.ak1PFJetsL1L2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak1PFL1L2L3'),\n src = cms.InputTag(\"ak1PFJets\")\n)\n\n\nprocess.ak1PFJetsL1L2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak1PFL1L2L3Residual'),\n src = cms.InputTag(\"ak1PFJets\")\n)\n\n\nprocess.ak1PFJetsL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak1PFL2L3'),\n src = cms.InputTag(\"ak1PFJets\")\n)\n\n\nprocess.ak1PFJetsL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak1PFL2L3Residual'),\n src = cms.InputTag(\"ak1PFJets\")\n)\n\n\nprocess.ak2PFJetsL1FastL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak2PFL1FastL2L3'),\n src = cms.InputTag(\"ak2PFJets\")\n)\n\n\nprocess.ak2PFJetsL1FastL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak2PFL1FastL2L3Residual'),\n src = cms.InputTag(\"ak2PFJets\")\n)\n\n\nprocess.ak2PFJetsL1L2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak2PFL1L2L3'),\n src = cms.InputTag(\"ak2PFJets\")\n)\n\n\nprocess.ak2PFJetsL1L2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak2PFL1L2L3Residual'),\n src = cms.InputTag(\"ak2PFJets\")\n)\n\n\nprocess.ak2PFJetsL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak2PFL2L3'),\n src = cms.InputTag(\"ak2PFJets\")\n)\n\n\nprocess.ak2PFJetsL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak2PFL2L3Residual'),\n src = cms.InputTag(\"ak2PFJets\")\n)\n\n\nprocess.ak3PFJetsL1FastL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak3PFL1FastL2L3'),\n src = cms.InputTag(\"ak3PFJets\")\n)\n\n\nprocess.ak3PFJetsL1FastL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak3PFL1FastL2L3Residual'),\n src = cms.InputTag(\"ak3PFJets\")\n)\n\n\nprocess.ak3PFJetsL1L2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak3PFL1L2L3'),\n src = cms.InputTag(\"ak3PFJets\")\n)\n\n\nprocess.ak3PFJetsL1L2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak3PFL1L2L3Residual'),\n src = cms.InputTag(\"ak3PFJets\")\n)\n\n\nprocess.ak3PFJetsL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak3PFL2L3'),\n src = cms.InputTag(\"ak3PFJets\")\n)\n\n\nprocess.ak3PFJetsL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak3PFL2L3Residual'),\n src = cms.InputTag(\"ak3PFJets\")\n)\n\n\nprocess.ak4CaloJetsL1FastL2L3 = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('ak4CaloL1FastL2L3'),\n src = cms.InputTag(\"ak4CaloJets\")\n)\n\n\nprocess.ak4CaloJetsL1FastL2L3Residual = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('ak4CaloL1FastL2L3Residual'),\n src = cms.InputTag(\"ak4CaloJets\")\n)\n\n\nprocess.ak4CaloJetsL1L2L3 = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('ak4CaloL1L2L3'),\n src = cms.InputTag(\"ak4CaloJets\")\n)\n\n\nprocess.ak4CaloJetsL1L2L3Residual = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('ak4CaloL1L2L3Residual'),\n src = cms.InputTag(\"ak4CaloJets\")\n)\n\n\nprocess.ak4CaloJetsL2L3 = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('ak4CaloL2L3'),\n src = cms.InputTag(\"ak4CaloJets\")\n)\n\n\nprocess.ak4CaloJetsL2L3Residual = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('ak4CaloL2L3Residual'),\n src = cms.InputTag(\"ak4CaloJets\")\n)\n\n\nprocess.ak4JPTJetsL1FastL2L3 = cms.EDProducer(\"JPTJetCorrectionProducer\",\n correctors = cms.vstring('ak4JPTL1FastL2L3'),\n src = cms.InputTag(\"JetPlusTrackZSPCorJetAntiKt4\")\n)\n\n\nprocess.ak4JPTJetsL1FastL2L3Residual = cms.EDProducer(\"JPTJetCorrectionProducer\",\n correctors = cms.vstring('ak4JPTL1FastL2L3Residual'),\n src = cms.InputTag(\"JetPlusTrackZSPCorJetAntiKt4\")\n)\n\n\nprocess.ak4JPTJetsL1L2L3 = cms.EDProducer(\"JPTJetCorrectionProducer\",\n correctors = cms.vstring('ak4JPTL1L2L3'),\n src = cms.InputTag(\"JetPlusTrackZSPCorJetAntiKt4\")\n)\n\n\nprocess.ak4JPTJetsL1L2L3Residual = cms.EDProducer(\"JPTJetCorrectionProducer\",\n correctors = cms.vstring('ak4JPTL1L2L3Residual'),\n src = cms.InputTag(\"JetPlusTrackZSPCorJetAntiKt4\")\n)\n\n\nprocess.ak4JPTJetsL2L3 = cms.EDProducer(\"JPTJetCorrectionProducer\",\n correctors = cms.vstring('ak4JPTL2L3'),\n src = cms.InputTag(\"JetPlusTrackZSPCorJetAntiKt4\")\n)\n\n\nprocess.ak4JPTJetsL2L3Residual = cms.EDProducer(\"JPTJetCorrectionProducer\",\n correctors = cms.vstring('ak4JPTL2L3Residual'),\n src = cms.InputTag(\"JetPlusTrackZSPCorJetAntiKt4\")\n)\n\n\nprocess.ak4PFJetsL1FastL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak4PFL1FastL2L3'),\n src = cms.InputTag(\"ak4PFJets\")\n)\n\n\nprocess.ak4PFJetsL1FastL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak4PFL1FastL2L3Residual'),\n src = cms.InputTag(\"ak4PFJets\")\n)\n\n\nprocess.ak4PFJetsL1L2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak4PFL1L2L3'),\n src = cms.InputTag(\"ak4PFJets\")\n)\n\n\nprocess.ak4PFJetsL1L2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak4PFL1L2L3Residual'),\n src = cms.InputTag(\"ak4PFJets\")\n)\n\n\nprocess.ak4PFJetsL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak4PFL2L3'),\n src = cms.InputTag(\"ak4PFJets\")\n)\n\n\nprocess.ak4PFJetsL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak4PFL2L3Residual'),\n src = cms.InputTag(\"ak4PFJets\")\n)\n\n\nprocess.ak4TrackJetsL2L3 = cms.EDProducer(\"TrackJetCorrectionProducer\",\n correctors = cms.vstring('ak4TrackL2L3'),\n src = cms.InputTag(\"ak4TrackJets\")\n)\n\n\nprocess.ak5PFJetsL1FastL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak5PFL1FastL2L3'),\n src = cms.InputTag(\"ak5PFJets\")\n)\n\n\nprocess.ak5PFJetsL1FastL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak5PFL1FastL2L3Residual'),\n src = cms.InputTag(\"ak5PFJets\")\n)\n\n\nprocess.ak5PFJetsL1L2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak5PFL1L2L3'),\n src = cms.InputTag(\"ak5PFJets\")\n)\n\n\nprocess.ak5PFJetsL1L2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak5PFL1L2L3Residual'),\n src = cms.InputTag(\"ak5PFJets\")\n)\n\n\nprocess.ak5PFJetsL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak5PFL2L3'),\n src = cms.InputTag(\"ak5PFJets\")\n)\n\n\nprocess.ak5PFJetsL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak5PFL2L3Residual'),\n src = cms.InputTag(\"ak5PFJets\")\n)\n\n\nprocess.ak6PFJetsL1FastL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak6PFL1FastL2L3'),\n src = cms.InputTag(\"ak6PFJets\")\n)\n\n\nprocess.ak6PFJetsL1FastL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak6PFL1FastL2L3Residual'),\n src = cms.InputTag(\"ak6PFJets\")\n)\n\n\nprocess.ak6PFJetsL1L2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak6PFL1L2L3'),\n src = cms.InputTag(\"ak6PFJets\")\n)\n\n\nprocess.ak6PFJetsL1L2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak6PFL1L2L3Residual'),\n src = cms.InputTag(\"ak6PFJets\")\n)\n\n\nprocess.ak6PFJetsL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak6PFL2L3'),\n src = cms.InputTag(\"ak6PFJets\")\n)\n\n\nprocess.ak6PFJetsL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak6PFL2L3Residual'),\n src = cms.InputTag(\"ak6PFJets\")\n)\n\n\nprocess.ak7CaloJetsL1FastL2L3 = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('ak7CaloL1FastL2L3'),\n src = cms.InputTag(\"ak7CaloJets\")\n)\n\n\nprocess.ak7CaloJetsL1FastL2L3Residual = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('ak7CaloL1FastL2L3Residual'),\n src = cms.InputTag(\"ak7CaloJets\")\n)\n\n\nprocess.ak7CaloJetsL1L2L3 = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('ak7CaloL1L2L3'),\n src = cms.InputTag(\"ak7CaloJets\")\n)\n\n\nprocess.ak7CaloJetsL1L2L3Residual = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('ak7CaloL1L2L3Residual'),\n src = cms.InputTag(\"ak7CaloJets\")\n)\n\n\nprocess.ak7CaloJetsL2L3 = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('ak7CaloL2L3'),\n src = cms.InputTag(\"ak7CaloJets\")\n)\n\n\nprocess.ak7CaloJetsL2L3Residual = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('ak7CaloL2L3Residual'),\n src = cms.InputTag(\"ak7CaloJets\")\n)\n\n\nprocess.ak7PFJetsL1FastL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak7PFL1FastL2L3'),\n src = cms.InputTag(\"ak7PFJets\")\n)\n\n\nprocess.ak7PFJetsL1FastL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak7PFL1FastL2L3Residual'),\n src = cms.InputTag(\"ak7PFJets\")\n)\n\n\nprocess.ak7PFJetsL1L2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak7PFL1L2L3'),\n src = cms.InputTag(\"ak7PFJets\")\n)\n\n\nprocess.ak7PFJetsL1L2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak7PFL1L2L3Residual'),\n src = cms.InputTag(\"ak7PFJets\")\n)\n\n\nprocess.ak7PFJetsL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak7PFL2L3'),\n src = cms.InputTag(\"ak7PFJets\")\n)\n\n\nprocess.ak7PFJetsL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak7PFL2L3Residual'),\n src = cms.InputTag(\"ak7PFJets\")\n)\n\n\nprocess.ak8PFJetsL1FastL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak8PFL1FastL2L3'),\n src = cms.InputTag(\"ak8PFJets\")\n)\n\n\nprocess.ak8PFJetsL1FastL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak8PFL1FastL2L3Residual'),\n src = cms.InputTag(\"ak8PFJets\")\n)\n\n\nprocess.ak8PFJetsL1L2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak8PFL1L2L3'),\n src = cms.InputTag(\"ak8PFJets\")\n)\n\n\nprocess.ak8PFJetsL1L2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak8PFL1L2L3Residual'),\n src = cms.InputTag(\"ak8PFJets\")\n)\n\n\nprocess.ak8PFJetsL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak8PFL2L3'),\n src = cms.InputTag(\"ak8PFJets\")\n)\n\n\nprocess.ak8PFJetsL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak8PFL2L3Residual'),\n src = cms.InputTag(\"ak8PFJets\")\n)\n\n\nprocess.ak9PFJetsL1FastL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak9PFL1FastL2L3'),\n src = cms.InputTag(\"ak9PFJets\")\n)\n\n\nprocess.ak9PFJetsL1FastL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak9PFL1FastL2L3Residual'),\n src = cms.InputTag(\"ak9PFJets\")\n)\n\n\nprocess.ak9PFJetsL1L2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak9PFL1L2L3'),\n src = cms.InputTag(\"ak9PFJets\")\n)\n\n\nprocess.ak9PFJetsL1L2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak9PFL1L2L3Residual'),\n src = cms.InputTag(\"ak9PFJets\")\n)\n\n\nprocess.ak9PFJetsL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak9PFL2L3'),\n src = cms.InputTag(\"ak9PFJets\")\n)\n\n\nprocess.ak9PFJetsL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ak9PFL2L3Residual'),\n src = cms.InputTag(\"ak9PFJets\")\n)\n\n\nprocess.egmGsfElectronIDs = cms.EDProducer(\"VersionedGsfElectronIdProducer\",\n physicsObjectIDs = cms.VPSet(cms.PSet(\n idDefinition = cms.PSet(\n cutFlow = cms.VPSet(cms.PSet(\n cutName = cms.string('GsfEleMVACut'),\n isIgnored = cms.bool(False),\n mvaCategoriesMapName = cms.InputTag(\"electronMVAValueMapProducer\",\"ElectronMVAEstimatorRun2Spring15Trig25nsV1Categories\"),\n mvaCuts = cms.vdouble(0.988153, 0.96791, 0.841729),\n mvaValueMapName = cms.InputTag(\"electronMVAValueMapProducer\",\"ElectronMVAEstimatorRun2Spring15Trig25nsV1Values\"),\n needsAdditionalProducts = cms.bool(True)\n )),\n idName = cms.string('mvaEleID-Spring15-25ns-Trig-V1-wp80')\n ),\n idMD5 = cms.string('81046ab478185af337be1be9b30948ae'),\n isPOGApproved = cms.untracked.bool(True)\n ), \n cms.PSet(\n idDefinition = cms.PSet(\n cutFlow = cms.VPSet(cms.PSet(\n cutName = cms.string('GsfEleMVACut'),\n isIgnored = cms.bool(False),\n mvaCategoriesMapName = cms.InputTag(\"electronMVAValueMapProducer\",\"ElectronMVAEstimatorRun2Spring15Trig25nsV1Categories\"),\n mvaCuts = cms.vdouble(0.972153, 0.922126, 0.610764),\n mvaValueMapName = cms.InputTag(\"electronMVAValueMapProducer\",\"ElectronMVAEstimatorRun2Spring15Trig25nsV1Values\"),\n needsAdditionalProducts = cms.bool(True)\n )),\n idName = cms.string('mvaEleID-Spring15-25ns-Trig-V1-wp90')\n ),\n idMD5 = cms.string('bb430b638bf3a4d970627021b0da63ae'),\n isPOGApproved = cms.untracked.bool(True)\n ), \n cms.PSet(\n idDefinition = cms.PSet(\n cutFlow = cms.VPSet(cms.PSet(\n cutName = cms.string('MinPtCut'),\n isIgnored = cms.bool(False),\n minPt = cms.double(5.0),\n needsAdditionalProducts = cms.bool(False)\n ), \n cms.PSet(\n allowedEtaRanges = cms.VPSet(cms.PSet(\n maxEta = cms.double(1.479),\n minEta = cms.double(0.0)\n ), \n cms.PSet(\n maxEta = cms.double(2.5),\n minEta = cms.double(1.479)\n )),\n cutName = cms.string('GsfEleSCEtaMultiRangeCut'),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(False),\n useAbsEta = cms.bool(True)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleDEtaInCut'),\n dEtaInCutValueEB = cms.double(0.0105),\n dEtaInCutValueEE = cms.double(0.00814),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(False)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleDPhiInCut'),\n dPhiInCutValueEB = cms.double(0.115),\n dPhiInCutValueEE = cms.double(0.182),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(False)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleFull5x5SigmaIEtaIEtaCut'),\n full5x5SigmaIEtaIEtaCutValueEB = cms.double(0.0103),\n full5x5SigmaIEtaIEtaCutValueEE = cms.double(0.0301),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(False)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleHadronicOverEMCut'),\n hadronicOverEMCutValueEB = cms.double(0.104),\n hadronicOverEMCutValueEE = cms.double(0.0897),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(False)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleDxyCut'),\n dxyCutValueEB = cms.double(0.0261),\n dxyCutValueEE = cms.double(0.118),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(True),\n vertexSrc = cms.InputTag(\"offlinePrimaryVertices\"),\n vertexSrcMiniAOD = cms.InputTag(\"offlineSlimmedPrimaryVertices\")\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleDzCut'),\n dzCutValueEB = cms.double(0.41),\n dzCutValueEE = cms.double(0.822),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(True),\n vertexSrc = cms.InputTag(\"offlinePrimaryVertices\"),\n vertexSrcMiniAOD = cms.InputTag(\"offlineSlimmedPrimaryVertices\")\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleEInverseMinusPInverseCut'),\n eInverseMinusPInverseCutValueEB = cms.double(0.102),\n eInverseMinusPInverseCutValueEE = cms.double(0.126),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(False)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleEffAreaPFIsoCut'),\n effAreasConfigFile = cms.FileInPath('RecoEgamma/ElectronIdentification/data/Spring15/effAreaElectrons_cone03_pfNeuHadronsAndPhotons_25ns.txt'),\n isIgnored = cms.bool(False),\n isRelativeIso = cms.bool(True),\n isoCutEBHighPt = cms.double(0.0893),\n isoCutEBLowPt = cms.double(0.0893),\n isoCutEEHighPt = cms.double(0.121),\n isoCutEELowPt = cms.double(0.121),\n needsAdditionalProducts = cms.bool(True),\n ptCutOff = cms.double(20.0),\n rho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n ), \n cms.PSet(\n beamspotSrc = cms.InputTag(\"offlineBeamSpot\"),\n conversionSrc = cms.InputTag(\"allConversions\"),\n conversionSrcMiniAOD = cms.InputTag(\"reducedEgamma\",\"reducedConversions\"),\n cutName = cms.string('GsfEleConversionVetoCut'),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(True)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleMissingHitsCut'),\n isIgnored = cms.bool(False),\n maxMissingHitsEB = cms.uint32(2),\n maxMissingHitsEE = cms.uint32(1),\n needsAdditionalProducts = cms.bool(False)\n )),\n idName = cms.string('cutBasedElectronID-Spring15-25ns-V1-standalone-loose')\n ),\n idMD5 = cms.string('4fab9e4d09a2c1a36cbbd2279deb3627'),\n isPOGApproved = cms.untracked.bool(True)\n ), \n cms.PSet(\n idDefinition = cms.PSet(\n cutFlow = cms.VPSet(cms.PSet(\n cutName = cms.string('MinPtCut'),\n isIgnored = cms.bool(False),\n minPt = cms.double(5.0),\n needsAdditionalProducts = cms.bool(False)\n ), \n cms.PSet(\n allowedEtaRanges = cms.VPSet(cms.PSet(\n maxEta = cms.double(1.479),\n minEta = cms.double(0.0)\n ), \n cms.PSet(\n maxEta = cms.double(2.5),\n minEta = cms.double(1.479)\n )),\n cutName = cms.string('GsfEleSCEtaMultiRangeCut'),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(False),\n useAbsEta = cms.bool(True)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleDEtaInCut'),\n dEtaInCutValueEB = cms.double(0.0103),\n dEtaInCutValueEE = cms.double(0.00733),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(False)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleDPhiInCut'),\n dPhiInCutValueEB = cms.double(0.0336),\n dPhiInCutValueEE = cms.double(0.114),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(False)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleFull5x5SigmaIEtaIEtaCut'),\n full5x5SigmaIEtaIEtaCutValueEB = cms.double(0.0101),\n full5x5SigmaIEtaIEtaCutValueEE = cms.double(0.0283),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(False)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleHadronicOverEMCut'),\n hadronicOverEMCutValueEB = cms.double(0.0876),\n hadronicOverEMCutValueEE = cms.double(0.0678),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(False)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleDxyCut'),\n dxyCutValueEB = cms.double(0.0118),\n dxyCutValueEE = cms.double(0.0739),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(True),\n vertexSrc = cms.InputTag(\"offlinePrimaryVertices\"),\n vertexSrcMiniAOD = cms.InputTag(\"offlineSlimmedPrimaryVertices\")\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleDzCut'),\n dzCutValueEB = cms.double(0.373),\n dzCutValueEE = cms.double(0.602),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(True),\n vertexSrc = cms.InputTag(\"offlinePrimaryVertices\"),\n vertexSrcMiniAOD = cms.InputTag(\"offlineSlimmedPrimaryVertices\")\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleEInverseMinusPInverseCut'),\n eInverseMinusPInverseCutValueEB = cms.double(0.0174),\n eInverseMinusPInverseCutValueEE = cms.double(0.0898),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(False)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleEffAreaPFIsoCut'),\n effAreasConfigFile = cms.FileInPath('RecoEgamma/ElectronIdentification/data/Spring15/effAreaElectrons_cone03_pfNeuHadronsAndPhotons_25ns.txt'),\n isIgnored = cms.bool(False),\n isRelativeIso = cms.bool(True),\n isoCutEBHighPt = cms.double(0.0766),\n isoCutEBLowPt = cms.double(0.0766),\n isoCutEEHighPt = cms.double(0.0678),\n isoCutEELowPt = cms.double(0.0678),\n needsAdditionalProducts = cms.bool(True),\n ptCutOff = cms.double(20.0),\n rho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n ), \n cms.PSet(\n beamspotSrc = cms.InputTag(\"offlineBeamSpot\"),\n conversionSrc = cms.InputTag(\"allConversions\"),\n conversionSrcMiniAOD = cms.InputTag(\"reducedEgamma\",\"reducedConversions\"),\n cutName = cms.string('GsfEleConversionVetoCut'),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(True)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleMissingHitsCut'),\n isIgnored = cms.bool(False),\n maxMissingHitsEB = cms.uint32(2),\n maxMissingHitsEE = cms.uint32(1),\n needsAdditionalProducts = cms.bool(False)\n )),\n idName = cms.string('cutBasedElectronID-Spring15-25ns-V1-standalone-medium')\n ),\n idMD5 = cms.string('aa291aba714c148fcba156544907c440'),\n isPOGApproved = cms.untracked.bool(True)\n ), \n cms.PSet(\n idDefinition = cms.PSet(\n cutFlow = cms.VPSet(cms.PSet(\n cutName = cms.string('MinPtCut'),\n isIgnored = cms.bool(False),\n minPt = cms.double(5.0),\n needsAdditionalProducts = cms.bool(False)\n ), \n cms.PSet(\n allowedEtaRanges = cms.VPSet(cms.PSet(\n maxEta = cms.double(1.479),\n minEta = cms.double(0.0)\n ), \n cms.PSet(\n maxEta = cms.double(2.5),\n minEta = cms.double(1.479)\n )),\n cutName = cms.string('GsfEleSCEtaMultiRangeCut'),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(False),\n useAbsEta = cms.bool(True)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleDEtaInCut'),\n dEtaInCutValueEB = cms.double(0.00926),\n dEtaInCutValueEE = cms.double(0.00724),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(False)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleDPhiInCut'),\n dPhiInCutValueEB = cms.double(0.0336),\n dPhiInCutValueEE = cms.double(0.0918),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(False)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleFull5x5SigmaIEtaIEtaCut'),\n full5x5SigmaIEtaIEtaCutValueEB = cms.double(0.0101),\n full5x5SigmaIEtaIEtaCutValueEE = cms.double(0.0279),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(False)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleHadronicOverEMCut'),\n hadronicOverEMCutValueEB = cms.double(0.0597),\n hadronicOverEMCutValueEE = cms.double(0.0615),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(False)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleDxyCut'),\n dxyCutValueEB = cms.double(0.0111),\n dxyCutValueEE = cms.double(0.0351),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(True),\n vertexSrc = cms.InputTag(\"offlinePrimaryVertices\"),\n vertexSrcMiniAOD = cms.InputTag(\"offlineSlimmedPrimaryVertices\")\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleDzCut'),\n dzCutValueEB = cms.double(0.0466),\n dzCutValueEE = cms.double(0.417),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(True),\n vertexSrc = cms.InputTag(\"offlinePrimaryVertices\"),\n vertexSrcMiniAOD = cms.InputTag(\"offlineSlimmedPrimaryVertices\")\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleEInverseMinusPInverseCut'),\n eInverseMinusPInverseCutValueEB = cms.double(0.012),\n eInverseMinusPInverseCutValueEE = cms.double(0.00999),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(False)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleEffAreaPFIsoCut'),\n effAreasConfigFile = cms.FileInPath('RecoEgamma/ElectronIdentification/data/Spring15/effAreaElectrons_cone03_pfNeuHadronsAndPhotons_25ns.txt'),\n isIgnored = cms.bool(False),\n isRelativeIso = cms.bool(True),\n isoCutEBHighPt = cms.double(0.0354),\n isoCutEBLowPt = cms.double(0.0354),\n isoCutEEHighPt = cms.double(0.0646),\n isoCutEELowPt = cms.double(0.0646),\n needsAdditionalProducts = cms.bool(True),\n ptCutOff = cms.double(20.0),\n rho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n ), \n cms.PSet(\n beamspotSrc = cms.InputTag(\"offlineBeamSpot\"),\n conversionSrc = cms.InputTag(\"allConversions\"),\n conversionSrcMiniAOD = cms.InputTag(\"reducedEgamma\",\"reducedConversions\"),\n cutName = cms.string('GsfEleConversionVetoCut'),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(True)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleMissingHitsCut'),\n isIgnored = cms.bool(False),\n maxMissingHitsEB = cms.uint32(2),\n maxMissingHitsEE = cms.uint32(1),\n needsAdditionalProducts = cms.bool(False)\n )),\n idName = cms.string('cutBasedElectronID-Spring15-25ns-V1-standalone-tight')\n ),\n idMD5 = cms.string('4e13b87c0573d3c8ebf91d446fa1d90f'),\n isPOGApproved = cms.untracked.bool(True)\n ), \n cms.PSet(\n idDefinition = cms.PSet(\n cutFlow = cms.VPSet(cms.PSet(\n cutName = cms.string('MinPtCut'),\n isIgnored = cms.bool(False),\n minPt = cms.double(5.0),\n needsAdditionalProducts = cms.bool(False)\n ), \n cms.PSet(\n allowedEtaRanges = cms.VPSet(cms.PSet(\n maxEta = cms.double(1.479),\n minEta = cms.double(0.0)\n ), \n cms.PSet(\n maxEta = cms.double(2.5),\n minEta = cms.double(1.479)\n )),\n cutName = cms.string('GsfEleSCEtaMultiRangeCut'),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(False),\n useAbsEta = cms.bool(True)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleDEtaInCut'),\n dEtaInCutValueEB = cms.double(0.0152),\n dEtaInCutValueEE = cms.double(0.0113),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(False)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleDPhiInCut'),\n dPhiInCutValueEB = cms.double(0.216),\n dPhiInCutValueEE = cms.double(0.237),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(False)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleFull5x5SigmaIEtaIEtaCut'),\n full5x5SigmaIEtaIEtaCutValueEB = cms.double(0.0114),\n full5x5SigmaIEtaIEtaCutValueEE = cms.double(0.0352),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(False)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleHadronicOverEMCut'),\n hadronicOverEMCutValueEB = cms.double(0.181),\n hadronicOverEMCutValueEE = cms.double(0.116),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(False)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleDxyCut'),\n dxyCutValueEB = cms.double(0.0564),\n dxyCutValueEE = cms.double(0.222),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(True),\n vertexSrc = cms.InputTag(\"offlinePrimaryVertices\"),\n vertexSrcMiniAOD = cms.InputTag(\"offlineSlimmedPrimaryVertices\")\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleDzCut'),\n dzCutValueEB = cms.double(0.472),\n dzCutValueEE = cms.double(0.921),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(True),\n vertexSrc = cms.InputTag(\"offlinePrimaryVertices\"),\n vertexSrcMiniAOD = cms.InputTag(\"offlineSlimmedPrimaryVertices\")\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleEInverseMinusPInverseCut'),\n eInverseMinusPInverseCutValueEB = cms.double(0.207),\n eInverseMinusPInverseCutValueEE = cms.double(0.174),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(False)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleEffAreaPFIsoCut'),\n effAreasConfigFile = cms.FileInPath('RecoEgamma/ElectronIdentification/data/Spring15/effAreaElectrons_cone03_pfNeuHadronsAndPhotons_25ns.txt'),\n isIgnored = cms.bool(False),\n isRelativeIso = cms.bool(True),\n isoCutEBHighPt = cms.double(0.126),\n isoCutEBLowPt = cms.double(0.126),\n isoCutEEHighPt = cms.double(0.144),\n isoCutEELowPt = cms.double(0.144),\n needsAdditionalProducts = cms.bool(True),\n ptCutOff = cms.double(20.0),\n rho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n ), \n cms.PSet(\n beamspotSrc = cms.InputTag(\"offlineBeamSpot\"),\n conversionSrc = cms.InputTag(\"allConversions\"),\n conversionSrcMiniAOD = cms.InputTag(\"reducedEgamma\",\"reducedConversions\"),\n cutName = cms.string('GsfEleConversionVetoCut'),\n isIgnored = cms.bool(False),\n needsAdditionalProducts = cms.bool(True)\n ), \n cms.PSet(\n barrelCutOff = cms.double(1.479),\n cutName = cms.string('GsfEleMissingHitsCut'),\n isIgnored = cms.bool(False),\n maxMissingHitsEB = cms.uint32(2),\n maxMissingHitsEE = cms.uint32(3),\n needsAdditionalProducts = cms.bool(False)\n )),\n idName = cms.string('cutBasedElectronID-Spring15-25ns-V1-standalone-veto')\n ),\n idMD5 = cms.string('202030579ee3eec90fdc2d236ba3de7e'),\n isPOGApproved = cms.untracked.bool(True)\n )),\n physicsObjectSrc = cms.InputTag(\"slimmedElectrons\")\n)\n\n\nprocess.electronMVAValueMapProducer = cms.EDProducer(\"ElectronMVAValueMapProducer\",\n mvaConfigurations = cms.VPSet(cms.PSet(\n mvaName = cms.string('ElectronMVAEstimatorRun2Phys14NonTrig'),\n mvaTag = cms.string('25nsV1'),\n weightFileNames = cms.vstring('RecoEgamma/ElectronIdentification/data/PHYS14/EIDmva_EB1_5_oldscenario2phys14_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/PHYS14/EIDmva_EB2_5_oldscenario2phys14_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/PHYS14/EIDmva_EE_5_oldscenario2phys14_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/PHYS14/EIDmva_EB1_10_oldscenario2phys14_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/PHYS14/EIDmva_EB2_10_oldscenario2phys14_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/PHYS14/EIDmva_EE_10_oldscenario2phys14_BDT.weights.xml')\n ), \n cms.PSet(\n beamSpot = cms.InputTag(\"offlineBeamSpot\"),\n conversionsAOD = cms.InputTag(\"allConversions\"),\n conversionsMiniAOD = cms.InputTag(\"reducedEgamma\",\"reducedConversions\"),\n mvaName = cms.string('ElectronMVAEstimatorRun2Spring15NonTrig'),\n mvaTag = cms.string('25nsV1'),\n weightFileNames = cms.vstring('RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EB1_5_oldNonTrigSpring15_ConvVarCwoBoolean_TMVA412_FullStatLowPt_PairNegWeightsGlobal_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EB2_5_oldNonTrigSpring15_ConvVarCwoBoolean_TMVA412_FullStatLowPt_PairNegWeightsGlobal_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EE_5_oldNonTrigSpring15_ConvVarCwoBoolean_TMVA412_FullStatLowPt_PairNegWeightsGlobal_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EB1_10_oldNonTrigSpring15_ConvVarCwoBoolean_TMVA412_FullStatLowPt_PairNegWeightsGlobal_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EB2_10_oldNonTrigSpring15_ConvVarCwoBoolean_TMVA412_FullStatLowPt_PairNegWeightsGlobal_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EE_10_oldNonTrigSpring15_ConvVarCwoBoolean_TMVA412_FullStatLowPt_PairNegWeightsGlobal_BDT.weights.xml')\n ), \n cms.PSet(\n beamSpot = cms.InputTag(\"offlineBeamSpot\"),\n conversionsAOD = cms.InputTag(\"allConversions\"),\n conversionsMiniAOD = cms.InputTag(\"reducedEgamma\",\"reducedConversions\"),\n mvaName = cms.string('ElectronMVAEstimatorRun2Spring15Trig'),\n mvaTag = cms.string('50nsV1'),\n weightFileNames = cms.vstring('RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EB1_10_oldTrigSpring15_50ns_data_1_VarD_TMVA412_Sig6BkgAll_MG_noSpec_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EB2_10_oldTrigSpring15_50ns_data_1_VarD_TMVA412_Sig6BkgAll_MG_noSpec_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EE_10_oldTrigSpring15_50ns_data_1_VarD_TMVA412_Sig6BkgAll_MG_noSpec_BDT.weights.xml')\n ), \n cms.PSet(\n beamSpot = cms.InputTag(\"offlineBeamSpot\"),\n conversionsAOD = cms.InputTag(\"allConversions\"),\n conversionsMiniAOD = cms.InputTag(\"reducedEgamma\",\"reducedConversions\"),\n mvaName = cms.string('ElectronMVAEstimatorRun2Spring15Trig'),\n mvaTag = cms.string('25nsV1'),\n weightFileNames = cms.vstring('RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EB1_10_oldTrigSpring15_25ns_data_1_VarD_TMVA412_Sig6BkgAll_MG_noSpec_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EB2_10_oldTrigSpring15_25ns_data_1_VarD_TMVA412_Sig6BkgAll_MG_noSpec_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EE_10_oldTrigSpring15_25ns_data_1_VarD_TMVA412_Sig6BkgAll_MG_noSpec_BDT.weights.xml')\n )),\n src = cms.InputTag(\"gedGsfElectrons\"),\n srcMiniAOD = cms.InputTag(\"slimmedElectrons\",\"\",\"@skipCurrentProcess\")\n)\n\n\nprocess.electronRegressionValueMapProducer = cms.EDProducer(\"ElectronRegressionValueMapProducer\",\n ebReducedRecHitCollection = cms.InputTag(\"reducedEcalRecHitsEB\"),\n ebReducedRecHitCollectionMiniAOD = cms.InputTag(\"reducedEgamma\",\"reducedEBRecHits\"),\n eeReducedRecHitCollection = cms.InputTag(\"reducedEcalRecHitsEE\"),\n eeReducedRecHitCollectionMiniAOD = cms.InputTag(\"reducedEgamma\",\"reducedEERecHits\"),\n esReducedRecHitCollection = cms.InputTag(\"reducedEcalRecHitsES\"),\n esReducedRecHitCollectionMiniAOD = cms.InputTag(\"reducedEgamma\",\"reducedESRecHits\"),\n src = cms.InputTag(\"gedGsfElectrons\"),\n srcMiniAOD = cms.InputTag(\"slimmedElectrons\",\"\",\"@skipCurrentProcess\"),\n useFull5x5 = cms.bool(False)\n)\n\n\nprocess.ic5CaloJetsL1FastL2L3 = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('ic5CaloL1FastL2L3'),\n src = cms.InputTag(\"iterativeCone5CaloJets\")\n)\n\n\nprocess.ic5CaloJetsL1FastL2L3Residual = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('ic5CaloL1FastL2L3Residual'),\n src = cms.InputTag(\"iterativeCone5CaloJets\")\n)\n\n\nprocess.ic5CaloJetsL1L2L3 = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('ic5CaloL1L2L3'),\n src = cms.InputTag(\"iterativeCone5CaloJets\")\n)\n\n\nprocess.ic5CaloJetsL1L2L3Residual = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('ic5CaloL1L2L3Residual'),\n src = cms.InputTag(\"iterativeCone5CaloJets\")\n)\n\n\nprocess.ic5CaloJetsL2L3 = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('ic5CaloL2L3'),\n src = cms.InputTag(\"iterativeCone5CaloJets\")\n)\n\n\nprocess.ic5CaloJetsL2L3Residual = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('ic5CaloL2L3Residual'),\n src = cms.InputTag(\"iterativeCone5CaloJets\")\n)\n\n\nprocess.ic5PFJetsL1FastL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ic5PFL1FastL2L3'),\n src = cms.InputTag(\"iterativeCone5PFJets\")\n)\n\n\nprocess.ic5PFJetsL1FastL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ic5PFL1FastL2L3Residual'),\n src = cms.InputTag(\"iterativeCone5PFJets\")\n)\n\n\nprocess.ic5PFJetsL1L2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ic5PFL1L2L3'),\n src = cms.InputTag(\"iterativeCone5PFJets\")\n)\n\n\nprocess.ic5PFJetsL1L2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ic5PFL1L2L3Residual'),\n src = cms.InputTag(\"iterativeCone5PFJets\")\n)\n\n\nprocess.ic5PFJetsL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ic5PFL2L3'),\n src = cms.InputTag(\"iterativeCone5PFJets\")\n)\n\n\nprocess.ic5PFJetsL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('ic5PFL2L3Residual'),\n src = cms.InputTag(\"iterativeCone5PFJets\")\n)\n\n\nprocess.kt4CaloJetsL1FastL2L3 = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('kt4CaloL1FastL2L3'),\n src = cms.InputTag(\"kt4CaloJets\")\n)\n\n\nprocess.kt4CaloJetsL1FastL2L3Residual = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('kt4CaloL1FastL2L3Residual'),\n src = cms.InputTag(\"kt4CaloJets\")\n)\n\n\nprocess.kt4CaloJetsL1L2L3 = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('kt4CaloL1L2L3'),\n src = cms.InputTag(\"kt4CaloJets\")\n)\n\n\nprocess.kt4CaloJetsL1L2L3Residual = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('kt4CaloL1L2L3Residual'),\n src = cms.InputTag(\"kt4CaloJets\")\n)\n\n\nprocess.kt4CaloJetsL2L3 = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('kt4CaloL2L3'),\n src = cms.InputTag(\"kt4CaloJets\")\n)\n\n\nprocess.kt4CaloJetsL2L3Residual = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('kt4CaloL2L3Residual'),\n src = cms.InputTag(\"kt4CaloJets\")\n)\n\n\nprocess.kt4PFJetsL1FastL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('kt4PFL1FastL2L3'),\n src = cms.InputTag(\"kt4PFJets\")\n)\n\n\nprocess.kt4PFJetsL1FastL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('kt4PFL1FastL2L3Residual'),\n src = cms.InputTag(\"kt4PFJets\")\n)\n\n\nprocess.kt4PFJetsL1L2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('kt4PFL1L2L3'),\n src = cms.InputTag(\"kt4PFJets\")\n)\n\n\nprocess.kt4PFJetsL1L2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('kt4PFL1L2L3Residual'),\n src = cms.InputTag(\"kt4PFJets\")\n)\n\n\nprocess.kt4PFJetsL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('kt4PFL2L3'),\n src = cms.InputTag(\"kt4PFJets\")\n)\n\n\nprocess.kt4PFJetsL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('kt4PFL2L3Residual'),\n src = cms.InputTag(\"kt4PFJets\")\n)\n\n\nprocess.kt6CaloJetsL1FastL2L3 = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('kt6CaloL1FastL2L3'),\n src = cms.InputTag(\"kt6CaloJets\")\n)\n\n\nprocess.kt6CaloJetsL1FastL2L3Residual = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('kt6CaloL1FastL2L3Residual'),\n src = cms.InputTag(\"kt6CaloJets\")\n)\n\n\nprocess.kt6CaloJetsL1L2L3 = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('kt6CaloL1L2L3'),\n src = cms.InputTag(\"kt6CaloJets\")\n)\n\n\nprocess.kt6CaloJetsL1L2L3Residual = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('kt6CaloL1L2L3Residual'),\n src = cms.InputTag(\"kt6CaloJets\")\n)\n\n\nprocess.kt6CaloJetsL2L3 = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('kt6CaloL2L3'),\n src = cms.InputTag(\"kt6CaloJets\")\n)\n\n\nprocess.kt6CaloJetsL2L3Residual = cms.EDProducer(\"CaloJetCorrectionProducer\",\n correctors = cms.vstring('kt6CaloL2L3Residual'),\n src = cms.InputTag(\"kt6CaloJets\")\n)\n\n\nprocess.kt6PFJetsL1FastL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('kt6PFL1FastL2L3'),\n src = cms.InputTag(\"kt6PFJets\")\n)\n\n\nprocess.kt6PFJetsL1FastL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('kt6PFL1FastL2L3Residual'),\n src = cms.InputTag(\"kt6PFJets\")\n)\n\n\nprocess.kt6PFJetsL1L2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('kt6PFL1L2L3'),\n src = cms.InputTag(\"kt6PFJets\")\n)\n\n\nprocess.kt6PFJetsL1L2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('kt6PFL1L2L3Residual'),\n src = cms.InputTag(\"kt6PFJets\")\n)\n\n\nprocess.kt6PFJetsL2L3 = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('kt6PFL2L3'),\n src = cms.InputTag(\"kt6PFJets\")\n)\n\n\nprocess.kt6PFJetsL2L3Residual = cms.EDProducer(\"PFJetCorrectionProducer\",\n correctors = cms.vstring('kt6PFL2L3Residual'),\n src = cms.InputTag(\"kt6PFJets\")\n)\n\n\nprocess.patJetCorrFactorsReapplyJEC = cms.EDProducer(\"JetCorrFactorsProducer\",\n emf = cms.bool(False),\n extraJPTOffset = cms.string('L1FastJet'),\n flavorType = cms.string('J'),\n levels = cms.vstring('L1FastJet', \n 'L2Relative', \n 'L3Absolute'),\n payload = cms.string('AK4PFchs'),\n primaryVertices = cms.InputTag(\"offlineSlimmedPrimaryVertices\"),\n rho = cms.InputTag(\"fixedGridRhoFastjetAll\"),\n src = cms.InputTag(\"slimmedJets\"),\n useNPV = cms.bool(True),\n useRho = cms.bool(True)\n)\n\n\nprocess.pseudoTop = cms.EDProducer(\"PseudoTopProducer\",\n finalStates = cms.InputTag(\"packedGenParticles\"),\n genParticles = cms.InputTag(\"prunedGenParticles\"),\n jetConeSize = cms.double(0.4),\n jetMaxEta = cms.double(5.0),\n jetMinPt = cms.double(20),\n leptonConeSize = cms.double(0.1),\n leptonMaxEta = cms.double(2.5),\n leptonMinPt = cms.double(20),\n tMass = cms.double(172.5),\n wMass = cms.double(80.4)\n)\n\n\nprocess.randomEngineStateProducer = cms.EDProducer(\"RandomEngineStateProducer\")\n\n\nprocess.slimmedJetsReapplyJEC = cms.EDProducer(\"PATJetUpdater\",\n addJetCorrFactors = cms.bool(True),\n jetCorrFactorsSource = cms.VInputTag(cms.InputTag(\"patJetCorrFactorsReapplyJEC\")),\n jetSource = cms.InputTag(\"slimmedJets\"),\n userData = cms.PSet(\n userCands = cms.PSet(\n src = cms.VInputTag(\"\")\n ),\n userClasses = cms.PSet(\n src = cms.VInputTag(\"\")\n ),\n userFloats = cms.PSet(\n src = cms.VInputTag(\"\")\n ),\n userFunctionLabels = cms.vstring(),\n userFunctions = cms.vstring(),\n userInts = cms.PSet(\n src = cms.VInputTag(\"\")\n )\n )\n)\n\n\nprocess.analysis = cms.EDAnalyzer(\"MiniAnalyzer\",\n elTriggersToUse = cms.vstring('Ele22_eta2p1_WPLoose_Gsf_v'),\n eleTightIdFullInfoMap = cms.InputTag(\"egmGsfElectronIDs\",\"cutBasedElectronID-Spring15-25ns-V1-standalone-medium\"),\n eleTightIdMap = cms.InputTag(\"egmGsfElectronIDs\",\"cutBasedElectronID-Spring15-25ns-V1-standalone-medium\"),\n eleVetoIdMap = cms.InputTag(\"egmGsfElectronIDs\",\"cutBasedElectronID-Spring15-25ns-V1-standalone-loose\"),\n electrons = cms.InputTag(\"slimmedElectrons\"),\n jets = cms.InputTag(\"slimmedJetsReapplyJEC\"),\n mets = cms.InputTag(\"slimmedMETs\"),\n muTriggersToUse = cms.vstring('IsoMu20_v', \n 'IsoTkMu20_v'),\n muons = cms.InputTag(\"slimmedMuons\"),\n pfCands = cms.InputTag(\"packedPFCandidates\"),\n prescales = cms.InputTag(\"patTrigger\"),\n puppimets = cms.InputTag(\"slimmedMETsPuppi\"),\n rho = cms.InputTag(\"fixedGridRhoFastjetAll\"),\n saveTree = cms.bool(True),\n triggerBits = cms.InputTag(\"TriggerResults\",\"\",\"HLT\"),\n vertices = cms.InputTag(\"offlineSlimmedPrimaryVertices\")\n)\n\n\nprocess.customizeJetToolsSequence = cms.Sequence(process.patJetCorrFactorsReapplyJEC+process.slimmedJetsReapplyJEC)\n\n\nprocess.egmGsfElectronIDSequence = cms.Sequence(process.electronMVAValueMapProducer+process.egmGsfElectronIDs+process.electronRegressionValueMapProducer)\n\n\nprocess.p = cms.Path(process.egmGsfElectronIDSequence+process.customizeJetToolsSequence+process.pseudoTop+process.analysis)\n\n\nprocess.DQMStore = cms.Service(\"DQMStore\",\n LSbasedMode = cms.untracked.bool(False),\n collateHistograms = cms.untracked.bool(False),\n enableMultiThread = cms.untracked.bool(False),\n forceResetOnBeginLumi = cms.untracked.bool(False),\n referenceFileName = cms.untracked.string(''),\n verbose = cms.untracked.int32(0),\n verboseQT = cms.untracked.int32(0)\n)\n\n\nprocess.MessageLogger = cms.Service(\"MessageLogger\",\n FrameworkJobReport = cms.untracked.PSet(\n FwkJob = cms.untracked.PSet(\n limit = cms.untracked.int32(10000000),\n optionalPSet = cms.untracked.bool(True)\n ),\n default = cms.untracked.PSet(\n limit = cms.untracked.int32(0)\n ),\n optionalPSet = cms.untracked.bool(True)\n ),\n categories = cms.untracked.vstring('FwkJob', \n 'FwkReport', \n 'FwkSummary', \n 'Root_NoDictionary'),\n cerr = cms.untracked.PSet(\n FwkJob = cms.untracked.PSet(\n limit = cms.untracked.int32(0),\n optionalPSet = cms.untracked.bool(True)\n ),\n FwkReport = cms.untracked.PSet(\n limit = cms.untracked.int32(10000000),\n optionalPSet = cms.untracked.bool(True),\n reportEvery = cms.untracked.int32(1000)\n ),\n FwkSummary = cms.untracked.PSet(\n limit = cms.untracked.int32(10000000),\n optionalPSet = cms.untracked.bool(True),\n reportEvery = cms.untracked.int32(1)\n ),\n INFO = cms.untracked.PSet(\n limit = cms.untracked.int32(0)\n ),\n Root_NoDictionary = cms.untracked.PSet(\n limit = cms.untracked.int32(0),\n optionalPSet = cms.untracked.bool(True)\n ),\n default = cms.untracked.PSet(\n limit = cms.untracked.int32(10000000)\n ),\n noTimeStamps = cms.untracked.bool(False),\n optionalPSet = cms.untracked.bool(True),\n threshold = cms.untracked.string('')\n ),\n cerr_stats = cms.untracked.PSet(\n optionalPSet = cms.untracked.bool(True),\n output = cms.untracked.string('cerr'),\n threshold = cms.untracked.string('WARNING')\n ),\n cout = cms.untracked.PSet(\n placeholder = cms.untracked.bool(True)\n ),\n debugModules = cms.untracked.vstring(),\n debugs = cms.untracked.PSet(\n placeholder = cms.untracked.bool(True)\n ),\n default = cms.untracked.PSet(\n\n ),\n destinations = cms.untracked.vstring('warnings', \n 'errors', \n 'infos', \n 'debugs', \n 'cout', \n 'cerr'),\n errors = cms.untracked.PSet(\n placeholder = cms.untracked.bool(True)\n ),\n fwkJobReports = cms.untracked.vstring('FrameworkJobReport'),\n infos = cms.untracked.PSet(\n Root_NoDictionary = cms.untracked.PSet(\n limit = cms.untracked.int32(0),\n optionalPSet = cms.untracked.bool(True)\n ),\n optionalPSet = cms.untracked.bool(True),\n placeholder = cms.untracked.bool(True)\n ),\n statistics = cms.untracked.vstring('cerr_stats'),\n suppressDebug = cms.untracked.vstring(),\n suppressInfo = cms.untracked.vstring(),\n suppressWarning = cms.untracked.vstring(),\n warnings = cms.untracked.PSet(\n placeholder = cms.untracked.bool(True)\n )\n)\n\n\nprocess.RandomNumberGeneratorService = cms.Service(\"RandomNumberGeneratorService\",\n LHCTransport = cms.PSet(\n engineName = cms.untracked.string('TRandom3'),\n initialSeed = cms.untracked.uint32(87654321)\n ),\n MuonSimHits = cms.PSet(\n engineName = cms.untracked.string('TRandom3'),\n initialSeed = cms.untracked.uint32(987346)\n ),\n VtxSmeared = cms.PSet(\n engineName = cms.untracked.string('HepJamesRandom'),\n initialSeed = cms.untracked.uint32(98765432)\n ),\n ecalPreshowerRecHit = cms.PSet(\n engineName = cms.untracked.string('TRandom3'),\n initialSeed = cms.untracked.uint32(6541321)\n ),\n ecalRecHit = cms.PSet(\n engineName = cms.untracked.string('TRandom3'),\n initialSeed = cms.untracked.uint32(654321)\n ),\n externalLHEProducer = cms.PSet(\n engineName = cms.untracked.string('HepJamesRandom'),\n initialSeed = cms.untracked.uint32(234567)\n ),\n famosPileUp = cms.PSet(\n engineName = cms.untracked.string('TRandom3'),\n initialSeed = cms.untracked.uint32(918273)\n ),\n famosSimHits = cms.PSet(\n engineName = cms.untracked.string('TRandom3'),\n initialSeed = cms.untracked.uint32(13579)\n ),\n g4SimHits = cms.PSet(\n engineName = cms.untracked.string('HepJamesRandom'),\n initialSeed = cms.untracked.uint32(11)\n ),\n generator = cms.PSet(\n engineName = cms.untracked.string('HepJamesRandom'),\n initialSeed = cms.untracked.uint32(123456789)\n ),\n hbhereco = cms.PSet(\n engineName = cms.untracked.string('TRandom3'),\n initialSeed = cms.untracked.uint32(541321)\n ),\n hfreco = cms.PSet(\n engineName = cms.untracked.string('TRandom3'),\n initialSeed = cms.untracked.uint32(541321)\n ),\n hiSignal = cms.PSet(\n engineName = cms.untracked.string('HepJamesRandom'),\n initialSeed = cms.untracked.uint32(123456789)\n ),\n hiSignalG4SimHits = cms.PSet(\n engineName = cms.untracked.string('HepJamesRandom'),\n initialSeed = cms.untracked.uint32(11)\n ),\n hiSignalLHCTransport = cms.PSet(\n engineName = cms.untracked.string('TRandom3'),\n initialSeed = cms.untracked.uint32(88776655)\n ),\n horeco = cms.PSet(\n engineName = cms.untracked.string('TRandom3'),\n initialSeed = cms.untracked.uint32(541321)\n ),\n l1ParamMuons = cms.PSet(\n engineName = cms.untracked.string('TRandom3'),\n initialSeed = cms.untracked.uint32(6453209)\n ),\n mix = cms.PSet(\n engineName = cms.untracked.string('HepJamesRandom'),\n initialSeed = cms.untracked.uint32(12345)\n ),\n mixData = cms.PSet(\n engineName = cms.untracked.string('HepJamesRandom'),\n initialSeed = cms.untracked.uint32(12345)\n ),\n mixGenPU = cms.PSet(\n engineName = cms.untracked.string('TRandom3'),\n initialSeed = cms.untracked.uint32(918273)\n ),\n mixRecoTracks = cms.PSet(\n engineName = cms.untracked.string('TRandom3'),\n initialSeed = cms.untracked.uint32(918273)\n ),\n mixSimCaloHits = cms.PSet(\n engineName = cms.untracked.string('TRandom3'),\n initialSeed = cms.untracked.uint32(918273)\n ),\n paramMuons = cms.PSet(\n engineName = cms.untracked.string('TRandom3'),\n initialSeed = cms.untracked.uint32(54525)\n ),\n saveFileName = cms.untracked.string(''),\n siTrackerGaussianSmearingRecHits = cms.PSet(\n engineName = cms.untracked.string('TRandom3'),\n initialSeed = cms.untracked.uint32(24680)\n ),\n simBeamSpotFilter = cms.PSet(\n engineName = cms.untracked.string('HepJamesRandom'),\n initialSeed = cms.untracked.uint32(87654321)\n ),\n simMuonCSCDigis = cms.PSet(\n engineName = cms.untracked.string('HepJamesRandom'),\n initialSeed = cms.untracked.uint32(11223344)\n ),\n simMuonDTDigis = cms.PSet(\n engineName = cms.untracked.string('HepJamesRandom'),\n initialSeed = cms.untracked.uint32(1234567)\n ),\n simMuonRPCDigis = cms.PSet(\n engineName = cms.untracked.string('HepJamesRandom'),\n initialSeed = cms.untracked.uint32(1234567)\n ),\n simSiStripDigiSimLink = cms.PSet(\n engineName = cms.untracked.string('HepJamesRandom'),\n initialSeed = cms.untracked.uint32(1234567)\n )\n)\n\n\nprocess.TFileService = cms.Service(\"TFileService\",\n fileName = cms.string('histo.root')\n)\n\n\nprocess.CSCGeometryESModule = cms.ESProducer(\"CSCGeometryESModule\",\n alignmentsLabel = cms.string(''),\n appendToDataLabel = cms.string(''),\n applyAlignment = cms.bool(True),\n debugV = cms.untracked.bool(False),\n useCentreTIOffsets = cms.bool(False),\n useDDD = cms.bool(False),\n useGangedStripsInME1a = cms.bool(True),\n useOnlyWiresInME1a = cms.bool(False),\n useRealWireGeometry = cms.bool(True)\n)\n\n\nprocess.CaloGeometryBuilder = cms.ESProducer(\"CaloGeometryBuilder\",\n SelectedCalos = cms.vstring('HCAL', \n 'ZDC', \n 'CASTOR', \n 'EcalBarrel', \n 'EcalEndcap', \n 'EcalPreshower', \n 'TOWER')\n)\n\n\nprocess.CaloTopologyBuilder = cms.ESProducer(\"CaloTopologyBuilder\")\n\n\nprocess.CaloTowerGeometryFromDBEP = cms.ESProducer(\"CaloTowerGeometryFromDBEP\",\n applyAlignment = cms.bool(False),\n hcalTopologyConstants = cms.PSet(\n maxDepthHB = cms.int32(2),\n maxDepthHE = cms.int32(3),\n mode = cms.string('HcalTopologyMode::LHC')\n )\n)\n\n\nprocess.CaloTowerTopologyEP = cms.ESProducer(\"CaloTowerTopologyEP\")\n\n\nprocess.CastorDbProducer = cms.ESProducer(\"CastorDbProducer\")\n\n\nprocess.CastorGeometryFromDBEP = cms.ESProducer(\"CastorGeometryFromDBEP\",\n applyAlignment = cms.bool(False)\n)\n\n\nprocess.DTGeometryESModule = cms.ESProducer(\"DTGeometryESModule\",\n alignmentsLabel = cms.string(''),\n appendToDataLabel = cms.string(''),\n applyAlignment = cms.bool(True),\n fromDDD = cms.bool(False)\n)\n\n\nprocess.EcalBarrelGeometryFromDBEP = cms.ESProducer(\"EcalBarrelGeometryFromDBEP\",\n applyAlignment = cms.bool(True)\n)\n\n\nprocess.EcalElectronicsMappingBuilder = cms.ESProducer(\"EcalElectronicsMappingBuilder\")\n\n\nprocess.EcalEndcapGeometryFromDBEP = cms.ESProducer(\"EcalEndcapGeometryFromDBEP\",\n applyAlignment = cms.bool(True)\n)\n\n\nprocess.EcalLaserCorrectionService = cms.ESProducer(\"EcalLaserCorrectionService\")\n\n\nprocess.EcalPreshowerGeometryFromDBEP = cms.ESProducer(\"EcalPreshowerGeometryFromDBEP\",\n applyAlignment = cms.bool(True)\n)\n\n\nprocess.EcalTrigTowerConstituentsMapBuilder = cms.ESProducer(\"EcalTrigTowerConstituentsMapBuilder\",\n MapFile = cms.untracked.string('Geometry/EcalMapping/data/EndCap_TTMap.txt')\n)\n\n\nprocess.GlobalTrackingGeometryESProducer = cms.ESProducer(\"GlobalTrackingGeometryESProducer\")\n\n\nprocess.HcalAlignmentEP = cms.ESProducer(\"HcalAlignmentEP\")\n\n\nprocess.HcalGeometryFromDBEP = cms.ESProducer(\"HcalGeometryFromDBEP\",\n applyAlignment = cms.bool(True),\n hcalTopologyConstants = cms.PSet(\n maxDepthHB = cms.int32(2),\n maxDepthHE = cms.int32(3),\n mode = cms.string('HcalTopologyMode::LHC')\n )\n)\n\n\nprocess.MuonDetLayerGeometryESProducer = cms.ESProducer(\"MuonDetLayerGeometryESProducer\")\n\n\nprocess.MuonNumberingInitialization = cms.ESProducer(\"MuonNumberingInitialization\")\n\n\nprocess.ParabolicParametrizedMagneticFieldProducer = cms.ESProducer(\"AutoParametrizedMagneticFieldProducer\",\n label = cms.untracked.string('ParabolicMf'),\n valueOverride = cms.int32(18268),\n version = cms.string('Parabolic')\n)\n\n\nprocess.RPCGeometryESModule = cms.ESProducer(\"RPCGeometryESModule\",\n compatibiltyWith11 = cms.untracked.bool(True),\n useDDD = cms.untracked.bool(False)\n)\n\n\nprocess.SiStripRecHitMatcherESProducer = cms.ESProducer(\"SiStripRecHitMatcherESProducer\",\n ComponentName = cms.string('StandardMatcher'),\n NSigmaInside = cms.double(3.0),\n PreFilter = cms.bool(False)\n)\n\n\nprocess.StripCPEfromTrackAngleESProducer = cms.ESProducer(\"StripCPEESProducer\",\n ComponentName = cms.string('StripCPEfromTrackAngle'),\n ComponentType = cms.string('StripCPEfromTrackAngle'),\n parameters = cms.PSet(\n mLC_P0 = cms.double(-0.326),\n mLC_P1 = cms.double(0.618),\n mLC_P2 = cms.double(0.3),\n mTEC_P0 = cms.double(-1.885),\n mTEC_P1 = cms.double(0.471),\n mTIB_P0 = cms.double(-0.742),\n mTIB_P1 = cms.double(0.202),\n mTID_P0 = cms.double(-1.427),\n mTID_P1 = cms.double(0.433),\n mTOB_P0 = cms.double(-1.026),\n mTOB_P1 = cms.double(0.253),\n maxChgOneMIP = cms.double(6000.0),\n useLegacyError = cms.bool(False)\n )\n)\n\n\nprocess.TrackerRecoGeometryESProducer = cms.ESProducer(\"TrackerRecoGeometryESProducer\")\n\n\nprocess.TransientTrackBuilderESProducer = cms.ESProducer(\"TransientTrackBuilderESProducer\",\n ComponentName = cms.string('TransientTrackBuilder')\n)\n\n\nprocess.VolumeBasedMagneticFieldESProducer = cms.ESProducer(\"VolumeBasedMagneticFieldESProducerFromDB\",\n debugBuilder = cms.untracked.bool(False),\n label = cms.untracked.string(''),\n valueOverride = cms.int32(18268)\n)\n\n\nprocess.XMLFromDBSource = cms.ESProducer(\"XMLIdealGeometryESProducer\",\n label = cms.string('Extended'),\n rootDDName = cms.string('cms:OCMS')\n)\n\n\nprocess.ZdcGeometryFromDBEP = cms.ESProducer(\"ZdcGeometryFromDBEP\",\n applyAlignment = cms.bool(False)\n)\n\n\nprocess.ak10PFCHSL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('AK10PFchs'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n)\n\n\nprocess.ak10PFCHSL1FastjetL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak10PFCHSL1Fastjet', \n 'ak10PFCHSL2Relative', \n 'ak10PFCHSL3Absolute', \n 'ak10PFCHSResidual')\n)\n\n\nprocess.ak10PFCHSL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak10PFCHSL1Offset', \n 'ak10PFCHSL2Relative', \n 'ak10PFCHSL3Absolute', \n 'ak10PFCHSResidual')\n)\n\n\nprocess.ak10PFCHSL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('AK10PFchs'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ak10PFCHSL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak10PFCHSL2Relative', \n 'ak10PFCHSL3Absolute')\n)\n\n\nprocess.ak10PFCHSL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak10PFCHSL2Relative', \n 'ak10PFCHSL3Absolute', \n 'ak10PFCHSResidual')\n)\n\n\nprocess.ak10PFCHSL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK10PFchs'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ak10PFCHSL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK10PFchs'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ak10PFCHSResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK10PFchs'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.ak10PFL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('AK10PF'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n)\n\n\nprocess.ak10PFL1FastjetL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak10PFL1Fastjet', \n 'ak10PFL2Relative', \n 'ak10PFL3Absolute', \n 'ak10PFResidual')\n)\n\n\nprocess.ak10PFL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak10PFL1Offset', \n 'ak10PFL2Relative', \n 'ak10PFL3Absolute', \n 'ak10PFResidual')\n)\n\n\nprocess.ak10PFL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('AK10PF'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ak10PFL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak10PFL2Relative', \n 'ak10PFL3Absolute')\n)\n\n\nprocess.ak10PFL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak10PFL2Relative', \n 'ak10PFL3Absolute', \n 'ak10PFResidual')\n)\n\n\nprocess.ak10PFL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK10PF'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ak10PFL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK10PF'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ak10PFResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK10PF'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.ak1PFCHSL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('AK1PFchs'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n)\n\n\nprocess.ak1PFCHSL1FastjetL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak1PFCHSL1Fastjet', \n 'ak1PFCHSL2Relative', \n 'ak1PFCHSL3Absolute', \n 'ak1PFCHSResidual')\n)\n\n\nprocess.ak1PFCHSL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak1PFCHSL1Offset', \n 'ak1PFCHSL2Relative', \n 'ak1PFCHSL3Absolute', \n 'ak1PFCHSResidual')\n)\n\n\nprocess.ak1PFCHSL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('AK1PFchs'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ak1PFCHSL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak1PFCHSL2Relative', \n 'ak1PFCHSL3Absolute')\n)\n\n\nprocess.ak1PFCHSL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak1PFCHSL2Relative', \n 'ak1PFCHSL3Absolute', \n 'ak1PFCHSResidual')\n)\n\n\nprocess.ak1PFCHSL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK1PFchs'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ak1PFCHSL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK1PFchs'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ak1PFCHSResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK1PFchs'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.ak1PFL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('AK1PF'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n)\n\n\nprocess.ak1PFL1FastjetL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak1PFL1Fastjet', \n 'ak1PFL2Relative', \n 'ak1PFL3Absolute', \n 'ak1PFResidual')\n)\n\n\nprocess.ak1PFL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak1PFL1Offset', \n 'ak1PFL2Relative', \n 'ak1PFL3Absolute', \n 'ak1PFResidual')\n)\n\n\nprocess.ak1PFL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('AK1PF'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ak1PFL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak1PFL2Relative', \n 'ak1PFL3Absolute')\n)\n\n\nprocess.ak1PFL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak1PFL2Relative', \n 'ak1PFL3Absolute', \n 'ak1PFResidual')\n)\n\n\nprocess.ak1PFL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK1PF'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ak1PFL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK1PF'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ak1PFResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK1PF'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.ak2PFCHSL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('AK2PFchs'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n)\n\n\nprocess.ak2PFCHSL1FastjetL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak2PFCHSL1Fastjet', \n 'ak2PFCHSL2Relative', \n 'ak2PFCHSL3Absolute', \n 'ak2PFCHSResidual')\n)\n\n\nprocess.ak2PFCHSL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak2PFCHSL1Offset', \n 'ak2PFCHSL2Relative', \n 'ak2PFCHSL3Absolute', \n 'ak2PFCHSResidual')\n)\n\n\nprocess.ak2PFCHSL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('AK2PFchs'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ak2PFCHSL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak2PFCHSL2Relative', \n 'ak2PFCHSL3Absolute')\n)\n\n\nprocess.ak2PFCHSL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak2PFCHSL2Relative', \n 'ak2PFCHSL3Absolute', \n 'ak2PFCHSResidual')\n)\n\n\nprocess.ak2PFCHSL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK2PFchs'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ak2PFCHSL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK2PFchs'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ak2PFCHSResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK2PFchs'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.ak2PFL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('AK2PF'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n)\n\n\nprocess.ak2PFL1FastjetL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak2PFL1Fastjet', \n 'ak2PFL2Relative', \n 'ak2PFL3Absolute', \n 'ak2PFResidual')\n)\n\n\nprocess.ak2PFL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak2PFL1Offset', \n 'ak2PFL2Relative', \n 'ak2PFL3Absolute', \n 'ak2PFResidual')\n)\n\n\nprocess.ak2PFL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('AK2PF'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ak2PFL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak2PFL2Relative', \n 'ak2PFL3Absolute')\n)\n\n\nprocess.ak2PFL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak2PFL2Relative', \n 'ak2PFL3Absolute', \n 'ak2PFResidual')\n)\n\n\nprocess.ak2PFL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK2PF'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ak2PFL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK2PF'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ak2PFResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK2PF'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.ak3PFCHSL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('AK3PFchs'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n)\n\n\nprocess.ak3PFCHSL1FastjetL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak3PFCHSL1Fastjet', \n 'ak3PFCHSL2Relative', \n 'ak3PFCHSL3Absolute', \n 'ak3PFCHSResidual')\n)\n\n\nprocess.ak3PFCHSL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak3PFCHSL1Offset', \n 'ak3PFCHSL2Relative', \n 'ak3PFCHSL3Absolute', \n 'ak3PFCHSResidual')\n)\n\n\nprocess.ak3PFCHSL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('AK3PFchs'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ak3PFCHSL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak3PFCHSL2Relative', \n 'ak3PFCHSL3Absolute')\n)\n\n\nprocess.ak3PFCHSL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak3PFCHSL2Relative', \n 'ak3PFCHSL3Absolute', \n 'ak3PFCHSResidual')\n)\n\n\nprocess.ak3PFCHSL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK3PFchs'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ak3PFCHSL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK3PFchs'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ak3PFCHSResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK3PFchs'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.ak3PFL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('AK3PF'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n)\n\n\nprocess.ak3PFL1FastjetL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak3PFL1Fastjet', \n 'ak3PFL2Relative', \n 'ak3PFL3Absolute', \n 'ak3PFResidual')\n)\n\n\nprocess.ak3PFL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak3PFL1Offset', \n 'ak3PFL2Relative', \n 'ak3PFL3Absolute', \n 'ak3PFResidual')\n)\n\n\nprocess.ak3PFL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('AK3PF'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ak3PFL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak3PFL2Relative', \n 'ak3PFL3Absolute')\n)\n\n\nprocess.ak3PFL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak3PFL2Relative', \n 'ak3PFL3Absolute', \n 'ak3PFResidual')\n)\n\n\nprocess.ak3PFL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK3PF'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ak3PFL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK3PF'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ak3PFResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK3PF'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.ak4CaloL1FastL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4CaloL1Fastjet', \n 'ak4CaloL2Relative', \n 'ak4CaloL3Absolute')\n)\n\n\nprocess.ak4CaloL1FastL2L3L6 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4CaloL1Fastjet', \n 'ak4CaloL2Relative', \n 'ak4CaloL3Absolute', \n 'ak4CaloL6SLB')\n)\n\n\nprocess.ak4CaloL1FastL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4CaloL1Fastjet', \n 'ak4CaloL2Relative', \n 'ak4CaloL3Absolute', \n 'ak4CaloResidual')\n)\n\n\nprocess.ak4CaloL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('AK5Calo'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAllCalo\")\n)\n\n\nprocess.ak4CaloL1L2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4CaloL1Offset', \n 'ak4CaloL2Relative', \n 'ak4CaloL3Absolute')\n)\n\n\nprocess.ak4CaloL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4CaloL1Offset', \n 'ak4CaloL2Relative', \n 'ak4CaloL3Absolute', \n 'ak4CaloResidual')\n)\n\n\nprocess.ak4CaloL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('AK5Calo'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ak4CaloL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4CaloL2Relative', \n 'ak4CaloL3Absolute')\n)\n\n\nprocess.ak4CaloL2L3L6 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4CaloL2Relative', \n 'ak4CaloL3Absolute', \n 'ak4CaloL6SLB')\n)\n\n\nprocess.ak4CaloL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4CaloL2Relative', \n 'ak4CaloL3Absolute', \n 'ak4CaloResidual')\n)\n\n\nprocess.ak4CaloL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK5Calo'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ak4CaloL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK5Calo'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ak4CaloL6SLB = cms.ESProducer(\"L6SLBCorrectionESProducer\",\n addMuonToJet = cms.bool(True),\n algorithm = cms.string(''),\n level = cms.string('L6SLB'),\n srcBTagInfoElectron = cms.InputTag(\"ak4CaloJetsSoftElectronTagInfos\"),\n srcBTagInfoMuon = cms.InputTag(\"ak4CaloJetsSoftMuonTagInfos\")\n)\n\n\nprocess.ak4CaloResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK5Calo'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.ak4JPTL1FastL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4JPTL1Fastjet', \n 'ak4JPTL2Relative', \n 'ak4JPTL3Absolute')\n)\n\n\nprocess.ak4JPTL1FastL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4JPTL1Fastjet', \n 'ak4JPTL2Relative', \n 'ak4JPTL3Absolute', \n 'ak4JPTResidual')\n)\n\n\nprocess.ak4JPTL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('AK5Calo'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAllCalo\")\n)\n\n\nprocess.ak4JPTL1L2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4L1JPTOffset', \n 'ak4JPTL2Relative', \n 'ak4JPTL3Absolute')\n)\n\n\nprocess.ak4JPTL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4L1JPTOffset', \n 'ak4JPTL2Relative', \n 'ak4JPTL3Absolute', \n 'ak4JPTResidual')\n)\n\n\nprocess.ak4JPTL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('AK5JPT'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ak4JPTL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4L1JPTOffset', \n 'ak4JPTL2Relative', \n 'ak4JPTL3Absolute')\n)\n\n\nprocess.ak4JPTL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4L1JPTOffset', \n 'ak4JPTL2Relative', \n 'ak4JPTL3Absolute', \n 'ak4JPTResidual')\n)\n\n\nprocess.ak4JPTL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK5JPT'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ak4JPTL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK5JPT'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ak4JPTResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK5JPT'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.ak4L1JPTOffset = cms.ESProducer(\"L1JPTOffsetCorrectionESProducer\",\n algorithm = cms.string('AK5JPT'),\n level = cms.string('L1JPTOffset'),\n offsetService = cms.string('ak4CaloL1Offset')\n)\n\n\nprocess.ak4PFCHSL1FastL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4PFCHSL1Fastjet', \n 'ak4PFCHSL2Relative', \n 'ak4PFCHSL3Absolute')\n)\n\n\nprocess.ak4PFCHSL1FastL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4PFCHSL1Fastjet', \n 'ak4PFCHSL2Relative', \n 'ak4PFCHSL3Absolute', \n 'ak4PFCHSResidual')\n)\n\n\nprocess.ak4PFCHSL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('AK4PFchs'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n)\n\n\nprocess.ak4PFCHSL1L2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4PFCHSL1Offset', \n 'ak4PFCHSL2Relative', \n 'ak4PFCHSL3Absolute')\n)\n\n\nprocess.ak4PFCHSL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4PFCHSL1Offset', \n 'ak4PFCHSL2Relative', \n 'ak4PFCHSL3Absolute', \n 'ak4PFCHSResidual')\n)\n\n\nprocess.ak4PFCHSL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('AK4PFchs'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ak4PFCHSL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4PFCHSL2Relative', \n 'ak4PFCHSL3Absolute')\n)\n\n\nprocess.ak4PFCHSL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4PFCHSL2Relative', \n 'ak4PFCHSL3Absolute', \n 'ak4PFCHSResidual')\n)\n\n\nprocess.ak4PFCHSL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK4PFchs'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ak4PFCHSL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK4PFchs'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ak4PFCHSResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK4PFchs'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.ak4PFL1FastL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4PFL1Fastjet', \n 'ak4PFL2Relative', \n 'ak4PFL3Absolute')\n)\n\n\nprocess.ak4PFL1FastL2L3L6 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4PFL1Fastjet', \n 'ak4PFL2Relative', \n 'ak4PFL3Absolute', \n 'ak4PFL6SLB')\n)\n\n\nprocess.ak4PFL1FastL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4PFL1Fastjet', \n 'ak4PFL2Relative', \n 'ak4PFL3Absolute', \n 'ak4PFResidual')\n)\n\n\nprocess.ak4PFL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('AK4PF'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n)\n\n\nprocess.ak4PFL1L2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4PFL1Offset', \n 'ak4PFL2Relative', \n 'ak4PFL3Absolute')\n)\n\n\nprocess.ak4PFL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4PFL1Offset', \n 'ak4PFL2Relative', \n 'ak4PFL3Absolute', \n 'ak4PFResidual')\n)\n\n\nprocess.ak4PFL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('AK4PF'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ak4PFL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4PFL2Relative', \n 'ak4PFL3Absolute')\n)\n\n\nprocess.ak4PFL2L3L6 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4PFL2Relative', \n 'ak4PFL3Absolute', \n 'ak4PFL6SLB')\n)\n\n\nprocess.ak4PFL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4PFL2Relative', \n 'ak4PFL3Absolute', \n 'ak4PFResidual')\n)\n\n\nprocess.ak4PFL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK4PF'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ak4PFL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK4PF'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ak4PFL6SLB = cms.ESProducer(\"L6SLBCorrectionESProducer\",\n addMuonToJet = cms.bool(False),\n algorithm = cms.string(''),\n level = cms.string('L6SLB'),\n srcBTagInfoElectron = cms.InputTag(\"ak4PFJetsSoftElectronTagInfos\"),\n srcBTagInfoMuon = cms.InputTag(\"ak4PFJetsSoftMuonTagInfos\")\n)\n\n\nprocess.ak4PFResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK4PF'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.ak4TrackL1FastL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4CaloL1Fastjet', \n 'ak4TrackL2Relative', \n 'ak4TrackL3Absolute')\n)\n\n\nprocess.ak4TrackL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4TrackL2Relative', \n 'ak4TrackL3Absolute')\n)\n\n\nprocess.ak4TrackL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK5TRK'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ak4TrackL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK5TRK'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ak5PFCHSL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('AK5PFchs'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n)\n\n\nprocess.ak5PFCHSL1FastjetL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak5PFCHSL1Fastjet', \n 'ak5PFCHSL2Relative', \n 'ak5PFCHSL3Absolute', \n 'ak5PFCHSResidual')\n)\n\n\nprocess.ak5PFCHSL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak5PFCHSL1Offset', \n 'ak5PFCHSL2Relative', \n 'ak5PFCHSL3Absolute', \n 'ak5PFCHSResidual')\n)\n\n\nprocess.ak5PFCHSL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('AK5PFchs'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ak5PFCHSL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak5PFCHSL2Relative', \n 'ak5PFCHSL3Absolute')\n)\n\n\nprocess.ak5PFCHSL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak5PFCHSL2Relative', \n 'ak5PFCHSL3Absolute', \n 'ak5PFCHSResidual')\n)\n\n\nprocess.ak5PFCHSL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK5PFchs'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ak5PFCHSL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK5PFchs'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ak5PFCHSResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK5PFchs'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.ak5PFL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('AK5PF'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n)\n\n\nprocess.ak5PFL1FastjetL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak5PFL1Fastjet', \n 'ak5PFL2Relative', \n 'ak5PFL3Absolute', \n 'ak5PFResidual')\n)\n\n\nprocess.ak5PFL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak5PFL1Offset', \n 'ak5PFL2Relative', \n 'ak5PFL3Absolute', \n 'ak5PFResidual')\n)\n\n\nprocess.ak5PFL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('AK5PF'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ak5PFL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak5PFL2Relative', \n 'ak5PFL3Absolute')\n)\n\n\nprocess.ak5PFL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak5PFL2Relative', \n 'ak5PFL3Absolute', \n 'ak5PFResidual')\n)\n\n\nprocess.ak5PFL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK5PF'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ak5PFL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK5PF'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ak5PFResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK5PF'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.ak6PFCHSL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('AK6PFchs'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n)\n\n\nprocess.ak6PFCHSL1FastjetL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak6PFCHSL1Fastjet', \n 'ak6PFCHSL2Relative', \n 'ak6PFCHSL3Absolute', \n 'ak6PFCHSResidual')\n)\n\n\nprocess.ak6PFCHSL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak6PFCHSL1Offset', \n 'ak6PFCHSL2Relative', \n 'ak6PFCHSL3Absolute', \n 'ak6PFCHSResidual')\n)\n\n\nprocess.ak6PFCHSL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('AK6PFchs'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ak6PFCHSL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak6PFCHSL2Relative', \n 'ak6PFCHSL3Absolute')\n)\n\n\nprocess.ak6PFCHSL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak6PFCHSL2Relative', \n 'ak6PFCHSL3Absolute', \n 'ak6PFCHSResidual')\n)\n\n\nprocess.ak6PFCHSL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK6PFchs'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ak6PFCHSL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK6PFchs'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ak6PFCHSResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK6PFchs'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.ak6PFL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('AK6PF'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n)\n\n\nprocess.ak6PFL1FastjetL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak6PFL1Fastjet', \n 'ak6PFL2Relative', \n 'ak6PFL3Absolute', \n 'ak6PFResidual')\n)\n\n\nprocess.ak6PFL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak6PFL1Offset', \n 'ak6PFL2Relative', \n 'ak6PFL3Absolute', \n 'ak6PFResidual')\n)\n\n\nprocess.ak6PFL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('AK6PF'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ak6PFL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak6PFL2Relative', \n 'ak6PFL3Absolute')\n)\n\n\nprocess.ak6PFL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak6PFL2Relative', \n 'ak6PFL3Absolute', \n 'ak6PFResidual')\n)\n\n\nprocess.ak6PFL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK6PF'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ak6PFL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK6PF'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ak6PFResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK6PF'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.ak7CaloL1FastL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4CaloL1Fastjet', \n 'ak7CaloL2Relative', \n 'ak7CaloL3Absolute')\n)\n\n\nprocess.ak7CaloL1FastL2L3L6 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak7CaloL1Offset', \n 'ak7CaloL2Relative', \n 'ak7CaloL3Absolute', \n 'ak7CaloL6SLB')\n)\n\n\nprocess.ak7CaloL1FastL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak7CaloL1Fastjet', \n 'ak7CaloL2Relative', \n 'ak7CaloL3Absolute', \n 'ak7CaloResidual')\n)\n\n\nprocess.ak7CaloL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('AK7Calo'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAllCalo\")\n)\n\n\nprocess.ak7CaloL1L2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak7CaloL1Offset', \n 'ak7CaloL2Relative', \n 'ak7CaloL3Absolute')\n)\n\n\nprocess.ak7CaloL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak7CaloL1Offset', \n 'ak7CaloL2Relative', \n 'ak7CaloL3Absolute', \n 'ak7CaloResidual')\n)\n\n\nprocess.ak7CaloL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('AK7Calo'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ak7CaloL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak7CaloL2Relative', \n 'ak7CaloL3Absolute')\n)\n\n\nprocess.ak7CaloL2L3L6 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak7CaloL2Relative', \n 'ak7CaloL3Absolute', \n 'ak7CaloL6SLB')\n)\n\n\nprocess.ak7CaloL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak7CaloL2Relative', \n 'ak7CaloL3Absolute', \n 'ak7CaloResidual')\n)\n\n\nprocess.ak7CaloL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK7Calo'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ak7CaloL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK7Calo'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ak7CaloL6SLB = cms.ESProducer(\"L6SLBCorrectionESProducer\",\n addMuonToJet = cms.bool(True),\n algorithm = cms.string(''),\n level = cms.string('L6SLB'),\n srcBTagInfoElectron = cms.InputTag(\"ak7CaloJetsSoftElectronTagInfos\"),\n srcBTagInfoMuon = cms.InputTag(\"ak7CaloJetsSoftMuonTagInfos\")\n)\n\n\nprocess.ak7CaloResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK7Calo'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.ak7JPTL1FastL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak7JPTL1Fastjet', \n 'ak7L1JPTOffset', \n 'ak7JPTL2Relative', \n 'ak7JPTL3Absolute', \n 'ak7JPTResidual')\n)\n\n\nprocess.ak7JPTL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('AK7JPT'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAllCalo\")\n)\n\n\nprocess.ak7JPTL1L2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak7JPTL1Offset', \n 'ak7L1JPTOffset', \n 'ak7JPTL2Relative', \n 'ak7JPTL3Absolute')\n)\n\n\nprocess.ak7JPTL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak7JPTL1Offset', \n 'ak7L1JPTOffset', \n 'ak7JPTL2Relative', \n 'ak7JPTL3Absolute', \n 'ak7JPTResidual')\n)\n\n\nprocess.ak7JPTL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('AK7JPT'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ak7JPTL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak7L1JPTOffset', \n 'ak7JPTL2Relative', \n 'ak7JPTL3Absolute')\n)\n\n\nprocess.ak7L1JPTOffset = cms.ESProducer(\"L1JPTOffsetCorrectionESProducer\",\n algorithm = cms.string('AK7JPT'),\n level = cms.string('L1JPTOffset'),\n offsetService = cms.string('ak4CaloL1Offset')\n)\n\n\nprocess.ak7PFCHSL1FastL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4PFCHSL1Fastjet', \n 'ak7PFCHSL2Relative', \n 'ak7PFCHSL3Absolute')\n)\n\n\nprocess.ak7PFCHSL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('AK7PFchs'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n)\n\n\nprocess.ak7PFCHSL1FastjetL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak7PFCHSL1Fastjet', \n 'ak7PFCHSL2Relative', \n 'ak7PFCHSL3Absolute', \n 'ak7PFCHSResidual')\n)\n\n\nprocess.ak7PFCHSL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak7PFCHSL1Offset', \n 'ak7PFCHSL2Relative', \n 'ak7PFCHSL3Absolute', \n 'ak7PFCHSResidual')\n)\n\n\nprocess.ak7PFCHSL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('AK7PFchs'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ak7PFCHSL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak7PFCHSL2Relative', \n 'ak7PFCHSL3Absolute')\n)\n\n\nprocess.ak7PFCHSL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak7PFCHSL2Relative', \n 'ak7PFCHSL3Absolute', \n 'ak7PFCHSResidual')\n)\n\n\nprocess.ak7PFCHSL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK7PFchs'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ak7PFCHSL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK7PFchs'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ak7PFCHSResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK7PFchs'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.ak7PFL1FastL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4PFL1Fastjet', \n 'ak7PFL2Relative', \n 'ak7PFL3Absolute')\n)\n\n\nprocess.ak7PFL1FastL2L3L6 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4PFL1Fastjet', \n 'ak7PFL2Relative', \n 'ak7PFL3Absolute', \n 'ak7PFL6SLB')\n)\n\n\nprocess.ak7PFL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('AK7PF'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n)\n\n\nprocess.ak7PFL1FastjetL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak7PFL1Fastjet', \n 'ak7PFL2Relative', \n 'ak7PFL3Absolute', \n 'ak7PFResidual')\n)\n\n\nprocess.ak7PFL1L2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak7PFL1Offset', \n 'ak7PFL2Relative', \n 'ak7PFL3Absolute')\n)\n\n\nprocess.ak7PFL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak7PFL1Offset', \n 'ak7PFL2Relative', \n 'ak7PFL3Absolute', \n 'ak7PFResidual')\n)\n\n\nprocess.ak7PFL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('AK7PF'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ak7PFL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak7PFL2Relative', \n 'ak7PFL3Absolute')\n)\n\n\nprocess.ak7PFL2L3L6 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak7PFL2Relative', \n 'ak7PFL3Absolute', \n 'ak7PFL6SLB')\n)\n\n\nprocess.ak7PFL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak7PFL2Relative', \n 'ak7PFL3Absolute', \n 'ak7PFResidual')\n)\n\n\nprocess.ak7PFL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK7PF'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ak7PFL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK7PF'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ak7PFL6SLB = cms.ESProducer(\"L6SLBCorrectionESProducer\",\n addMuonToJet = cms.bool(False),\n algorithm = cms.string(''),\n level = cms.string('L6SLB'),\n srcBTagInfoElectron = cms.InputTag(\"ak7PFJetsSoftElectronTagInfos\"),\n srcBTagInfoMuon = cms.InputTag(\"ak7PFJetsSoftMuonTagInfos\")\n)\n\n\nprocess.ak7PFResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK7PF'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.ak8PFCHSL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('AK8PFchs'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n)\n\n\nprocess.ak8PFCHSL1FastjetL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak8PFCHSL1Fastjet', \n 'ak8PFCHSL2Relative', \n 'ak8PFCHSL3Absolute', \n 'ak8PFCHSResidual')\n)\n\n\nprocess.ak8PFCHSL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak8PFCHSL1Offset', \n 'ak8PFCHSL2Relative', \n 'ak8PFCHSL3Absolute', \n 'ak8PFCHSResidual')\n)\n\n\nprocess.ak8PFCHSL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('AK8PFchs'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ak8PFCHSL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak8PFCHSL2Relative', \n 'ak8PFCHSL3Absolute')\n)\n\n\nprocess.ak8PFCHSL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak8PFCHSL2Relative', \n 'ak8PFCHSL3Absolute', \n 'ak8PFCHSResidual')\n)\n\n\nprocess.ak8PFCHSL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK8PFchs'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ak8PFCHSL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK8PFchs'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ak8PFCHSResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK8PFchs'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.ak8PFL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('AK8PF'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n)\n\n\nprocess.ak8PFL1FastjetL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak8PFL1Fastjet', \n 'ak8PFL2Relative', \n 'ak8PFL3Absolute', \n 'ak8PFResidual')\n)\n\n\nprocess.ak8PFL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak8PFL1Offset', \n 'ak8PFL2Relative', \n 'ak8PFL3Absolute', \n 'ak8PFResidual')\n)\n\n\nprocess.ak8PFL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('AK8PF'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ak8PFL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak8PFL2Relative', \n 'ak8PFL3Absolute')\n)\n\n\nprocess.ak8PFL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak8PFL2Relative', \n 'ak8PFL3Absolute', \n 'ak8PFResidual')\n)\n\n\nprocess.ak8PFL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK8PF'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ak8PFL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK8PF'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ak8PFResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK8PF'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.ak9PFCHSL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('AK9PFchs'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n)\n\n\nprocess.ak9PFCHSL1FastjetL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak9PFCHSL1Fastjet', \n 'ak9PFCHSL2Relative', \n 'ak9PFCHSL3Absolute', \n 'ak9PFCHSResidual')\n)\n\n\nprocess.ak9PFCHSL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak9PFCHSL1Offset', \n 'ak9PFCHSL2Relative', \n 'ak9PFCHSL3Absolute', \n 'ak9PFCHSResidual')\n)\n\n\nprocess.ak9PFCHSL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('AK9PFchs'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ak9PFCHSL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak9PFCHSL2Relative', \n 'ak9PFCHSL3Absolute')\n)\n\n\nprocess.ak9PFCHSL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak9PFCHSL2Relative', \n 'ak9PFCHSL3Absolute', \n 'ak9PFCHSResidual')\n)\n\n\nprocess.ak9PFCHSL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK9PFchs'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ak9PFCHSL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK9PFchs'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ak9PFCHSResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK9PFchs'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.ak9PFL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('AK9PF'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n)\n\n\nprocess.ak9PFL1FastjetL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak9PFL1Fastjet', \n 'ak9PFL2Relative', \n 'ak9PFL3Absolute', \n 'ak9PFResidual')\n)\n\n\nprocess.ak9PFL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak9PFL1Offset', \n 'ak9PFL2Relative', \n 'ak9PFL3Absolute', \n 'ak9PFResidual')\n)\n\n\nprocess.ak9PFL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('AK9PF'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ak9PFL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak9PFL2Relative', \n 'ak9PFL3Absolute')\n)\n\n\nprocess.ak9PFL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak9PFL2Relative', \n 'ak9PFL3Absolute', \n 'ak9PFResidual')\n)\n\n\nprocess.ak9PFL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK9PF'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ak9PFL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK9PF'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ak9PFResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('AK9PF'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.fakeForIdealAlignment = cms.ESProducer(\"FakeAlignmentProducer\",\n appendToDataLabel = cms.string('fakeForIdeal')\n)\n\n\nprocess.hcalDDDRecConstants = cms.ESProducer(\"HcalDDDRecConstantsESModule\",\n appendToDataLabel = cms.string('')\n)\n\n\nprocess.hcalDDDSimConstants = cms.ESProducer(\"HcalDDDSimConstantsESModule\",\n appendToDataLabel = cms.string('')\n)\n\n\nprocess.hcalTopologyIdeal = cms.ESProducer(\"HcalTopologyIdealEP\",\n Exclude = cms.untracked.string(''),\n appendToDataLabel = cms.string(''),\n hcalTopologyConstants = cms.PSet(\n maxDepthHB = cms.int32(2),\n maxDepthHE = cms.int32(3),\n mode = cms.string('HcalTopologyMode::LHC')\n )\n)\n\n\nprocess.hcal_db_producer = cms.ESProducer(\"HcalDbProducer\",\n dump = cms.untracked.vstring(''),\n file = cms.untracked.string('')\n)\n\n\nprocess.ic5CaloL1FastL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4CaloL1Fastjet', \n 'ic5CaloL2Relative', \n 'ic5CaloL3Absolute')\n)\n\n\nprocess.ic5CaloL1FastL2L3L6 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ic5CaloL1Offset', \n 'ic5CaloL2Relative', \n 'ic5CaloL3Absolute', \n 'ic5CaloL6SLB')\n)\n\n\nprocess.ic5CaloL1FastL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ic5CaloL1Fastjet', \n 'ic5CaloL2Relative', \n 'ic5CaloL3Absolute', \n 'ic5CaloResidual')\n)\n\n\nprocess.ic5CaloL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('IC5Calo'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAllCalo\")\n)\n\n\nprocess.ic5CaloL1L2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ic5CaloL1Offset', \n 'ic5CaloL2Relative', \n 'ic5CaloL3Absolute')\n)\n\n\nprocess.ic5CaloL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ic5CaloL1Offset', \n 'ic5CaloL2Relative', \n 'ic5CaloL3Absolute', \n 'ic5CaloResidual')\n)\n\n\nprocess.ic5CaloL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('IC5Calo'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ic5CaloL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ic5CaloL2Relative', \n 'ic5CaloL3Absolute')\n)\n\n\nprocess.ic5CaloL2L3L6 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ic5CaloL2Relative', \n 'ic5CaloL3Absolute', \n 'ic5CaloL6SLB')\n)\n\n\nprocess.ic5CaloL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ic5CaloL2Relative', \n 'ic5CaloL3Absolute', \n 'ic5CaloResidual')\n)\n\n\nprocess.ic5CaloL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('IC5Calo'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ic5CaloL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('IC5Calo'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ic5CaloL6SLB = cms.ESProducer(\"L6SLBCorrectionESProducer\",\n addMuonToJet = cms.bool(True),\n algorithm = cms.string(''),\n level = cms.string('L6SLB'),\n srcBTagInfoElectron = cms.InputTag(\"ic5CaloJetsSoftElectronTagInfos\"),\n srcBTagInfoMuon = cms.InputTag(\"ic5CaloJetsSoftMuonTagInfos\")\n)\n\n\nprocess.ic5CaloResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('IC5Calo'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.ic5PFL1FastL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4PFL1Fastjet', \n 'ic5PFL2Relative', \n 'ic5PFL3Absolute')\n)\n\n\nprocess.ic5PFL1FastL2L3L6 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4PFL1Fastjet', \n 'ic5PFL2Relative', \n 'ic5PFL3Absolute', \n 'ic5PFL6SLB')\n)\n\n\nprocess.ic5PFL1FastL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ic5PFL1Fastjet', \n 'ic5PFL2Relative', \n 'ic5PFL3Absolute', \n 'ic5PFResidual')\n)\n\n\nprocess.ic5PFL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('IC5PF'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n)\n\n\nprocess.ic5PFL1L2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ic5PFL1Offset', \n 'ic5PFL2Relative', \n 'ic5PFL3Absolute')\n)\n\n\nprocess.ic5PFL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ic5PFL1Offset', \n 'ic5PFL2Relative', \n 'ic5PFL3Absolute', \n 'ic5PFResidual')\n)\n\n\nprocess.ic5PFL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('IC5PF'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.ic5PFL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ic5PFL2Relative', \n 'ic5PFL3Absolute')\n)\n\n\nprocess.ic5PFL2L3L6 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ic5PFL2Relative', \n 'ic5PFL3Absolute', \n 'ic5PFL6SLB')\n)\n\n\nprocess.ic5PFL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ic5PFL2Relative', \n 'ic5PFL3Absolute', \n 'ic5PFResidual')\n)\n\n\nprocess.ic5PFL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('IC5PF'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.ic5PFL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('IC5PF'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.ic5PFL6SLB = cms.ESProducer(\"L6SLBCorrectionESProducer\",\n addMuonToJet = cms.bool(False),\n algorithm = cms.string(''),\n level = cms.string('L6SLB'),\n srcBTagInfoElectron = cms.InputTag(\"ic5PFJetsSoftElectronTagInfos\"),\n srcBTagInfoMuon = cms.InputTag(\"ic5PFJetsSoftMuonTagInfos\")\n)\n\n\nprocess.ic5PFResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('IC5PF'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.idealForDigiCSCGeometry = cms.ESProducer(\"CSCGeometryESModule\",\n alignmentsLabel = cms.string('fakeForIdeal'),\n appendToDataLabel = cms.string('idealForDigi'),\n applyAlignment = cms.bool(False),\n debugV = cms.untracked.bool(False),\n useCentreTIOffsets = cms.bool(False),\n useDDD = cms.bool(False),\n useGangedStripsInME1a = cms.bool(True),\n useOnlyWiresInME1a = cms.bool(False),\n useRealWireGeometry = cms.bool(True)\n)\n\n\nprocess.idealForDigiDTGeometry = cms.ESProducer(\"DTGeometryESModule\",\n alignmentsLabel = cms.string('fakeForIdeal'),\n appendToDataLabel = cms.string('idealForDigi'),\n applyAlignment = cms.bool(False),\n fromDDD = cms.bool(False)\n)\n\n\nprocess.idealForDigiTrackerGeometry = cms.ESProducer(\"TrackerDigiGeometryESModule\",\n alignmentsLabel = cms.string('fakeForIdeal'),\n appendToDataLabel = cms.string('idealForDigi'),\n applyAlignment = cms.bool(False),\n fromDDD = cms.bool(False)\n)\n\n\nprocess.kt4CaloL1FastL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4CaloL1Fastjet', \n 'kt4CaloL2Relative', \n 'kt4CaloL3Absolute')\n)\n\n\nprocess.kt4CaloL1FastL2L3L6 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt4CaloL1Offset', \n 'kt4CaloL2Relative', \n 'kt4CaloL3Absolute', \n 'kt4CaloL6SLB')\n)\n\n\nprocess.kt4CaloL1FastL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt4CaloL1Fastjet', \n 'kt4CaloL2Relative', \n 'kt4CaloL3Absolute', \n 'kt4CaloResidual')\n)\n\n\nprocess.kt4CaloL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('KT4Calo'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAllCalo\")\n)\n\n\nprocess.kt4CaloL1L2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt4CaloL1Offset', \n 'kt4CaloL2Relative', \n 'kt4CaloL3Absolute')\n)\n\n\nprocess.kt4CaloL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt4CaloL1Offset', \n 'kt4CaloL2Relative', \n 'kt4CaloL3Absolute', \n 'kt4CaloResidual')\n)\n\n\nprocess.kt4CaloL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('KT4Calo'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.kt4CaloL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt4CaloL2Relative', \n 'kt4CaloL3Absolute')\n)\n\n\nprocess.kt4CaloL2L3L6 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt4CaloL2Relative', \n 'kt4CaloL3Absolute', \n 'kt4CaloL6SLB')\n)\n\n\nprocess.kt4CaloL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt4CaloL2Relative', \n 'kt4CaloL3Absolute', \n 'kt4CaloResidual')\n)\n\n\nprocess.kt4CaloL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('KT4Calo'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.kt4CaloL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('KT4Calo'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.kt4CaloL6SLB = cms.ESProducer(\"L6SLBCorrectionESProducer\",\n addMuonToJet = cms.bool(True),\n algorithm = cms.string(''),\n level = cms.string('L6SLB'),\n srcBTagInfoElectron = cms.InputTag(\"kt4CaloJetsSoftElectronTagInfos\"),\n srcBTagInfoMuon = cms.InputTag(\"kt4CaloJetsSoftMuonTagInfos\")\n)\n\n\nprocess.kt4CaloResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('KT4Calo'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.kt4PFL1FastL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4PFL1Fastjet', \n 'kt4PFL2Relative', \n 'kt4PFL3Absolute')\n)\n\n\nprocess.kt4PFL1FastL2L3L6 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4PFL1Fastjet', \n 'kt4PFL2Relative', \n 'kt4PFL3Absolute', \n 'kt4PFL6SLB')\n)\n\n\nprocess.kt4PFL1FastL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt4PFL1Fastjet', \n 'kt4PFL2Relative', \n 'kt4PFL3Absolute', \n 'kt4PFResidual')\n)\n\n\nprocess.kt4PFL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('KT4PF'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n)\n\n\nprocess.kt4PFL1L2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt4PFL1Offset', \n 'kt4PFL2Relative', \n 'kt4PFL3Absolute')\n)\n\n\nprocess.kt4PFL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt4PFL1Offset', \n 'kt4PFL2Relative', \n 'kt4PFL3Absolute', \n 'kt4PFResidual')\n)\n\n\nprocess.kt4PFL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('KT4PF'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.kt4PFL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt4PFL2Relative', \n 'kt4PFL3Absolute')\n)\n\n\nprocess.kt4PFL2L3L6 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt4PFL2Relative', \n 'kt4PFL3Absolute', \n 'kt4PFL6SLB')\n)\n\n\nprocess.kt4PFL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt4PFL2Relative', \n 'kt4PFL3Absolute', \n 'kt4PFResidual')\n)\n\n\nprocess.kt4PFL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('KT4PF'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.kt4PFL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('KT4PF'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.kt4PFL6SLB = cms.ESProducer(\"L6SLBCorrectionESProducer\",\n addMuonToJet = cms.bool(False),\n algorithm = cms.string(''),\n level = cms.string('L6SLB'),\n srcBTagInfoElectron = cms.InputTag(\"kt4PFJetsSoftElectronTagInfos\"),\n srcBTagInfoMuon = cms.InputTag(\"kt4PFJetsSoftMuonTagInfos\")\n)\n\n\nprocess.kt4PFResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('KT4PF'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.kt6CaloL1FastL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4CaloL1Fastjet', \n 'kt6CaloL2Relative', \n 'kt6CaloL3Absolute')\n)\n\n\nprocess.kt6CaloL1FastL2L3L6 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt6CaloL1Offset', \n 'kt6CaloL2Relative', \n 'kt6CaloL3Absolute', \n 'kt6CaloL6SLB')\n)\n\n\nprocess.kt6CaloL1FastL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt6CaloL1Fastjet', \n 'kt6CaloL2Relative', \n 'kt6CaloL3Absolute', \n 'kt6CaloResidual')\n)\n\n\nprocess.kt6CaloL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('KT6Calo'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAllCalo\")\n)\n\n\nprocess.kt6CaloL1L2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt6CaloL1Offset', \n 'kt6CaloL2Relative', \n 'kt6CaloL3Absolute')\n)\n\n\nprocess.kt6CaloL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt6CaloL1Offset', \n 'kt6CaloL2Relative', \n 'kt6CaloL3Absolute', \n 'kt6CaloResidual')\n)\n\n\nprocess.kt6CaloL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('KT6Calo'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.kt6CaloL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt6CaloL2Relative', \n 'kt6CaloL3Absolute')\n)\n\n\nprocess.kt6CaloL2L3L6 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt6CaloL2Relative', \n 'kt6CaloL3Absolute', \n 'kt6CaloL6SLB')\n)\n\n\nprocess.kt6CaloL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt6CaloL2Relative', \n 'kt6CaloL3Absolute', \n 'kt6CaloResidual')\n)\n\n\nprocess.kt6CaloL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('KT6Calo'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.kt6CaloL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('KT6Calo'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.kt6CaloL6SLB = cms.ESProducer(\"L6SLBCorrectionESProducer\",\n addMuonToJet = cms.bool(True),\n algorithm = cms.string(''),\n level = cms.string('L6SLB'),\n srcBTagInfoElectron = cms.InputTag(\"kt6CaloJetsSoftElectronTagInfos\"),\n srcBTagInfoMuon = cms.InputTag(\"kt6CaloJetsSoftMuonTagInfos\")\n)\n\n\nprocess.kt6CaloResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('KT6Calo'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.kt6PFL1FastL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4PFL1Fastjet', \n 'kt6PFL2Relative', \n 'kt6PFL3Absolute')\n)\n\n\nprocess.kt6PFL1FastL2L3L6 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('ak4PFL1Fastjet', \n 'kt6PFL2Relative', \n 'kt6PFL3Absolute', \n 'kt6PFL6SLB')\n)\n\n\nprocess.kt6PFL1FastL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt6PFL1Fastjet', \n 'kt6PFL2Relative', \n 'kt6PFL3Absolute', \n 'kt6PFResidual')\n)\n\n\nprocess.kt6PFL1Fastjet = cms.ESProducer(\"L1FastjetCorrectionESProducer\",\n algorithm = cms.string('KT6PF'),\n level = cms.string('L1FastJet'),\n srcRho = cms.InputTag(\"fixedGridRhoFastjetAll\")\n)\n\n\nprocess.kt6PFL1L2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt6PFL1Offset', \n 'kt6PFL2Relative', \n 'kt6PFL3Absolute')\n)\n\n\nprocess.kt6PFL1L2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt6PFL1Offset', \n 'kt6PFL2Relative', \n 'kt6PFL3Absolute', \n 'kt6PFResidual')\n)\n\n\nprocess.kt6PFL1Offset = cms.ESProducer(\"L1OffsetCorrectionESProducer\",\n algorithm = cms.string('KT6PF'),\n level = cms.string('L1Offset'),\n minVtxNdof = cms.int32(4),\n vertexCollection = cms.string('offlinePrimaryVertices')\n)\n\n\nprocess.kt6PFL2L3 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt6PFL2Relative', \n 'kt6PFL3Absolute')\n)\n\n\nprocess.kt6PFL2L3L6 = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt6PFL2Relative', \n 'kt6PFL3Absolute', \n 'kt6PFL6SLB')\n)\n\n\nprocess.kt6PFL2L3Residual = cms.ESProducer(\"JetCorrectionESChain\",\n correctors = cms.vstring('kt6PFL2Relative', \n 'kt6PFL3Absolute', \n 'kt6PFResidual')\n)\n\n\nprocess.kt6PFL2Relative = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('KT6PF'),\n level = cms.string('L2Relative')\n)\n\n\nprocess.kt6PFL3Absolute = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('KT6PF'),\n level = cms.string('L3Absolute')\n)\n\n\nprocess.kt6PFL6SLB = cms.ESProducer(\"L6SLBCorrectionESProducer\",\n addMuonToJet = cms.bool(False),\n algorithm = cms.string(''),\n level = cms.string('L6SLB'),\n srcBTagInfoElectron = cms.InputTag(\"kt6PFJetsSoftElectronTagInfos\"),\n srcBTagInfoMuon = cms.InputTag(\"kt6PFJetsSoftMuonTagInfos\")\n)\n\n\nprocess.kt6PFResidual = cms.ESProducer(\"LXXXCorrectionESProducer\",\n algorithm = cms.string('KT6PF'),\n level = cms.string('L2L3Residual')\n)\n\n\nprocess.siPixelQualityESProducer = cms.ESProducer(\"SiPixelQualityESProducer\",\n ListOfRecordToMerge = cms.VPSet(cms.PSet(\n record = cms.string('SiPixelQualityFromDbRcd'),\n tag = cms.string('')\n ), \n cms.PSet(\n record = cms.string('SiPixelDetVOffRcd'),\n tag = cms.string('')\n ))\n)\n\n\nprocess.siStripBackPlaneCorrectionDepESProducer = cms.ESProducer(\"SiStripBackPlaneCorrectionDepESProducer\",\n BackPlaneCorrectionDeconvMode = cms.PSet(\n label = cms.untracked.string('deconvolution'),\n record = cms.string('SiStripBackPlaneCorrectionRcd')\n ),\n BackPlaneCorrectionPeakMode = cms.PSet(\n label = cms.untracked.string('peak'),\n record = cms.string('SiStripBackPlaneCorrectionRcd')\n ),\n LatencyRecord = cms.PSet(\n label = cms.untracked.string(''),\n record = cms.string('SiStripLatencyRcd')\n )\n)\n\n\nprocess.siStripGainESProducer = cms.ESProducer(\"SiStripGainESProducer\",\n APVGain = cms.VPSet(cms.PSet(\n Label = cms.untracked.string(''),\n NormalizationFactor = cms.untracked.double(1.0),\n Record = cms.string('SiStripApvGainRcd')\n ), \n cms.PSet(\n Label = cms.untracked.string(''),\n NormalizationFactor = cms.untracked.double(1.0),\n Record = cms.string('SiStripApvGain2Rcd')\n )),\n AutomaticNormalization = cms.bool(False),\n appendToDataLabel = cms.string(''),\n printDebug = cms.untracked.bool(False)\n)\n\n\nprocess.siStripLorentzAngleDepESProducer = cms.ESProducer(\"SiStripLorentzAngleDepESProducer\",\n LatencyRecord = cms.PSet(\n label = cms.untracked.string(''),\n record = cms.string('SiStripLatencyRcd')\n ),\n LorentzAngleDeconvMode = cms.PSet(\n label = cms.untracked.string('deconvolution'),\n record = cms.string('SiStripLorentzAngleRcd')\n ),\n LorentzAnglePeakMode = cms.PSet(\n label = cms.untracked.string('peak'),\n record = cms.string('SiStripLorentzAngleRcd')\n )\n)\n\n\nprocess.siStripQualityESProducer = cms.ESProducer(\"SiStripQualityESProducer\",\n ListOfRecordToMerge = cms.VPSet(cms.PSet(\n record = cms.string('SiStripDetVOffRcd'),\n tag = cms.string('')\n ), \n cms.PSet(\n record = cms.string('SiStripDetCablingRcd'),\n tag = cms.string('')\n ), \n cms.PSet(\n record = cms.string('RunInfoRcd'),\n tag = cms.string('')\n ), \n cms.PSet(\n record = cms.string('SiStripBadChannelRcd'),\n tag = cms.string('')\n ), \n cms.PSet(\n record = cms.string('SiStripBadFiberRcd'),\n tag = cms.string('')\n ), \n cms.PSet(\n record = cms.string('SiStripBadModuleRcd'),\n tag = cms.string('')\n ), \n cms.PSet(\n record = cms.string('SiStripBadStripRcd'),\n tag = cms.string('')\n )),\n PrintDebugOutput = cms.bool(False),\n ReduceGranularity = cms.bool(False),\n ThresholdForReducedGranularity = cms.double(0.3),\n UseEmptyRunInfo = cms.bool(False),\n appendToDataLabel = cms.string('')\n)\n\n\nprocess.sistripconn = cms.ESProducer(\"SiStripConnectivity\")\n\n\nprocess.stripCPEESProducer = cms.ESProducer(\"StripCPEESProducer\",\n ComponentName = cms.string('stripCPE'),\n ComponentType = cms.string('SimpleStripCPE'),\n parameters = cms.PSet(\n\n )\n)\n\n\nprocess.trackerGeometryDB = cms.ESProducer(\"TrackerDigiGeometryESModule\",\n alignmentsLabel = cms.string(''),\n appendToDataLabel = cms.string(''),\n applyAlignment = cms.bool(True),\n fromDDD = cms.bool(False)\n)\n\n\nprocess.trackerNumberingGeometryDB = cms.ESProducer(\"TrackerGeometricDetESModule\",\n appendToDataLabel = cms.string(''),\n fromDDD = cms.bool(False)\n)\n\n\nprocess.trackerTopology = cms.ESProducer(\"TrackerTopologyEP\",\n appendToDataLabel = cms.string('')\n)\n\n\nprocess.GlobalTag = cms.ESSource(\"PoolDBESSource\",\n DBParameters = cms.PSet(\n authenticationPath = cms.untracked.string(''),\n authenticationSystem = cms.untracked.int32(0),\n connectionRetrialPeriod = cms.untracked.int32(10),\n connectionRetrialTimeOut = cms.untracked.int32(60),\n connectionTimeOut = cms.untracked.int32(60),\n enableConnectionSharing = cms.untracked.bool(True),\n enablePoolAutomaticCleanUp = cms.untracked.bool(False),\n enableReadOnlySessionOnUpdateConnection = cms.untracked.bool(False),\n idleConnectionCleanupPeriod = cms.untracked.int32(10),\n messageLevel = cms.untracked.int32(0)\n ),\n connect = cms.string('frontier://FrontierProd/CMS_CONDITIONS'),\n globaltag = cms.string('76X_mcRun2_asymptotic_v12'),\n toGet = cms.VPSet()\n)\n\n\nprocess.HepPDTESSource = cms.ESSource(\"HepPDTESSource\",\n pdtFileName = cms.FileInPath('SimGeneral/HepPDTESSource/data/pythiaparticle.tbl')\n)\n\n\nprocess.eegeom = cms.ESSource(\"EmptyESSource\",\n firstValid = cms.vuint32(1),\n iovIsRunNotTime = cms.bool(True),\n recordName = cms.string('EcalMappingRcd')\n)\n\n\nprocess.es_hardcode = cms.ESSource(\"HcalHardcodeCalibrations\",\n GainWidthsForTrigPrims = cms.bool(False),\n HERecalibration = cms.bool(False),\n HEreCalibCutoff = cms.double(20.0),\n HFRecalibration = cms.bool(False),\n HcalReLabel = cms.PSet(\n RelabelHits = cms.untracked.bool(False),\n RelabelRules = cms.untracked.PSet(\n CorrectPhi = cms.untracked.bool(False),\n Eta1 = cms.untracked.vint32(1, 2, 2, 2, 3, \n 3, 3, 3, 3, 3, \n 3, 3, 3, 3, 3, \n 3, 3, 3, 3),\n Eta16 = cms.untracked.vint32(1, 1, 2, 2, 2, \n 2, 2, 2, 2, 3, \n 3, 3, 3, 3, 3, \n 3, 3, 3, 3),\n Eta17 = cms.untracked.vint32(1, 1, 2, 2, 3, \n 3, 3, 4, 4, 4, \n 4, 4, 5, 5, 5, \n 5, 5, 5, 5)\n )\n ),\n hcalTopologyConstants = cms.PSet(\n maxDepthHB = cms.int32(2),\n maxDepthHE = cms.int32(3),\n mode = cms.string('HcalTopologyMode::LHC')\n ),\n iLumi = cms.double(-1.0),\n toGet = cms.untracked.vstring('GainWidths')\n)\n\n\nprocess.jec = cms.ESSource(\"PoolDBESSource\",\n DBParameters = cms.PSet(\n messageLevel = cms.untracked.int32(0)\n ),\n connect = cms.string('sqlite_file:Fall15_25nsV2_MC.db'),\n timetype = cms.string('runnumber'),\n toGet = cms.VPSet(cms.PSet(\n label = cms.untracked.string('AK4PFchs'),\n record = cms.string('JetCorrectionsRecord'),\n tag = cms.string('JetCorrectorParametersCollection_Fall15_25nsV2_MC_AK4PFchs')\n ))\n)\n\n\nprocess.prefer(\"es_hardcode\")\n\nprocess.prefer(\"jec\")\n\nprocess.CondDBCommon = cms.PSet(\n DBParameters = cms.PSet(\n authenticationPath = cms.untracked.string(''),\n authenticationSystem = cms.untracked.int32(0),\n connectionRetrialPeriod = cms.untracked.int32(10),\n connectionRetrialTimeOut = cms.untracked.int32(60),\n connectionTimeOut = cms.untracked.int32(60),\n enableConnectionSharing = cms.untracked.bool(True),\n enablePoolAutomaticCleanUp = cms.untracked.bool(False),\n enableReadOnlySessionOnUpdateConnection = cms.untracked.bool(False),\n idleConnectionCleanupPeriod = cms.untracked.int32(10),\n messageLevel = cms.untracked.int32(0)\n ),\n connect = cms.string('protocol://db/schema')\n)\n\nprocess.CondDBSetup = cms.PSet(\n DBParameters = cms.PSet(\n authenticationPath = cms.untracked.string(''),\n authenticationSystem = cms.untracked.int32(0),\n connectionRetrialPeriod = cms.untracked.int32(10),\n connectionRetrialTimeOut = cms.untracked.int32(60),\n connectionTimeOut = cms.untracked.int32(60),\n enableConnectionSharing = cms.untracked.bool(True),\n enablePoolAutomaticCleanUp = cms.untracked.bool(False),\n enableReadOnlySessionOnUpdateConnection = cms.untracked.bool(False),\n idleConnectionCleanupPeriod = cms.untracked.int32(10),\n messageLevel = cms.untracked.int32(0)\n )\n)\n\nprocess.HcalReLabel = cms.PSet(\n RelabelHits = cms.untracked.bool(False),\n RelabelRules = cms.untracked.PSet(\n CorrectPhi = cms.untracked.bool(False),\n Eta1 = cms.untracked.vint32(1, 2, 2, 2, 3, \n 3, 3, 3, 3, 3, \n 3, 3, 3, 3, 3, \n 3, 3, 3, 3),\n Eta16 = cms.untracked.vint32(1, 1, 2, 2, 2, \n 2, 2, 2, 2, 3, \n 3, 3, 3, 3, 3, \n 3, 3, 3, 3),\n Eta17 = cms.untracked.vint32(1, 1, 2, 2, 3, \n 3, 3, 4, 4, 4, \n 4, 4, 5, 5, 5, \n 5, 5, 5, 5)\n )\n)\n\nprocess.maxEvents = cms.untracked.PSet(\n input = cms.untracked.int32(-1)\n)\n\nprocess.mvaEleID_PHYS14_PU20bx25_nonTrig_V1_producer_config = cms.PSet(\n mvaName = cms.string('ElectronMVAEstimatorRun2Phys14NonTrig'),\n mvaTag = cms.string('25nsV1'),\n weightFileNames = cms.vstring('RecoEgamma/ElectronIdentification/data/PHYS14/EIDmva_EB1_5_oldscenario2phys14_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/PHYS14/EIDmva_EB2_5_oldscenario2phys14_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/PHYS14/EIDmva_EE_5_oldscenario2phys14_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/PHYS14/EIDmva_EB1_10_oldscenario2phys14_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/PHYS14/EIDmva_EB2_10_oldscenario2phys14_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/PHYS14/EIDmva_EE_10_oldscenario2phys14_BDT.weights.xml')\n)\n\nprocess.mvaEleID_PHYS14_PU20bx25_nonTrig_V1_wp80 = cms.PSet(\n cutFlow = cms.VPSet(cms.PSet(\n cutName = cms.string('GsfEleMVACut'),\n isIgnored = cms.bool(False),\n mvaCategoriesMapName = cms.InputTag(\"electronMVAValueMapProducer\",\"ElectronMVAEstimatorRun2Phys14NonTrig25nsV1Categories\"),\n mvaCuts = cms.vdouble(-0.253, 0.081, -0.081, 0.965, 0.917, \n 0.683),\n mvaValueMapName = cms.InputTag(\"electronMVAValueMapProducer\",\"ElectronMVAEstimatorRun2Phys14NonTrig25nsV1Values\"),\n needsAdditionalProducts = cms.bool(True)\n )),\n idName = cms.string('mvaEleID-PHYS14-PU20bx25-nonTrig-V1-wp80'),\n isPOGApproved = cms.untracked.bool(False)\n)\n\nprocess.mvaEleID_PHYS14_PU20bx25_nonTrig_V1_wp90 = cms.PSet(\n cutFlow = cms.VPSet(cms.PSet(\n cutName = cms.string('GsfEleMVACut'),\n isIgnored = cms.bool(False),\n mvaCategoriesMapName = cms.InputTag(\"electronMVAValueMapProducer\",\"ElectronMVAEstimatorRun2Phys14NonTrig25nsV1Categories\"),\n mvaCuts = cms.vdouble(-0.483, -0.267, -0.323, 0.933, 0.825, \n 0.337),\n mvaValueMapName = cms.InputTag(\"electronMVAValueMapProducer\",\"ElectronMVAEstimatorRun2Phys14NonTrig25nsV1Values\"),\n needsAdditionalProducts = cms.bool(True)\n )),\n idName = cms.string('mvaEleID-PHYS14-PU20bx25-nonTrig-V1-wp90'),\n isPOGApproved = cms.untracked.bool(False)\n)\n\nprocess.mvaEleID_Spring15_25ns_Trig_V1_producer_config = cms.PSet(\n beamSpot = cms.InputTag(\"offlineBeamSpot\"),\n conversionsAOD = cms.InputTag(\"allConversions\"),\n conversionsMiniAOD = cms.InputTag(\"reducedEgamma\",\"reducedConversions\"),\n mvaName = cms.string('ElectronMVAEstimatorRun2Spring15Trig'),\n mvaTag = cms.string('25nsV1'),\n weightFileNames = cms.vstring('RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EB1_10_oldTrigSpring15_25ns_data_1_VarD_TMVA412_Sig6BkgAll_MG_noSpec_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EB2_10_oldTrigSpring15_25ns_data_1_VarD_TMVA412_Sig6BkgAll_MG_noSpec_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EE_10_oldTrigSpring15_25ns_data_1_VarD_TMVA412_Sig6BkgAll_MG_noSpec_BDT.weights.xml')\n)\n\nprocess.mvaEleID_Spring15_25ns_Trig_V1_wp80 = cms.PSet(\n cutFlow = cms.VPSet(cms.PSet(\n cutName = cms.string('GsfEleMVACut'),\n isIgnored = cms.bool(False),\n mvaCategoriesMapName = cms.InputTag(\"electronMVAValueMapProducer\",\"ElectronMVAEstimatorRun2Spring15Trig25nsV1Categories\"),\n mvaCuts = cms.vdouble(0.988153, 0.96791, 0.841729),\n mvaValueMapName = cms.InputTag(\"electronMVAValueMapProducer\",\"ElectronMVAEstimatorRun2Spring15Trig25nsV1Values\"),\n needsAdditionalProducts = cms.bool(True)\n )),\n idName = cms.string('mvaEleID-Spring15-25ns-Trig-V1-wp80')\n)\n\nprocess.mvaEleID_Spring15_25ns_Trig_V1_wp90 = cms.PSet(\n cutFlow = cms.VPSet(cms.PSet(\n cutName = cms.string('GsfEleMVACut'),\n isIgnored = cms.bool(False),\n mvaCategoriesMapName = cms.InputTag(\"electronMVAValueMapProducer\",\"ElectronMVAEstimatorRun2Spring15Trig25nsV1Categories\"),\n mvaCuts = cms.vdouble(0.972153, 0.922126, 0.610764),\n mvaValueMapName = cms.InputTag(\"electronMVAValueMapProducer\",\"ElectronMVAEstimatorRun2Spring15Trig25nsV1Values\"),\n needsAdditionalProducts = cms.bool(True)\n )),\n idName = cms.string('mvaEleID-Spring15-25ns-Trig-V1-wp90')\n)\n\nprocess.mvaEleID_Spring15_25ns_nonTrig_V1_producer_config = cms.PSet(\n beamSpot = cms.InputTag(\"offlineBeamSpot\"),\n conversionsAOD = cms.InputTag(\"allConversions\"),\n conversionsMiniAOD = cms.InputTag(\"reducedEgamma\",\"reducedConversions\"),\n mvaName = cms.string('ElectronMVAEstimatorRun2Spring15NonTrig'),\n mvaTag = cms.string('25nsV1'),\n weightFileNames = cms.vstring('RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EB1_5_oldNonTrigSpring15_ConvVarCwoBoolean_TMVA412_FullStatLowPt_PairNegWeightsGlobal_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EB2_5_oldNonTrigSpring15_ConvVarCwoBoolean_TMVA412_FullStatLowPt_PairNegWeightsGlobal_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EE_5_oldNonTrigSpring15_ConvVarCwoBoolean_TMVA412_FullStatLowPt_PairNegWeightsGlobal_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EB1_10_oldNonTrigSpring15_ConvVarCwoBoolean_TMVA412_FullStatLowPt_PairNegWeightsGlobal_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EB2_10_oldNonTrigSpring15_ConvVarCwoBoolean_TMVA412_FullStatLowPt_PairNegWeightsGlobal_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EE_10_oldNonTrigSpring15_ConvVarCwoBoolean_TMVA412_FullStatLowPt_PairNegWeightsGlobal_BDT.weights.xml')\n)\n\nprocess.mvaEleID_Spring15_25ns_nonTrig_V1_wp80 = cms.PSet(\n cutFlow = cms.VPSet(cms.PSet(\n cutName = cms.string('GsfEleMVACut'),\n isIgnored = cms.bool(False),\n mvaCategoriesMapName = cms.InputTag(\"electronMVAValueMapProducer\",\"ElectronMVAEstimatorRun2Spring15NonTrig25nsV1Categories\"),\n mvaCuts = cms.vdouble(0.287435, 0.221846, -0.303263, 0.967083, 0.929117, \n 0.726311),\n mvaValueMapName = cms.InputTag(\"electronMVAValueMapProducer\",\"ElectronMVAEstimatorRun2Spring15NonTrig25nsV1Values\"),\n needsAdditionalProducts = cms.bool(True)\n )),\n idName = cms.string('mvaEleID-Spring15-25ns-nonTrig-V1-wp80'),\n isPOGApproved = cms.untracked.bool(True)\n)\n\nprocess.mvaEleID_Spring15_25ns_nonTrig_V1_wp90 = cms.PSet(\n cutFlow = cms.VPSet(cms.PSet(\n cutName = cms.string('GsfEleMVACut'),\n isIgnored = cms.bool(False),\n mvaCategoriesMapName = cms.InputTag(\"electronMVAValueMapProducer\",\"ElectronMVAEstimatorRun2Spring15NonTrig25nsV1Categories\"),\n mvaCuts = cms.vdouble(-0.083313, -0.235222, -0.67099, 0.913286, 0.805013, \n 0.358969),\n mvaValueMapName = cms.InputTag(\"electronMVAValueMapProducer\",\"ElectronMVAEstimatorRun2Spring15NonTrig25nsV1Values\"),\n needsAdditionalProducts = cms.bool(True)\n )),\n idName = cms.string('mvaEleID-Spring15-25ns-nonTrig-V1-wp90'),\n isPOGApproved = cms.untracked.bool(True)\n)\n\nprocess.mvaEleID_Spring15_50ns_Trig_V1_producer_config = cms.PSet(\n beamSpot = cms.InputTag(\"offlineBeamSpot\"),\n conversionsAOD = cms.InputTag(\"allConversions\"),\n conversionsMiniAOD = cms.InputTag(\"reducedEgamma\",\"reducedConversions\"),\n mvaName = cms.string('ElectronMVAEstimatorRun2Spring15Trig'),\n mvaTag = cms.string('50nsV1'),\n weightFileNames = cms.vstring('RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EB1_10_oldTrigSpring15_50ns_data_1_VarD_TMVA412_Sig6BkgAll_MG_noSpec_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EB2_10_oldTrigSpring15_50ns_data_1_VarD_TMVA412_Sig6BkgAll_MG_noSpec_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EE_10_oldTrigSpring15_50ns_data_1_VarD_TMVA412_Sig6BkgAll_MG_noSpec_BDT.weights.xml')\n)\n\nprocess.mvaEleID_Spring15_50ns_Trig_V1_wp80 = cms.PSet(\n cutFlow = cms.VPSet(cms.PSet(\n cutName = cms.string('GsfEleMVACut'),\n isIgnored = cms.bool(False),\n mvaCategoriesMapName = cms.InputTag(\"electronMVAValueMapProducer\",\"ElectronMVAEstimatorRun2Spring15Trig50nsV1Categories\"),\n mvaCuts = cms.vdouble(0.981841, 0.946762, 0.79704),\n mvaValueMapName = cms.InputTag(\"electronMVAValueMapProducer\",\"ElectronMVAEstimatorRun2Spring15Trig50nsV1Values\"),\n needsAdditionalProducts = cms.bool(True)\n )),\n idName = cms.string('mvaEleID-Spring15-50ns-Trig-V1-wp80'),\n isPOGApproved = cms.untracked.bool(True)\n)\n\nprocess.mvaEleID_Spring15_50ns_Trig_V1_wp90 = cms.PSet(\n cutFlow = cms.VPSet(cms.PSet(\n cutName = cms.string('GsfEleMVACut'),\n isIgnored = cms.bool(False),\n mvaCategoriesMapName = cms.InputTag(\"electronMVAValueMapProducer\",\"ElectronMVAEstimatorRun2Spring15Trig50nsV1Categories\"),\n mvaCuts = cms.vdouble(0.953843, 0.849994, 0.514118),\n mvaValueMapName = cms.InputTag(\"electronMVAValueMapProducer\",\"ElectronMVAEstimatorRun2Spring15Trig50nsV1Values\"),\n needsAdditionalProducts = cms.bool(True)\n )),\n idName = cms.string('mvaEleID-Spring15-50ns-Trig-V1-wp90'),\n isPOGApproved = cms.untracked.bool(True)\n)\n\nprocess.mvaConfigsForEleProducer = cms.VPSet(cms.PSet(\n mvaName = cms.string('ElectronMVAEstimatorRun2Phys14NonTrig'),\n mvaTag = cms.string('25nsV1'),\n weightFileNames = cms.vstring('RecoEgamma/ElectronIdentification/data/PHYS14/EIDmva_EB1_5_oldscenario2phys14_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/PHYS14/EIDmva_EB2_5_oldscenario2phys14_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/PHYS14/EIDmva_EE_5_oldscenario2phys14_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/PHYS14/EIDmva_EB1_10_oldscenario2phys14_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/PHYS14/EIDmva_EB2_10_oldscenario2phys14_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/PHYS14/EIDmva_EE_10_oldscenario2phys14_BDT.weights.xml')\n), \n cms.PSet(\n beamSpot = cms.InputTag(\"offlineBeamSpot\"),\n conversionsAOD = cms.InputTag(\"allConversions\"),\n conversionsMiniAOD = cms.InputTag(\"reducedEgamma\",\"reducedConversions\"),\n mvaName = cms.string('ElectronMVAEstimatorRun2Spring15NonTrig'),\n mvaTag = cms.string('25nsV1'),\n weightFileNames = cms.vstring('RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EB1_5_oldNonTrigSpring15_ConvVarCwoBoolean_TMVA412_FullStatLowPt_PairNegWeightsGlobal_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EB2_5_oldNonTrigSpring15_ConvVarCwoBoolean_TMVA412_FullStatLowPt_PairNegWeightsGlobal_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EE_5_oldNonTrigSpring15_ConvVarCwoBoolean_TMVA412_FullStatLowPt_PairNegWeightsGlobal_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EB1_10_oldNonTrigSpring15_ConvVarCwoBoolean_TMVA412_FullStatLowPt_PairNegWeightsGlobal_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EB2_10_oldNonTrigSpring15_ConvVarCwoBoolean_TMVA412_FullStatLowPt_PairNegWeightsGlobal_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EE_10_oldNonTrigSpring15_ConvVarCwoBoolean_TMVA412_FullStatLowPt_PairNegWeightsGlobal_BDT.weights.xml')\n ), \n cms.PSet(\n beamSpot = cms.InputTag(\"offlineBeamSpot\"),\n conversionsAOD = cms.InputTag(\"allConversions\"),\n conversionsMiniAOD = cms.InputTag(\"reducedEgamma\",\"reducedConversions\"),\n mvaName = cms.string('ElectronMVAEstimatorRun2Spring15Trig'),\n mvaTag = cms.string('50nsV1'),\n weightFileNames = cms.vstring('RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EB1_10_oldTrigSpring15_50ns_data_1_VarD_TMVA412_Sig6BkgAll_MG_noSpec_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EB2_10_oldTrigSpring15_50ns_data_1_VarD_TMVA412_Sig6BkgAll_MG_noSpec_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EE_10_oldTrigSpring15_50ns_data_1_VarD_TMVA412_Sig6BkgAll_MG_noSpec_BDT.weights.xml')\n ), \n cms.PSet(\n beamSpot = cms.InputTag(\"offlineBeamSpot\"),\n conversionsAOD = cms.InputTag(\"allConversions\"),\n conversionsMiniAOD = cms.InputTag(\"reducedEgamma\",\"reducedConversions\"),\n mvaName = cms.string('ElectronMVAEstimatorRun2Spring15Trig'),\n mvaTag = cms.string('25nsV1'),\n weightFileNames = cms.vstring('RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EB1_10_oldTrigSpring15_25ns_data_1_VarD_TMVA412_Sig6BkgAll_MG_noSpec_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EB2_10_oldTrigSpring15_25ns_data_1_VarD_TMVA412_Sig6BkgAll_MG_noSpec_BDT.weights.xml', \n 'RecoEgamma/ElectronIdentification/data/Spring15/EIDmva_EE_10_oldTrigSpring15_25ns_data_1_VarD_TMVA412_Sig6BkgAll_MG_noSpec_BDT.weights.xml')\n ))\n\n","sub_path":"TopAnalysis/grid/crab_MC13TeV_TTJets/inputs/PSetDump.py","file_name":"PSetDump.py","file_ext":"py","file_size_in_byte":152559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"208896255","text":"import unittest\nfrom RenderManForBlender.rfb_unittests.test_string_expr import StringExprTest\n\nclasses = [\n StringExprTest\n]\n\ndef suite():\n suite = unittest.TestSuite()\n\n for cls in classes:\n cls.add_tests(suite)\n\n return suite\n\ndef run_rfb_unittests():\n runner = unittest.TextTestRunner()\n runner.run(suite())\n\nif __name__ == '__main__':\n run_rfb_unittests()","sub_path":"rfb_unittests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"7488783","text":"import tensorflow as tf\n\ninput_X = tf.placeholder(dtype = tf.float32)\n\nW = tf.Variable(tf.ones([8,3]),dtype = tf.float32)\nb = tf.Variable(3.)\n\nW=tf.assign(W,tf.random_normal([8,3], stddev=0.3))\nmul = tf.matmul(input_X,W)\nx = tf.add(mul,b)\nx_tran = tf.transpose(x)\n#new_op\noutput = tf.matmul(x_tran,x)\n\n\ninit = tf.initialize_all_variables()\n\nwith tf.Session() as sess:\n sess.run(init)\n print(sess.run([output],feed_dict = {input_X:[[4,2,12,5,6,7,7,5],[1,3,4,4,6,7,8,5],[4,3,4,5,6,7,8,5]]}))","sub_path":"test1/matmul.py","file_name":"matmul.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"22816193","text":"\"\"\"\ninsertionソート\n先頭から一つ前の値と比べていく\ntempに避難して適切な位置まで一つ前の値と比較していく\n\"\"\"\n\nfrom typing import List\n\ndef insertion_sort(numbers: List[int]) -> List[int]:\n len_number = len(numbers)\n for i in range(1, len_number):\n # 先頭から2番目をtempに避難する\n temp = numbers[i]\n # 一つ前の数字\n j = i - 1\n # 一つ前のindexが0より大きいとき and 一つ前のindexが避難させた値より大きいとき\n while j >= 0 and numbers[j] > temp:\n # 空になっているnumbers[j+1]に入れる\n numbers[j+1] = numbers[j]\n # 後ろの値を一つずつ前にずらす\n j -= 1\n\n numbers[j+1] = temp\n \n return numbers\n\n\n\nimport random\nnums = [random.randint(0, 1000) for _ in range(10)]\nprint(insertion_sort(nums))","sub_path":"python/sort/insertion.py","file_name":"insertion.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"556181156","text":"from django.utils.translation import ugettext_lazy as _\nfrom wagtail.wagtailcore.models import Page\nfrom .models import MenuItem\nfrom . import app_settings\n\n\ndef get_attrs_from_context(context, guess_tree_position=True):\n \"\"\"\n Gets a bunch of useful things from the context/request and returns them as\n a tuple for use in most menu tags.\n \"\"\"\n request = context['request']\n site = request.site\n wagtailmenus_vals = context.get('wagtailmenus_vals')\n current_page = wagtailmenus_vals.get('current_page')\n section_root = wagtailmenus_vals.get('section_root')\n ancestor_ids = wagtailmenus_vals.get('current_page_ancestor_ids')\n return (request, site, current_page, section_root, ancestor_ids)\n\n\ndef get_template_names(menu_tag, request, override):\n if override:\n return [override]\n template_names = []\n if app_settings.SITE_SPECIFIC_TEMPLATE_DIRS and getattr(\n request, 'site', None\n ):\n hostname = request.site.hostname\n template_names.extend([\n \"menus/%s/%s/menu.html\" % (hostname, menu_tag),\n \"menus/%s/%s_menu.html\" % (hostname, menu_tag),\n ])\n template_names.append(\"menus/%s/menu.html\" % menu_tag)\n if menu_tag == 'main':\n template_names.append(app_settings.DEFAULT_MAIN_MENU_TEMPLATE)\n elif menu_tag == 'section':\n template_names.append(app_settings.DEFAULT_SECTION_MENU_TEMPLATE)\n elif menu_tag == 'children':\n template_names.append(app_settings.DEFAULT_CHILDREN_MENU_TEMPLATE)\n return template_names\n\n\ndef get_sub_menu_template_names(menu_tag, request, override):\n if override:\n return [override]\n template_names = []\n if app_settings.SITE_SPECIFIC_TEMPLATE_DIRS and getattr(\n request, 'site', None\n ):\n hostname = request.site.hostname\n template_names.extend([\n \"menus/%s/%s/sub_menu.html\" % (hostname, menu_tag),\n \"menus/%s/%s_sub_menu.html\" % (hostname, menu_tag),\n \"menus/%s/sub_menu.html\" % hostname,\n ])\n template_names.extend([\n \"menus/%s/sub_menu.html\" % menu_tag,\n \"menus/%s_sub_menu.html\" % menu_tag,\n app_settings.DEFAULT_SUB_MENU_TEMPLATE,\n ])\n return template_names\n\n\ndef validate_supplied_values(tag, max_levels=None, use_specific=None,\n parent_page=None, menuitem_or_page=None):\n if max_levels is not None:\n if max_levels not in (1, 2, 3, 4, 5):\n raise ValueError(_(\n \"The `%s` tag expects `max_levels` to be an integer value \"\n \"between 1 and 5. Please review your template.\") % tag)\n if use_specific is not None:\n if use_specific not in (0, 1, 2, 3):\n raise ValueError(_(\n \"The `%s` tag expects `use_specific` to be an integer value \"\n \"between 0 and 3. Please review your template.\") % tag)\n if parent_page is not None:\n if not isinstance(parent_page, Page):\n raise ValueError(_(\n \"The `%s` tag expects `parent_page` to be a `Page` instance. \"\n \"A value of type `%s` was supplied.\") %\n (tag, parent_page.__class__))\n if menuitem_or_page is not None:\n if not isinstance(menuitem_or_page, (Page, MenuItem)):\n raise ValueError(_(\n \"The `%s` tag expects `menuitem_or_page` to be a `Page` or \"\n \"`MenuItem` instance. A value of type `%s` was supplied.\") %\n (tag, menuitem_or_page.__class__))\n","sub_path":"wagtailmenus/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"264443512","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nA module to create a psf file from an xyz file.\n\"\"\"\nimport numpy as np\n\nfrom src.calc import general_calc as gen_calc\nfrom src.calc import molecule_utils as mol_utils\n\nfrom src.system import type_checking as type_check\n\n\ndef calc_all_dists(pos1, all_pos, types=False):\n dist = np.linalg.norm(all_pos - pos1, axis=1)\n if types is not False:\n sorting = sorted(zip(dist, np.arange(1, len(dist)+1), types))\n else:\n sorting = sorted(zip(dist, np.arange(1, len(dist)+1)))\n return sorting\n\n\nclass Create_PSF(gen_calc.Calc_Type):\n \"\"\"\n Will create a psf file from\n \"\"\"\n required_metadata = ('atoms_per_molecule', 'number_each_atom', 'bonds',\n 'dihedrals', 'angles', 'atom_types',)\n required_data_types = ('pos', )\n _write_types = ('psf', )\n\n # Need these 3 attributes to create a new variable type\n metadata = {'file_type': 'psf'}\n name = \"Create PSF File\"\n\n def _calc_(self):\n \"\"\"\n Will call the relevant functions to calculate the psf file info.\n\n This will calculate:\n * Bonds => Which atom is bonded to which. We assume elements num of\n bonds are given by the periodic table.\n * Angles => Which elements form the angles are given by the metadata\n * Dihedrals => Which elements form the dihedrals are given by the metadata\n \"\"\"\n self.ats_per_mol = self.metadata['atoms_per_molecule']\n\n self.xyz_data = self.Var.data.get_xyz_data()\n self.cols = self.Var.data.get_xyz_cols(self.metadata['number_each_atom'])\n\n self.each_file_data = []\n for ifile in range(len(self.xyz_data)):\n file_xyz = self.xyz_data[ifile]\n file_cols = self.cols[ifile]\n\n self.natom = len(self.xyz_data[0][0])\n print(np.shape(self.xyz_data))\n self.all_mol_crds = mol_utils.atoms_to_mols(file_xyz, self.ats_per_mol)\n nmol = self.all_mol_crds.shape[1]\n self.mol_col = np.reshape(file_cols[0], (nmol, self.ats_per_mol))\n\n for mol_crd in self.all_mol_crds:\n # Calculate the NN list for 1 molecule\n NN = np.apply_along_axis(calc_all_dists, 1, mol_crd[0], mol_crd[0],\n self.mol_col[0])\n\n # Get the bonding info for the first molecule only. This can be replicated\n # later\n bond_types = self.get_bonding_types(self.metadata['bonds'])\n all_bonds = mol_utils.get_bonding_info(mol_crd[:1], bond_types,\n self.mol_col, self.metadata['atom_types'],\n NN=NN, cutoff=4)\n\n bonds = self.remove_bond_info_dupes(all_bonds[0])\n nbonds = len(bonds)\n\n # Get the angle info\n all_angles = mol_utils.get_topo_info(mol_crd[:1], self.metadata['angles'],\n all_bonds, self.mol_col,\n self.metadata['atom_types'],\n NN=NN)\n angles = self.remove_top_dict_dupes(all_angles[0])\n nangles = len(angles)\n\n # Get the dihedral info\n all_dihedrals = mol_utils.get_topo_info(mol_crd[:1], self.metadata['dihedrals'],\n all_bonds, self.mol_col,\n self.metadata['atom_types'],\n NN=NN)\n dihedrals = self.remove_top_dict_dupes(all_dihedrals[0])\n ndihedrals = len(dihedrals)\n\n self.each_file_data.append(\n {\n 'all_bonds': all_bonds, 'nbonds': nbonds, 'bonds': bonds,\n 'all_angles': all_angles, 'nangles': nangles, 'angles': angles,\n 'all_dihedrals': all_dihedrals, 'ndihedrals': ndihedrals, 'dihedrals': dihedrals,\n }\n )\n self.plot_bond_structure(bonds)\n print(\"\\n\\nINFO:\\nTo see if the bonding looks correct open the bond_struct.png picture!\\n\\n\")\n\n\n def remove_top_dict_dupes(self, top_dict):\n \"\"\"\n Will remove the duplicates from the all angles and dihedrals dictionary.\n\n This will remove any chains of atom indices that are equivalent. E.g:\n if [2, 1, 11] is already in the list of atoms then we can't allow\n [11, 1, 2] (its reverse).\n\n Inputs:\n * top_dict => The dictionary of the topological quantities\n Ouputs:\n Every value in an array where there aren't any items that\n are the reverse of any other item.\n \"\"\"\n all_inds = []\n for iat in top_dict:\n for vals in top_dict[iat]:\n if vals not in all_inds and list(reversed(vals)) not in all_inds:\n all_inds.append(vals)\n\n return np.array(all_inds)\n\n\n def remove_bond_info_dupes(self, all_bonds):\n \"\"\"\n Will remove duplicate bonds from the all_bonds dict\n\n Inputs:\n * all_bonds => The dictionary holding info on all bonds\n \"\"\"\n all_pairs = []\n for i in all_bonds:\n for j in all_bonds[i]:\n pair = min([i, j]), max([i, j])\n if pair not in all_pairs:\n all_pairs.append(pair)\n return np.array(all_pairs)\n\n\n\n def get_bonding_types(self, bond_info):\n \"\"\"\n Will return a dict with every allowed bonding configuration.\n\n Inputs:\n * bond_info => The dict declared in the input parameters\n Outputs:\n bonding types\n \"\"\"\n bonding_types = {}\n for i in bond_info:\n if len(bond_info[i]) == 2:\n if bond_info[i][0] == bond_info[i][1]:\n bonding_types.setdefault(bond_info[i][0],\n []).append(bond_info[i][1])\n else:\n bonding_types.setdefault(bond_info[i][0],\n []).append(bond_info[i][1])\n bonding_types.setdefault(bond_info[i][1],\n []).append(bond_info[i][0])\n else:\n raise SystemExit(\"\\n\\n\\n\\nThe 'BONDS' section should declare how each \"\n + \"atom bonds with other atoms.\\n\\n\"\n + \"To do this you should use the format:\\n\\n\\t\"\n + \"BONDS:\\n\\t1 = \\n\\t\"\n + \"2 = \\n\\t.\\n\\t.\\n\\t.\\n\\n\"\n + \"You haven't declared the correct number of \"\n + \"atom types in the params file, you declared\"\n + f\" {len(bond_info[i])} for var {i}.\")\n return bonding_types\n\n\n def plot_bond_structure(self, bonds, show=False):\n \"\"\"\n Will plot the atoms in a 3D scatter plot with bonds that have been calculated plotted too\n \"\"\"\n import matplotlib.pyplot as plt\n from mpl_toolkits.mplot3d import Axes3D\n fig = plt.figure(figsize=(16,9))\n ax = fig.add_subplot(111, projection=\"3d\")\n\n crds = self.all_mol_crds[0][0]\n cols = [self.metadata['atom_types'][i] for i in self.mol_col[0]]\n masses = np.array([mol_utils.PT_abbrv[i]['atomic_weight'] for i in cols])\n colors = np.array([mol_utils.PT_abbrv[i]['plot_color'] for i in cols])\n\n # Plot coords in a cube space\n max_len = max(np.abs([max(crds[:, 0]) - min(crds[:, 0]),\n max(crds[:, 1]) - min(crds[:, 1]),\n max(crds[:, 2]) - min(crds[:, 2])]))\n min_vals = [min(crds[:, 0]), min(crds[:, 1]), min(crds[:, 2])]\n\n u_mass = np.unique(masses)\n for m in u_mass:\n mask = masses == m\n c = colors[mask][0]\n new_crds = crds[mask]\n ax.plot(new_crds[:, 0], new_crds[:, 1], new_crds[:, 2], 'o',\n color=c, ms=(m**0.3)*5, ls='none')\n\n ax.set_xlim([min_vals[0]-1, min_vals[0]+max_len+1])\n ax.set_ylim([min_vals[1]-1, min_vals[1]+max_len+1])\n ax.set_zlim([min_vals[2]-1, min_vals[2]+max_len+1])\n\n # Now add the bonds\n for bnd in bonds:\n at1, at2 = crds[bnd[0]-1], crds[bnd[1]-1]\n ax.plot([at1[0], at2[0]], [at1[1], at2[1]],\n [at1[2], at2[2]], 'k--')\n\n plt.savefig(\"bond_struct.png\")\n\n def create_atoms_section(self, spaces=10):\n \"\"\"\n Will create the atoms section of the PSF file.\n\n Inputs:\n * space OPTIONAL => The spacing from from the start line to the end of the first int\n Outputs:\n The atoms section as a string\n \"\"\"\n at_counts = {}\n print(self.natom)\n s = f\"{self.natom}\".rjust(spaces) + \" !NATOM\\n\"\n for istep in range(len(self.all_mol_crds)):\n for imol, cols in enumerate(self.mol_col):\n for iat, at in enumerate(cols):\n at_counts[at] = at_counts.setdefault(at, 0) + 1\n at_num = at_counts[at]\n name = f\"{at}{at_num}\".ljust(9)\n at_type = f\"{at}\".ljust(6)\n num = f\"{iat + 1}\".rjust(spaces)\n mass = f\"{mol_utils.PT_abbrv[self.metadata['atom_types'][at]]['atomic_weight']}\".rjust(14)\n s += f\"{num} SYS {imol+1} UNK {name}{at_type}0.000000{mass}\"\n s += \"\\n\"\n\n return s\n\n def create_topo_section(self, inds, inds_in_row, spaces=10):\n \"\"\"\n Will create the bonds, angles, dihedrals etc sections.\n\n Inputs:\n * inds => The atom indices that should be saved in shape (nat_per_mol, N)\n * inds_in_row => The number of entries in 1 row\n * space OPTIONAL => The spacing from from the start line to the end of the first int\n \n Outputs:\n The section text\n \"\"\"\n s = \"\"\n inds = inds.astype(str)\n for i in range(len(inds)):\n if i % inds_in_row == 0: s += \"\\n\"\n for ind in inds[i]:\n s += ind.rjust(spaces)\n return s\n\n\n def create_file_str(self):\n \"\"\"\n Will create the string that can be written as a file.\n\n Outputs:\n The file text\n \"\"\"\n len_start = 10\n\n all_file_txt = []\n for file_data in self.each_file_data:\n bonds, nbonds = file_data['bonds'], file_data['nbonds']\n angles, nangles = file_data['angles'], file_data['nangles']\n dihedrals, ndihedrals = file_data['dihedrals'], file_data['ndihedrals']\n\n # Title\n s = \"PSF\\n\\n\"\n s += \"%s !NTITLE\\n PYTHON UTILITY CREATED PSF FILE\\n\\n\" % (\"1\".rjust(len_start))\n \n # Atoms section\n s += self.create_atoms_section(len_start)\n\n # Bonds section\n s += \"\\n\" + f\"{nbonds}\".rjust(len_start) +\" !NBOND: bonds\\n\"\n s += self.create_topo_section(bonds, 4, len_start).lstrip(\"\\n\")\n\n # Angles section\n s += \"\\n\\n\" + f\"{nangles}\".rjust(len_start) +\" !NTHETA: angles\\n\"\n s += self.create_topo_section(angles, 3, len_start).lstrip(\"\\n\")\n\n # Dihedrals section\n s += \"\\n\\n\" + f\"{ndihedrals}\".rjust(len_start) +\" !NPHI: dihedrals\\n\"\n s += self.create_topo_section(dihedrals, 2, len_start).lstrip(\"\\n\")\n\n # The other parts\n for i in (\"!NIMPHI: impropers\", \"!NDON: donors\", \"!NACC: acceptors\", \"!NNB\", \"!NCRTERM: cross-terms\"):\n s += \"\\n\\n\" + \"0\".rjust(len_start) + f\" {i}\"\n \n all_file_txt.append(s)\n\n return all_file_txt\n\n\n def __str__(self):\n \"\"\"\n Return the file txt\n \"\"\"\n return \"\\n\\n\".join([f\"File {i}:\"+\"\\n\\n\" + f\"{txt}\" for i, txt in enumerate(self.create_file_str())])\n","sub_path":"src/calc/create_psf.py","file_name":"create_psf.py","file_ext":"py","file_size_in_byte":12555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"364398173","text":"import pickle\nimport numpy as np\nimport pandas as pd\nimport sys\nsys.path.insert(1, '../src/MyAIGuide/data')\n\nfrom fitbitDataGatheredFromWebExport import fitbitDataGatheredFromWebExport\nfrom movesDataGatheredFromWebExport import movesDataGatheredFromWebExport\nfrom googleFitGatheredFromWebExport import googleFitGatheredFromWebExport\nfrom storePainIntensitiesForParticipant1 import storePainIntensitiesForParticipant1\nfrom retrieve_mentalstate_participant1 import retrieve_mentalstate_participant1\nfrom storeSportDataParticipant1 import storeSportDataParticipant1\nfrom storeManicTimeBlankScreen import storeManicTimeBlankScreen\nfrom storeManicTime import storeManicTime\n\n# Creation of the dataframe where everything will be stored\ni = pd.date_range(\"2015-11-19\", periods=1700, freq=\"1D\")\nsLength = len(i)\nempty = pd.Series(np.zeros(sLength)).values\nd = {\n \"steps\": empty,\n \"denivelation\": empty,\n \"kneePain\": empty,\n \"handsAndFingerPain\": empty,\n \"foreheadAndEyesPain\": empty,\n \"forearmElbowPain\": empty,\n \"aroundEyesPain\": empty,\n \"shoulderNeckPain\": empty,\n \"movesSteps\": empty,\n \"googlefitSteps\": empty,\n \"generalmood\": empty,\n \"walk\": empty,\n \"roadBike\": empty,\n \"mountainBike\": empty,\n \"swimming\": empty,\n \"surfing\": empty,\n \"climbing\": empty,\n \"viaFerrata\": empty,\n \"alpiSki\": empty,\n \"downSki\": empty,\n \"climbingDenivelation\": empty,\n \"climbingMaxEffortIntensity\": empty,\n \"climbingMeanEffortIntensity\": empty,\n \"swimmingKm\": empty,\n \"manicTimeC1\": empty,\n \"manicTimeC2\": empty,\n \"manicTimeC3\": empty,\n \"manicTimeT\": empty,\n \"manicTimeBlankScreenC1\": empty,\n \"manicTimeBlankScreenC2\": empty,\n \"manicTimeBlankScreenC3\": empty,\n \"manicTimeBlankScreenT\": empty,\n \"manicTimeDelta\": empty,\n}\ndata = pd.DataFrame(data=d, index=i)\n\n# Storing fitbit data in dataframe\nfname = \"../data/raw/ParticipantData/Participant1PublicOM/dailyFitBitPerMonth/\"\ndata = fitbitDataGatheredFromWebExport(fname, data)\n\n# Storing moves data in dataframe\nfname = \"../data/raw/ParticipantData/Participant1PublicOM/MovesAppData/yearly/summary/\"\ndata = movesDataGatheredFromWebExport(fname, data)\n\n# Storing google fit data in dataframe\nfilename1 = \"../data/raw/ParticipantData/Participant1PublicOM/GoogleFitData/smartphone1/dailyAggregations/dailySummaries.csv\"\nfilename2 = \"../data/raw/ParticipantData/Participant1PublicOM/GoogleFitData/smartphone2/dailyAggregations/dailySummaries.csv\"\ndata = googleFitGatheredFromWebExport(filename1, filename2, data)\n\n# Storing pain intensities in dataframe\nfilename = \"../data/raw/ParticipantData/Participant1PublicOM/pain.csv\"\ndata = storePainIntensitiesForParticipant1(filename, data)\n\n# Storing mental state in dataframe\nfilename = \"../data/external/moodAndOtherVariables.csv\"\ndata = retrieve_mentalstate_participant1(filename, data)\n\n# Storing sport data in dataframe\nfilename = \"../data/raw/ParticipantData/Participant1PublicOM/sport.csv\"\ndata = storeSportDataParticipant1(filename, data)\n\n# Storing Manic Time data in dataFrame\nfname = \"../data/raw/ParticipantData/Participant1PublicOM/computerUsage/computer\"\nnumberlist = [\"1\", \"2\", \"3\"]\ndata = storeManicTime(fname, numberlist, data)\n\n# Storing Manic Time Blank Screen data in dataframe\nfname = \"../data/raw/ParticipantData/Participant1PublicOM/computerUsage/computer\"\nnumberlist = [\"1\", \"2\", \"3\"]\ndata = storeManicTimeBlankScreen(fname, numberlist, data)\n\n# Create Manic Time Delta Column in dataframe\ndata['manicTimeDelta'] = data['manicTimeT'] - data['manicTimeBlankScreenT'].astype(int)\n\n# Prints the dataframe\npd.set_option('display.max_rows', None)\nprint(data)\n\n# Saving the dataframe in a txt\noutput = open(\"../data/preprocessed/preprocessedDataParticipant1.txt\", \"wb\")\npickle.dump(data, output)\noutput.close()\n","sub_path":"scripts/create_preprocessed_data_participant1.py","file_name":"create_preprocessed_data_participant1.py","file_ext":"py","file_size_in_byte":3789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"107719435","text":"import cs50\n\nwhile True:\n print(\"Enter credit card number: \")\n cc_number = cs50.get_float()\n\n if not cc_number:\n continue\n else:\n break\n\ntemp = cc_number\ni = 0\nsum1 = 0\nsum2 = 0\n\nwhile (temp != 0):\n\n digit = int(temp % 10)\n temp = int(temp / 10)\n\n if (i % 2 == 0):\n sum2 = sum2 + digit\n else:\n temp2 = digit * 2\n if (temp2 < 10):\n sum1 = sum1 + temp2\n\n else:\n sum1 = sum1 + (temp2 % 10) + (temp2 // 10)\n\n i = i + 1\n\n# Check Checksum (Last digit should be 0)\nif ((sum1 + sum2) % 10) != 0:\n print(\"INVALID\")\n\n\ntemp3 = pow(10, (i - 2))\nfirst_digit = cc_number // temp3\n\n# Amex check\nif (i == 15):\n if (first_digit == 34 or first_digit == 37):\n print(\"AMEX\")\n\n\nelif (i == 13 or i == 16):\n\n # MC\n if (first_digit == 51 or\n first_digit == 52 or\n first_digit == 53 or\n first_digit == 54 or\n first_digit == 55):\n print(\"MASTERCARD\")\n\n # VC\n if(first_digit // 10 == 4):\n print(\"VISA\")\n\n\nelse:\n print(\"INVALID\")\n","sub_path":"pset6/credit/credit.py","file_name":"credit.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"428636328","text":"# import socket programming library\nimport socket\nimport math\nimport numpy as np\nfrom threading import Lock\nfrom _thread import *\nfrom Client import worker, create_state, check_worker\nimport threading\nimport json\nimport time\nimport traceback\nfrom Device import Device\nfrom Optimization import Optimization\nimport copy\nimport struct\nfrom multiprocessing import Process, Manager\n\nlock = Lock()\n\n\nclass Controller(threading.Thread, Optimization):\n def __init__(self, selection, opt_delta):\n # self.print_lock = threading.Lock()\n self.clean_cache = None\n self.current_t = None\n self.player = None\n self.selection = selection\n self.opt_delta = opt_delta\n self.full = None\n self.channel_allocation = None\n self.epsilon = None\n self.info = None\n self.s = None\n self.c = []\n self.cache = []\n # self.initial_info()\n self.request = None\n self.finish = None\n self.lock = Lock()\n self.priority = None\n self.number_of_opt = 0\n self.number_of_finished_opt = 0\n self.validation = None\n\n def reset_request_pool(self, number_of_user):\n self.request = [None for n in range(number_of_user)]\n self.finish = [0 for n in range(number_of_user)]\n\n def check_worker(self, doing):\n for n in doing:\n if self.finish[n] != 1:\n return False\n return True\n\n def inital_config(self, player, epsilon, priority=\"energy_reduction\", clean_cache=True, channel_allocation=1, full=False):\n self.player = player\n self.full = full\n self.priority = priority\n self.channel_allocation = channel_allocation\n self.epsilon = epsilon\n self.clean_cache = clean_cache\n\n def initial_info(self, player=None, current_t=None):\n self.current_t = current_t\n job_list = []\n for n in range(self.player.number_of_user):\n self.player.users[n].partition()\n job_list.append(self.player.users[n].DAG.display())\n\n D_n = np.array([self.player.users[n].DAG.D / 1000 for n in range(self.player.number_of_user)]).tolist()\n X_n = np.array([self.player.users[n].remote for n in range(self.player.number_of_user)]).tolist()\n Y_n = np.array([self.player.users[n].local for n in range(self.player.number_of_user)]).tolist()\n user_cpu = np.array([self.player.users[n].freq for n in range(self.player.number_of_user)]).tolist()\n edge_cpu = np.array([self.player.edges[k].freq for k in range(self.player.number_of_edge)]).tolist()\n number_of_chs = np.array([self.player.edges[k].number_of_chs for k in range(self.player.number_of_edge)]).tolist()\n P_max = np.array([self.player.users[n].p_max for n in range(self.player.number_of_user)]).tolist()\n B = np.array([self.player.users[n].local_to_remote_size for n in range(self.player.number_of_user)]).tolist()\n H = np.array(\n [[self.player.users[n].H[k] for k in range(self.player.number_of_edge)] for n in range(self.player.number_of_user)]).tolist()\n configs = [self.player.users[n].config for n in range(self.player.number_of_user)]\n\n self.info = {\n \"current_t\": self.current_t,\n \"clean_cache\": self.clean_cache,\n \"configs\": configs,\n \"tasks\": job_list,\n \"local_only_enabled\": [item.local_only_enabled for item in player.users],\n \"local_only_energy\": [item.local_only_energy for item in player.users],\n \"opt_delta\": self.opt_delta.tolist(),\n \"selection\": self.selection.tolist(),\n \"number_of_edge\": self.player.number_of_edge,\n \"number_of_user\": self.player.number_of_user,\n \"D_n\": D_n,\n \"X_n\": X_n,\n \"Y_n\": Y_n,\n \"user_cpu\": user_cpu,\n \"edge_cpu\": edge_cpu,\n \"number_of_chs\": number_of_chs,\n \"P_max\": P_max,\n \"B\": B,\n \"H\": H,\n \"W\": 2 * math.pow(10, 6),\n \"who\": None,\n \"full\": self.full,\n \"default_channel\": 1,\n \"channel_allocation\": self.channel_allocation,\n \"step\": 0.005,\n \"interval\": 10,\n \"stop_point\": self.epsilon\n }\n\n def optimize_locally(self, info, doing):\n state = create_state(doing, info, self.cache)\n processes = list()\n for n in doing:\n info[\"who\"] = Device(info[\"user_cpu\"][n], n, info[\"H\"][n]\n , transmission_power=info[\"P_max\"][n], epsilon=info[\"stop_point\"])\n info[\"who\"].inital_DAG(n, info[\"tasks\"][n], info[\"D_n\"][n], info[\"D_n\"][n])\n info[\"who\"].local_only_execution()\n info[\"who\"].config = info[\"configs\"][n]\n x = Process(target=worker, args=(copy.deepcopy(info), state))\n x.start()\n processes.append(x)\n for process in processes:\n process.join()\n\n def run(self, port=12345):\n host = \"\"\n port = port\n self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.s.bind((host, port))\n self.s.listen(5)\n while True:\n try:\n c, addr = self.s.accept()\n self.c.append(c)\n start_new_thread(self.client_threaded, (c,))\n print(\"connected to \", addr)\n if len(self.c) == 2:\n break\n except Exception as e:\n break\n\n def close(self):\n for c in self.c:\n try:\n message = \"close\"\n self.send_msg(c, message.encode('ascii'))\n c.close()\n except socket.error:\n pass\n\n def send_msg(self, c, msg):\n # Prefix each message with a 4-byte length (network byte order)\n msg = struct.pack('>I', len(msg)) + msg\n c.sendall(msg)\n\n def notify_all(self):\n # print(\"sending computing requests...\")\n for c in self.c:\n try:\n self.info[\"who\"] = None\n json_data = json.dumps(self.info).encode(\"ascii\")\n self.send_msg(c, json_data)\n except socket.error:\n pass\n # print(\"sending computing requests...Done!\")\n\n def client_threaded(self, c):\n message = \"start_opt\"\n self.send_msg(c, message.encode('ascii'))\n while True:\n try:\n data = c.recv(5024)\n str_data = str(data.decode('ascii'))\n if str_data[0] != 'm':\n result = json.loads(str(data.decode('ascii')))\n request = result[\"req\"]\n doing = result[\"doing\"]\n # print(\"request\", request)\n # message = \"waiting\"\n # self.send_msg(c, message.encode('ascii'))\n self.lock.acquire()\n for n in doing:\n self.request[n] = request[n]\n self.finish[n] = 1\n self.lock.release()\n except:\n pass\n","sub_path":"MOBIHOC/Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":7151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"590575912","text":"first_number = int(input())\nsecond_number = int(input())\n\nfor current_number in range(first_number, second_number + 1):\n odd_digit_sum = 0\n even_digit_sum = 0\n current_number_as_string = str(current_number)\n for index, digit in enumerate(current_number_as_string):\n if index % 2 == 0:\n odd_digit_sum += int(digit)\n else:\n even_digit_sum += int(digit)\n if odd_digit_sum == even_digit_sum:\n print(current_number, end=\" \")\n\n\n\n\n\n\n\n","sub_path":"6.Nested_loops/Exercise/02.1 Equal Sums Even Odd Position.py","file_name":"02.1 Equal Sums Even Odd Position.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"310228465","text":"#!/usr/bin/env python\n\n\"\"\"\ntrain_SVM.py\n \nVARPA, University of Coruna\nMondejar Guerra, Victor M.\n23 Oct 2017\n\"\"\"\n\nfrom load_MITBIH import *\nfrom evaluation_AAMI import *\n\nimport sklearn\nfrom sklearn.externals import joblib\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn import svm\nimport time\n\n# Merge the OVO probs in final predictions.\n# N = number of classes\n# M = (N * (N-1))/ 2 OVO pairs\ndef voting_ovo(probs):\n predictions = np.zeros(len(probs))\n class_p = [0, 0, 0, 1, 1, 2]\n class_n = [1, 2, 3, 2, 3, 3]\n for p in range(len(probs)):\n #for j in range(len(p)):\n # prob_sig[j] = (1 / (1 + np.exp(-p[j]))))\n counter = np.zeros(4)\n for i in range(len(probs[p])):\n counter[class_p[i]] = counter[class_p[i]] + (1 / (1 + np.exp(-probs[p,i])))\n counter[class_n[i]] = counter[class_n[i]] + (1 / (1 + np.exp(probs[p,i])))\n\n predictions[p] = np.argmax(counter)\n\n return predictions\n\ndef create_svm_model_name(model_svm_path, winL, winR, do_preprocess, \n use_RR, norm_RR, compute_morph, use_weight_class, delimiter):\n\n if do_preprocess:\n model_svm_path = model_svm_path + delimiter + 'rm_bsln'\n \n if use_RR:\n model_svm_path = model_svm_path + delimiter + 'RR'\n \n if norm_RR:\n model_svm_path = model_svm_path + delimiter + 'norm_RR'\n \n if 'wavelets' in compute_morph:\n model_svm_path = model_svm_path + delimiter + 'wvlt'\n\n if 'HOS' in compute_morph:\n model_svm_path = model_svm_path + delimiter + 'HOS'\n\n if 'myMorph' in compute_morph:\n model_svm_path = model_svm_path + delimiter + 'myMorph'\n\n if use_weight_class:\n model_svm_path = model_svm_path + delimiter + 'weighted'\n\n return model_svm_path\n\ndef main(winL=90, winR=90, do_preprocess=True, use_weight_class=True, \n maxRR=True, use_RR=True, norm_RR=True, compute_morph={''}):\n print(\"Runing train_SVM.py!\")\n\n db_path = '/home/mondejar/dataset/ECG/mitdb/m_learning/'\n \n # Load train data \n [tr_features, tr_labels] = load_mit_db('DS1', winL, winR, do_preprocess,\n maxRR, use_RR, norm_RR, compute_morph, db_path)\n # np.savetxt('mit_db/DS1_labels.csv', tr_labels.astype(int), '%.0f') \n # Do oversampling?\n\n # Normalization of the input data\n # scaled: zero mean unit variance ( z-score )\n scaler = StandardScaler()\n scaler.fit(tr_features)\n tr_features_scaled = scaler.transform(tr_features)\n # NOTE for cross validation use: \n # pipeline = Pipeline([('transformer', scalar), ('estimator', clf)])\n # instead of \"StandardScaler()\"\n\n ##############################\n # Train SVM model\n C_value = 0.001\n\n model_svm_path = db_path + 'svm_models_py/rbf'\n model_svm_path = create_svm_model_name(model_svm_path, winL, winR, \n do_preprocess, use_RR, norm_RR, compute_morph, use_weight_class, '_')\n model_svm_path = model_svm_path + '_C_' + str(C_value) + '.joblib.pkl'\n\n print(\"Training model on MIT-BIH DS1: \" + model_svm_path + \"...\")\n\n if os.path.isfile(model_svm_path):\n # Load the trained model!\n svm_model = joblib.load(model_svm_path)\n\n else:\n svm_model = svm.SVC(C=C_value, kernel='rbf', degree=3, gamma='auto', \n coef0=0.0, shrinking=True, probability=True, tol=0.001, \n cache_size=200, class_weight='balanced', verbose=False, \n max_iter=-1, decision_function_shape='ovo', random_state=None)\n \n # Let's Train!\n\n start = time.time()\n svm_model.fit(tr_features_scaled, tr_labels) \n end = time.time()\n # TODO assert that the class_ID appears with the desired order, \n # with the goal of ovo make the combinations properly\n print(\"Trained completed!\\n\\t\" + model_svm_path + \"\\n \\\n \\tTime required: \" + str(format(end - start, '.2f')) + \" sec\" )\n\n # Export model: save/write trained SVM model\n joblib.dump(svm_model, model_svm_path)\n \n ##############################\n ## Test SVM model\n print(\"Testing model on MIT-BIH DS2: \" + model_svm_path + \"...\")\n\n [eval_features, eval_labels] = load_mit_db('DS2', winL, winR, do_preprocess, \n maxRR, use_RR, norm_RR, compute_morph, db_path)\n #np.savetxt('mit_db/DS2_labels.csv', eval_labels.astype(int), '%.0f') \n\n # Normalization of the input data\n # scaled: zero mean unit variance ( z-score )\n eval_features_scaled = scaler.transform(eval_features)\n\n # Let's test new data!\n prob_ovo = svm_model.decision_function(eval_features_scaled)\n predict_ovo = voting_ovo(prob_ovo)\n\n #predicts_log_proba = svm_model.predict_log_proba(eval_features_scaled)\n #predicts_proba = svm_model.predict_proba(eval_features_scaled)\n\n #predicts = svm_model.predict(eval_features_scaled)\n\n print(\"Evaluation\")\n perf_measures = compute_AAMI_performance_measures(predict_ovo, eval_labels)\n \n perf_measures_path = create_svm_model_name('results', winL, winR, do_preprocess, \n use_RR, norm_RR, compute_morph, use_weight_class, '/')\n # Write results and also predictions on DS2\n if not os.path.exists(perf_measures_path):\n os.makedirs(perf_measures_path)\n\n write_AAMI_results( perf_measures, perf_measures_path + '/C_' + str(C_value) + \n '_score_Ijk_' + str(format(perf_measures.Ijk, '.2f')) + '.txt')\n \n # Array to .csv\n np.savetxt(perf_measures_path + '/C_' + str(C_value) + \n '_predict_ovo.csv', predict_ovo.astype(int), '%.0f') \n\n print(\"Results writed at \" )\n\n \nif __name__ == '__main__':\n import sys\n\n winL = sys.argv[1]\n winR = sys.argv[2]\n do_preprocess = sys.argv[3]\n use_weight_class = sys.argv[4]\n maxRR = sys.argv[5]\n use_RR = sys.argv[6]\n norm_RR = sys.argv[7]\n \n compute_morph = {''} # 'wavelets', 'HOS', 'myMorph'\n for s in sys.argv[8:]:\n compute_morph.add(s)\n \n main(winL, winR, do_preprocess, use_weight_class, maxRR, use_RR, norm_RR, compute_morph)\n","sub_path":"python/train_SVM.py","file_name":"train_SVM.py","file_ext":"py","file_size_in_byte":6017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"297382451","text":"import numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport csv\nimport matplotlib.pyplot as plt\nimport time\n\nNUM_EPOCHS = 1501\nLEARNING_RATE = 0.01\nMAX_DOCUMENT_LENGTH = 100\nMAX_LABEL = 15\nSEED = 15\nBATCH_SIZE = 128\nNUM_CHARS = 256\n\ntf.logging.set_verbosity(tf.logging.ERROR)\ntf.set_random_seed(SEED)\n\ndef read_data_words():\n \n x_train, y_train, x_test, y_test = [], [], [], []\n\n with open('/content/gdrive/My Drive/CZ4042 Dataset/train_medium.csv', encoding='utf-8') as filex:\n reader = csv.reader(filex)\n for row in reader:\n x_train.append(row[2]) #Uses the first paragraph\n y_train.append(int(row[0]))\n\n with open('/content/gdrive/My Drive/CZ4042 Dataset/test_medium.csv', encoding='utf-8') as filex:\n reader = csv.reader(filex)\n for row in reader:\n x_test.append(row[2]) #Uses the first paragraph \n y_test.append(int(row[0]))\n \n x_train = pd.Series(x_train)\n y_train = pd.Series(y_train)\n x_test = pd.Series(x_test)\n y_test = pd.Series(y_test)\n \n x_train = pd.Series(x_train)\n y_train = pd.Series(y_train)\n x_test = pd.Series(x_test)\n y_test = pd.Series(y_test)\n y_train = y_train.values\n y_test = y_test.values\n \n vocab_processor = tf.contrib.learn.preprocessing.VocabularyProcessor(MAX_DOCUMENT_LENGTH)\n\n x_transform_train = vocab_processor.fit_transform(x_train)\n x_transform_test = vocab_processor.transform(x_test)\n\n x_train = np.array(list(x_transform_train))\n x_test = np.array(list(x_transform_test))\n\n num_words = len(vocab_processor.vocabulary_)\n \n return x_train, y_train, x_test, y_test, num_words\n\ndef genAccLossFig4(epoch, train_loss, train_acc, test_acc, name=''):\n plt.plot(range(len(train_loss)), train_loss, label='train loss')\n plt.plot(range(len(train_acc)), train_acc, label='train acc')\n plt.plot(range(len(test_acc)), test_acc, label='test acc')\n plt.text(len(train_loss), train_loss[-1], \"%.4f\" % train_loss[-1])\n plt.text(len(train_acc), train_acc[-1], \"%.4f\" % train_acc[-1])\n plt.text(len(test_acc), test_acc[-1], \"%.4f\" % test_acc[-1])\n plt.legend()\n plt.title('Word RNN - Accuracy / Loss of Model Iteration:' + str(epoch))\n plt.xlabel('Epochs')\n plt.ylabel('Accuracy/Loss')\n plt.savefig('/content/gdrive/My Drive/CZ4042 Dataset/images/Q4/Q4_Figure1_'+str(epoch)+name+'.png')\n plt.close()\n\nHIDDEN_SIZE = 20\nEMBEDDING_SIZE = 20\n\ndef rnn_words_model(x, num_words, dropout = 0.0):\n\n word_vectors = tf.contrib.layers.embed_sequence(x, vocab_size=num_words, embed_dim=EMBEDDING_SIZE)\n word_list = tf.unstack(word_vectors, axis=1)\n\n cell = tf.nn.rnn_cell.GRUCell(HIDDEN_SIZE)\n\n if dropout > 0:\n cell = tf.contrib.rnn.DropoutWrapper(cell, input_keep_prob=dropout, output_keep_prob=dropout)\n \n\n _, encoding = tf.nn.static_rnn(cell, word_list, dtype=tf.float32)\n\n logits = tf.layers.dense(encoding, MAX_LABEL, activation=None)\n\n return word_list, logits\n\ndef main():\n x_train, y_train, x_test, y_test, num_words = read_data_words()\n\n probability = [0.2, 0.4, 0.6, 0.8]\n\n for prob in probability:\n tf.reset_default_graph()\n\n # Create the model\n x = tf.placeholder(tf.int64, [None, MAX_DOCUMENT_LENGTH])\n y_ = tf.placeholder(tf.int64)\n\n inputs, logits = rnn_words_model(x, num_words, prob)\n\n # Optimizer\n entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=tf.one_hot(y_, MAX_LABEL), logits=logits))\n train_op = tf.train.AdamOptimizer(LEARNING_RATE).minimize(entropy)\n\n # Accuracy\n correct_prediction = tf.cast(tf.equal(tf.argmax(logits, 1), y_), tf.float32)\n accuracy = tf.reduce_mean(correct_prediction)\n\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n\n # training\n train_loss, train_acc, test_acc = [], [], []\n x_len = len(x_train)\n idx = np.arange(x_len)\n\n for epoch in range(NUM_EPOCHS):\n np.random.shuffle(idx)\n x_train, y_train = x_train[idx], y_train[idx]\n\n\n #Mini-batch Training\n for start, end in zip(range(0, len(x_train), BATCH_SIZE), range(BATCH_SIZE, len(x_train), BATCH_SIZE)):\n batch_data = x_train[start:end]\n batch_labels = y_train[start:end]\n sess.run(train_op, feed_dict={x:batch_data, y_:batch_labels})\n\n inputs_, loss_, acc_ = sess.run([inputs, entropy, accuracy], feed_dict={x: x_train, y_: y_train})\n test_acc_ = accuracy.eval(feed_dict={x: x_test, y_: y_test})\n\n train_loss.append(loss_)\n train_acc.append(acc_)\n test_acc.append(test_acc_)\n\n if epoch%100 == 0:\n print('iter: %d, train_loss: %g'%(epoch, train_loss[epoch]))\n\n if epoch%100 == 0:\n genAccLossFig4(epoch, train_loss, train_acc, test_acc, '_'+str(prob))\n pd.DataFrame(train_loss).to_csv('/content/gdrive/My Drive/CZ4042 Dataset/csv/Q5/Q4/Q4train_loss_'+str(epoch)+'_'+str(prob)+'.csv')\n pd.DataFrame(train_acc).to_csv('/content/gdrive/My Drive/CZ4042 Dataset/csv/Q5/Q4/Q4train_acc_'+str(epoch)+'_'+str(prob)+'.csv')\n pd.DataFrame(test_acc).to_csv('/content/gdrive/My Drive/CZ4042 Dataset/csv/Q5/Q4/Q4test_acc_'+str(epoch)+'_'+str(prob)+'.csv')\n \n print(\"End of dropout with %0.1f\" % prob)\n\n print(\"==========END===========\")\n\nif __name__ == '__main__':\n main()","sub_path":"Project 2/Part B Source Codes/Part b_5_word_rnn.py","file_name":"Part b_5_word_rnn.py","file_ext":"py","file_size_in_byte":5253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"168259604","text":"from github import Github\n\nimport os\nimport json\nimport subprocess\nimport pprint\n\nREPOSITORY_SLUG = os.getenv(\"GITHUB_REPOSITORY\")\nevent_name = os.getenv(\"GITHUB_EVENT_NAME\")\nevent_path = os.getenv(\"GITHUB_EVENT_PATH\")\nevent_ref = os.getenv(\"GITHUB_REF\")\nevent_sha = os.getenv(\"GITHUB_SHA\")\nprint(\"REPOSITORY_SLUG: {}\".format(REPOSITORY_SLUG))\nprint(\"event_name: {}\".format(event_name))\nprint(\"event_path: {}\".format(event_path))\nprint(\"event_ref: {}\".format(event_ref))\nprint(\"event_sha: {}\".format(event_sha))\nprint(\"\")\nprint(\"\")\n\ng = Github(os.getenv(\"BOT_GITHUB_TOKEN\"))\nrepo = g.get_repo(REPOSITORY_SLUG)\n\n\ndef print_error(output_str: str):\n print(output_str)\n exit(1)\n\n\nif event_name != \"workflow_run\" and event_name != \"pull_request_review\" and event_name != \"check_suite\":\n print_error(\"Unexpected event_name which triggered this workflow run: {}\".format(event_name))\n\nevent_data = {}\nwith open(os.getenv(\"GITHUB_EVENT_PATH\"), mode=\"r\") as payload:\n event_data = json.load(payload)\n # pprint.pprint(event_data)\n\n\npull_request_number = \"0\"\nif event_name == \"workflow_run\" or event_name == \"check_suite\":\n if len(event_data[event_name][\"pull_requests\"]) != 1:\n print(\"This {} is either connected to several pull requests or none. Nothing to merge.\".format(event_name))\n exit(0)\n pull_request_number = event_data[event_name][\"pull_requests\"][0][\"number\"]\nelif event_name == \"pull_request_review\":\n pull_request_number = event_data[\"pull_request\"][\"number\"]\n\nprint(\"pull_request_number: {}\".format(pull_request_number))\n\nif pull_request_number == \"0\":\n print_error(\"pull_request_number could not be detected in the event payload\")\n\npr = repo.get_pull(pull_request_number)\n\nif not pr.mergeable:\n print(\"According to GitHub the pull request is not mergeable right now. Are there conflicts?\")\n exit(0)\n\npr_latest_commit = pr.head.sha\n\nprint(\"latest commit in pull request: {}\".format(pr_latest_commit))\n\nreviews = pr.get_reviews()\ncollaborators = repo.get_collaborators()\n\nprint(\"all reviews on latest commit from collaborators:\")\n\nprint(\"\")\n\nchanges_requested = False\napprovals_on_latest_commit = 0\napprovals_required = 1\n\nlatest_review_by_collaborators = {}\nfor review in reviews:\n if review.user in collaborators:\n # We only care about APPROVED, CHANGES_REQUESTED and DISMISSED\n if review.state != \"COMMENTED\":\n latest_review_by_collaborators[review.user.login] = review\n\nfor _, review in latest_review_by_collaborators.items():\n # CHANGES_REQUESTED should be always dismissed or changed to an APPROVAL\n # Even if the CHANGES_REQUESTED do not happen on the latest commit,\n # they should be respected\n if review.state == \"CHANGES_REQUESTED\":\n changes_requested = True\n\n if review.commit_id == pr_latest_commit:\n print(\"{}: {} on commit: {}\".format(review.user, review.state, review.commit_id))\n\n if review.state == \"APPROVED\":\n approvals_on_latest_commit = approvals_on_latest_commit + 1\n\nprint(\"\")\nprint(\"\")\nprint(\"approvals_on_latest_commit: {}\".format(approvals_on_latest_commit))\nprint(\"approvals_required: {}\".format(approvals_required))\nprint(\"\")\nprint(\"\")\n\nif changes_requested:\n print(\"The pull request contains at least one request for changes. This has to be addressed first.\")\n exit(0)\n\nif approvals_on_latest_commit < approvals_required:\n print(\"The amount of required approvals are not reached yet.\")\n exit(0)\n\nprint(\"Required approvals reached and no request for changes. Checking latest commit status...\")\nprint(\"\")\n\n# There is a difference in commit statuses and checks\n# Our CI runs are all qualifing as checks\n# Since PyGithub is not yet supporting checks, we have to use something else here\n# https://github.com/PyGithub/PyGithub/issues/1621\n# TODO: Use only PyGithub once it supports checks\n\nchecks = {}\n\n# Read up to 1000 checks\nfor page in range(1, 10):\n checks_api_call = subprocess.run(\n 'curl -H \"Accept: application/vnd.github.v3+json\" https://api.github.com/repos/{}/commits/{}/check-runs?per_page=100&page={}'.format(REPOSITORY_SLUG, pr_latest_commit, page),\n capture_output=True,\n shell=True\n )\n\n checks_string = checks_api_call.stdout.decode(\"utf-8\")\n\n checks.update(json.loads(checks_string))\n\n\nchecks_successful = 0\n# THIS workflow run (auto merge) is currently running, it can't be successful yet\n# Therefore everything has to be successful except one\nchecks_successful_required = checks[\"total_count\"] - 1\n\nfor check in checks[\"check_runs\"]:\n if check[\"status\"] == \"completed\" and check[\"conclusion\"] == \"success\":\n checks_successful = checks_successful + 1\n elif check[\"status\"] == \"in_progress\":\n if check[\"name\"] != \"Auto Merge Pull Requests\":\n print(\"The check {} is still pending. Exiting.\".format(check[\"name\"]))\n exit(0)\n else:\n print(\"Unexpected status {} for check {}. Conclusion {}. Exiting.\".format(check[\"status\"], check[\"name\"], check[\"conclusion\"]))\n print(check)\n exit(0)\n\n\n# checks_successful might be one higher than checks_successful_required\n# there seems to be a dely in the API reponse,\n# so the response might not yet have THIS workflow run in it\nprint(\"checks_successful: {}\".format(checks_successful))\nprint(\"checks_successful_required: {}\".format(checks_successful_required))\nprint(\"\")\n\nif checks_successful < checks_successful_required:\n print(\"Not all checks have passed. More work required 🙂\")\n exit(0)\n\nprint(\"\")\nprint(\"All checks passed. Merging...\")\n\npr.merge(merge_method=\"squash\")\n","sub_path":".github/workflows/auto-merge.py","file_name":"auto-merge.py","file_ext":"py","file_size_in_byte":5605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"357914468","text":"# vi: set shiftwidth=4 tabstop=4 expandtab:\nimport datetime\nimport itertools\nimport collections\n\nRUN_LONG_TESTS = False\n\n\ndef string_to_seat_layout(string):\n return {\n (i, j): s\n for i, line in enumerate(string.splitlines())\n for j, s in enumerate(line)\n }\n\n\ndef seat_layout_to_string(seats):\n m = max(i for i, j in seats.keys())\n n = max(j for i, j in seats.keys())\n return \"\\n\".join(\"\".join(seats[(i, j)] for j in range(n + 1)) for i in range(m + 1))\n\n\ndef get_seat_layout_from_file(file_path=\"day11_input.txt\"):\n with open(file_path) as f:\n return string_to_seat_layout(f.read())\n\n\ndirections = [pos for pos in itertools.product((-1, 0, +1), repeat=2) if pos != (0, 0)]\n\n\ndef get_new_seat_value_1(seat, nb_neigh):\n if seat == \"L\":\n return \"#\" if nb_neigh == 0 else seat\n elif seat == \"#\":\n return \"L\" if nb_neigh >= 4 else seat\n return seat\n\n\ndef get_new_seats1(seats):\n neighbours_count = collections.Counter(\n (x + dx, y + dy)\n for (x, y), seat in seats.items()\n if seat == \"#\"\n for dx, dy in directions\n )\n return {\n pos: get_new_seat_value_1(seat, neighbours_count[pos])\n for pos, seat in seats.items()\n }\n\n\ndef get_new_seat_value_rule2(seat, nb_visible):\n if seat == \"L\":\n return \"#\" if nb_visible == 0 else seat\n elif seat == \"#\":\n return \"L\" if nb_visible >= 5 else seat\n return seat\n\n\ndef get_new_seats2(seats):\n visible_count = collections.Counter()\n for (x, y), seat in seats.items():\n if seat == \"#\":\n for dx, dy in directions:\n for d in itertools.count(start=1):\n pos = x + (d * dx), y + (d * dy)\n seat = seats.get(pos, None)\n if seat != \".\":\n visible_count[pos] += 1\n break\n return {\n pos: get_new_seat_value_rule2(seat, visible_count[pos])\n for pos, seat in seats.items()\n }\n\n\ndef get_nb_seat_on_fixedpoint(seats, func):\n while True:\n new_seats = func(seats)\n if new_seats == seats:\n break\n seats = new_seats\n return sum(seat == \"#\" for seat in seats.values())\n\n\ndef run_tests():\n example1 = string_to_seat_layout(\n \"\"\"L.LL.LL.LL\nLLLLLLL.LL\nL.L.L..L..\nLLLL.LL.LL\nL.LL.LL.LL\nL.LLLLL.LL\n..L.L.....\nLLLLLLLLLL\nL.LLLLLL.L\nL.LLLLL.LL\"\"\"\n )\n example2 = string_to_seat_layout(\n \"\"\"#.##.##.##\n#######.##\n#.#.#..#..\n####.##.##\n#.##.##.##\n#.#####.##\n..#.#.....\n##########\n#.######.#\n#.#####.##\"\"\"\n )\n example3a = string_to_seat_layout(\n \"\"\"#.LL.L#.##\n#LLLLLL.L#\nL.L.L..L..\n#LLL.LL.L#\n#.LL.LL.LL\n#.LLLL#.##\n..L.L.....\n#LLLLLLLL#\n#.LLLLLL.L\n#.#LLLL.##\"\"\"\n )\n example3b = string_to_seat_layout(\n \"\"\"#.LL.LL.L#\n#LLLLLL.LL\nL.L.L..L..\nLLLL.LL.LL\nL.LL.LL.LL\nL.LLLLL.LL\n..L.L.....\nLLLLLLLLL#\n#.LLLLLL.L\n#.LLLLL.L#\"\"\"\n )\n\n assert example2 == get_new_seats1(example1)\n assert example3a == get_new_seats1(example2)\n assert get_nb_seat_on_fixedpoint(example1, get_new_seats1) == 37\n\n assert example2 == get_new_seats2(example1)\n assert example3b == get_new_seats2(example2)\n assert get_nb_seat_on_fixedpoint(example1, get_new_seats2) == 26\n\n\ndef get_solutions():\n seat_layout = get_seat_layout_from_file()\n print(get_nb_seat_on_fixedpoint(seat_layout, get_new_seats1) == 2204)\n if RUN_LONG_TESTS:\n print(get_nb_seat_on_fixedpoint(seat_layout, get_new_seats2) == 1986)\n\n\nif __name__ == \"__main__\":\n RUN_LONG_TESTS = True\n begin = datetime.datetime.now()\n run_tests()\n get_solutions()\n end = datetime.datetime.now()\n print(end - begin)\n","sub_path":"day11.py","file_name":"day11.py","file_ext":"py","file_size_in_byte":3679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"315623004","text":"\"\"\" Model which predicts the set of cards that should be touched by an agent when following an instruction.\n\nClases:\n CardPredictorModel (nn.Module): Given an instruction and environment state, predicts which of the possible card\n combinations should be touched by the agent when executing the instruction.\n\"\"\"\nfrom __future__ import annotations\n\nimport copy\nimport logging\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\nimport torch\nfrom torch import nn\n\nfrom agent import util\nfrom agent.data import partial_observation\nfrom agent.environment import agent_actions\nfrom agent.environment import util as environment_util\nfrom agent.evaluation import distribution_visualizer\nfrom agent.evaluation import plan_metrics\nfrom agent.learning import auxiliary\nfrom agent.learning import batch_util\nfrom agent.learning import sampling\nfrom agent.learning.plan_losses import SpatialSoftmax2d\nfrom agent.model.models import plan_predictor_model\nfrom agent.model.modules import map_distribution_embedder\nfrom agent.model.modules import word_embedder\nfrom agent.model.utilities import initialization\nfrom agent.model.utilities import rnn\nfrom agent.simulation import planner\nfrom agent.simulation import unity_game\n\nif TYPE_CHECKING:\n from typing import Any, Dict, List, Optional, Tuple\n\n from agent.config import evaluation_args\n from agent.config import model_args\n from agent.data import instruction_example\n from agent.evaluation import evaluation_logger\n from agent.environment import state_delta\n from agent.simulation import game\n\n\n\nclass ActionGeneratorModel(nn.Module):\n \"\"\" Module which predicts an action to take given a distribution over hexes.\n\n Args:\n args: model_args.ModelArgs. The model arguments used to create this model.\n \"\"\"\n\n def __init__(self,\n args: model_args.ModelArgs,\n input_vocabulary: List[str],\n auxiliaries: List[auxiliary.Auxiliary],\n load_pretrained: bool = True,\n end_to_end: bool = False):\n super(ActionGeneratorModel, self).__init__()\n self._args: model_args.ModelArgs = args\n self._end_to_end = end_to_end\n\n # If end-to-end, also add in the hex predictor model.\n self._plan_predictor: Optional[plan_predictor_model.PlanPredictorModel] = None\n if self._end_to_end or load_pretrained:\n self._plan_predictor: plan_predictor_model.PlanPredictorModel = plan_predictor_model.PlanPredictorModel(\n args, input_vocabulary, auxiliaries)\n\n self._output_layer = None\n self._rnn = None\n self._action_embedder = None\n\n if self._args.get_decoder_args().use_recurrence():\n self._action_embedder: word_embedder.WordEmbedder = \\\n word_embedder.WordEmbedder(\n self._args.get_decoder_args().get_action_embedding_size(),\n [str(action) for action in agent_actions.AGENT_ACTIONS],\n add_unk=False)\n\n self._rnn: nn.Module = nn.LSTM(self._args.get_decoder_args().get_state_internal_size()\n + self._args.get_decoder_args().get_action_embedding_size(),\n self._args.get_decoder_args().get_hidden_size(),\n self._args.get_decoder_args().get_num_layers(),\n batch_first=True)\n\n # Add a different output layer\n self._output_layer: nn.Module = nn.Linear(\n self._args.get_decoder_args().get_hidden_size()\n + self._args.get_decoder_args().get_state_internal_size(),\n len(agent_actions.AGENT_ACTIONS))\n torch.nn.init.orthogonal_(self._output_layer.weight, torch.nn.init.calculate_gain(\"leaky_relu\"))\n self._output_layer.bias.data.fill_(0)\n\n distribution_num_channels: int = 0\n if self._args.get_decoder_args().use_trajectory_distribution():\n distribution_num_channels += 1\n if self._args.get_decoder_args().use_goal_probabilities():\n distribution_num_channels += 1\n if self._args.get_decoder_args().use_obstacle_probabilities():\n distribution_num_channels += 1\n if self._args.get_decoder_args().use_avoid_probabilities():\n distribution_num_channels += 1\n\n self._map_distribution_embedder: map_distribution_embedder.MapDistributionEmbedder = \\\n map_distribution_embedder.MapDistributionEmbedder(\n distribution_num_channels,\n self._args.get_decoder_args().get_state_internal_size(),\n self._args.get_decoder_args().get_state_internal_size()\n if self._args.get_decoder_args().use_recurrence() else len(\n agent_actions.AGENT_ACTIONS),\n self._args.get_decoder_args().get_crop_size(),\n self._args.get_decoder_args().convolution_encode_map_distributions(),\n self._args.get_decoder_args().use_recurrence())\n\n if load_pretrained:\n if self._args.get_decoder_args().pretrained_generator():\n initialization.load_pretrained_parameters(\n self._args.get_decoder_args().pretrained_action_generator_filepath(),\n module=self)\n if self._args.get_decoder_args().pretrained_plan_predictor():\n initialization.load_pretrained_parameters(\n self._args.get_decoder_args().pretrained_plan_predictor_filepath(),\n module=self._plan_predictor)\n\n def load_pretrained_plan_predictor(self, filepath: str, vocabulary: List[str],\n auxiliaries: List[auxiliary.Auxiliary]):\n assert not self._plan_predictor\n logging.info('Loading pretrained plan predictor: ' + filepath + ' with auxiliaries: %r' % auxiliaries)\n self._plan_predictor: plan_predictor_model.PlanPredictorModel = plan_predictor_model.PlanPredictorModel(\n self._args, vocabulary, auxiliaries)\n initialization.load_pretrained_parameters(filepath, module=self._plan_predictor)\n\n def _encode_and_expand_map_distributions(self,\n goal_probabilities: torch.Tensor,\n trajectory_distributions: torch.Tensor,\n obstacle_probabilities: torch.Tensor,\n avoid_probabilities: torch.Tensor,\n positions: torch.Tensor,\n rotations: torch.Tensor) -> torch.Tensor:\n if self._args.get_state_rep_args().full_observability():\n if goal_probabilities is not None:\n batch_size, _, raw_height, raw_width = goal_probabilities.size()\n else:\n batch_size, _, raw_height, raw_width = trajectory_distributions.size()\n\n num_actions: int = rotations.size(1)\n\n # [1] Expand the trajectories\n expanded_trajectory_distribution = None\n if self._args.get_decoder_args().use_trajectory_distribution():\n # Do the same thing as above.\n expanded_trajectory_distribution = \\\n trajectory_distributions.unsqueeze(4).expand(\n (batch_size, 1, raw_height, raw_width, num_actions)).permute(\n 0, 4, 1, 2, 3).contiguous().view(batch_size * num_actions, 1, raw_height, raw_width)\n\n # Rotate to the current positions.\n map_to_embed = None\n if expanded_trajectory_distribution is not None:\n map_to_embed: torch.Tensor = expanded_trajectory_distribution\n if self._args.get_decoder_args().use_goal_probabilities():\n if map_to_embed is not None:\n map_to_embed = \\\n torch.cat(\n (batch_util.expand_flat_map_distribution(goal_probabilities, num_actions), map_to_embed),\n dim=1)\n else:\n map_to_embed = batch_util.expand_flat_map_distribution(goal_probabilities, num_actions)\n if self._args.get_decoder_args().use_obstacle_probabilities():\n if map_to_embed is not None:\n map_to_embed = \\\n torch.cat((batch_util.expand_flat_map_distribution(obstacle_probabilities, num_actions),\n map_to_embed), dim=1)\n else:\n map_to_embed = batch_util.expand_flat_map_distribution(obstacle_probabilities, num_actions)\n if self._args.get_decoder_args().use_avoid_probabilities():\n if map_to_embed is not None:\n map_to_embed = \\\n torch.cat((batch_util.expand_flat_map_distribution(avoid_probabilities, num_actions),\n map_to_embed), dim=1)\n else:\n map_to_embed = batch_util.expand_flat_map_distribution(avoid_probabilities, num_actions),\n else:\n if goal_probabilities is not None:\n batch_size, num_actions, raw_height, raw_width = goal_probabilities.size()\n else:\n batch_size, num_actions, raw_height, raw_width = trajectory_distributions.size()\n\n # Reshape to be the expanded size.\n def reshape_to_flat(x):\n return x.view((batch_size * num_actions, 1, raw_height, raw_width))\n\n map_to_embed = None\n if trajectory_distributions is not None:\n map_to_embed = reshape_to_flat(trajectory_distributions)\n if goal_probabilities is not None:\n if map_to_embed is not None:\n map_to_embed = torch.cat((reshape_to_flat(goal_probabilities), map_to_embed), dim=1)\n else:\n map_to_embed = reshape_to_flat(goal_probabilities)\n if obstacle_probabilities is not None:\n if map_to_embed is not None:\n map_to_embed = torch.cat((reshape_to_flat(obstacle_probabilities), map_to_embed), dim=1)\n else:\n map_to_embed = reshape_to_flat(obstacle_probabilities)\n if avoid_probabilities is not None:\n if map_to_embed is not None:\n map_to_embed = torch.cat((reshape_to_flat(avoid_probabilities), map_to_embed), dim=1)\n else:\n map_to_embed = reshape_to_flat(avoid_probabilities)\n\n return self._map_distribution_embedder(map_to_embed,\n positions.view(batch_size * num_actions, 2),\n rotations.view(batch_size * num_actions)).view(batch_size,\n num_actions,\n -1)\n\n def _predict_one_action(\n self, action_sequence: List[agent_actions.AgentAction], game_server: game.Game,\n state_distribution: torch.Tensor,\n rnn_state: Optional[Tuple[torch.Tensor,\n torch.Tensor]]) -> Tuple[agent_actions.AgentAction,\n Optional[Tuple[torch.Tensor, torch.Tensor]],\n state_delta.StateDelta]:\n # Deal with the state\n follower = game_server.get_game_info().follower\n current_position = follower.get_position()\n\n # Transform and crop\n embedded_state = \\\n self._map_distribution_embedder(\n state_distribution,\n torch.tensor([[float(current_position.x), float(current_position.y)]]).to(util.DEVICE),\n torch.tensor([follower.get_rotation().to_radians()]).to(util.DEVICE))\n\n new_rnn_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None\n if self._args.get_decoder_args().use_recurrence():\n rnn_input = \\\n self._action_embedder(torch.tensor([self._action_embedder.get_index(str(action_sequence[-1]))],\n dtype=torch.long).to(util.DEVICE))\n\n rnn_input = torch.cat((rnn_input, embedded_state), dim=1)\n\n output, new_rnn_state = self._rnn(rnn_input.unsqueeze(1), rnn_state)\n\n # Predict an action\n action_scores: torch.Tensor = \\\n self._output_layer(torch.cat((output.view(1, -1), embedded_state), dim=1))[0]\n else:\n action_scores: torch.Tensor = embedded_state[0]\n\n predicted_action: agent_actions.AgentAction = sampling.constrained_argmax_sampling(\n nn.functional.softmax(action_scores, dim=0), planner.get_possible_actions(game_server, follower))\n\n resulting_game_state = game_server.execute_follower_action(predicted_action)\n\n return predicted_action, new_rnn_state, resulting_game_state\n\n def _initialize_rnn(self, batch_size: int):\n return (torch.zeros(self._args.get_decoder_args().get_num_layers(),\n batch_size,\n self._args.get_decoder_args().get_hidden_size()).to(util.DEVICE),\n torch.zeros(self._args.get_decoder_args().get_num_layers(),\n batch_size,\n self._args.get_decoder_args().get_hidden_size()).to(util.DEVICE))\n\n def _combine_distributions(self,\n goal_probabilities: torch.Tensor,\n trajectory_distribution: torch.Tensor,\n obstacle_probabilities: torch.Tensor,\n avoid_probabilities: torch.Tensor) -> torch.Tensor:\n # Assumes there is no batch size dimension.\n timestep_map = None\n if self._args.get_decoder_args().use_trajectory_distribution():\n timestep_map: torch.Tensor = trajectory_distribution.unsqueeze(0).unsqueeze(0)\n\n if self._args.get_decoder_args().use_goal_probabilities():\n if timestep_map is not None:\n timestep_map = torch.cat((goal_probabilities.unsqueeze(0).unsqueeze(0), timestep_map), dim=1)\n else:\n timestep_map = goal_probabilities.unsqueeze(0).unsqueeze(0)\n if self._args.get_decoder_args().use_obstacle_probabilities():\n if timestep_map is not None:\n timestep_map = torch.cat((obstacle_probabilities.unsqueeze(0).unsqueeze(0), timestep_map), dim=1)\n else:\n timestep_map = obstacle_probabilities.unsqueeze(0).unsqueeze(0)\n if self._args.get_decoder_args().use_avoid_probabilities():\n if timestep_map is not None:\n timestep_map = torch.cat((avoid_probabilities.unsqueeze(0).unsqueeze(0), timestep_map), dim=1)\n else:\n timestep_map = avoid_probabilities.unsqueeze(0).unsqueeze(0)\n return timestep_map\n\n def _predict_actions_full_observability(\n self, goal_probabilities: torch.Tensor, trajectory_distribution: torch.Tensor,\n obstacle_probabilities: torch.Tensor, avoid_probabilities: torch.Tensor, game_server: game.Game,\n evaluation_arguments: evaluation_args.EvaluationArgs) -> Tuple[List[agent_actions.AgentAction],\n List[state_delta.StateDelta]]:\n\n if evaluation_arguments.visualize_auxiliaries():\n raise NotImplementedError\n\n action_sequence: List[agent_actions.AgentAction] = [agent_actions.AgentAction.START]\n stopped: bool = False\n timestep: int = 0\n\n rnn_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None\n if self._args.get_decoder_args().use_recurrence():\n rnn_state = self._initialize_rnn(1)\n\n resulting_game_state = copy.deepcopy(game_server.get_game_info())\n visited_states: List[state_delta.StateDelta] = [resulting_game_state]\n\n # [1] Combine the map distributions only once.\n timestep_map = self._combine_distributions(goal_probabilities, trajectory_distribution,\n obstacle_probabilities, avoid_probabilities)\n\n while (timestep < evaluation_arguments.get_maximum_generation_length() or\n evaluation_arguments.get_maximum_generation_length() < 0) and not stopped:\n\n predicted_action, rnn_state, resulting_game_state = \\\n self._predict_one_action(action_sequence,\n game_server,\n timestep_map.to(util.DEVICE),\n rnn_state)\n visited_states.append(resulting_game_state)\n\n action_sequence.append(predicted_action)\n if predicted_action == agent_actions.AgentAction.STOP or not game_server.valid_state():\n stopped = True\n\n timestep += 1\n\n return action_sequence[1:], visited_states\n\n def _predict_actions_partial_observability(\n self, example: instruction_example.InstructionExample, game_server: game.Game,\n evaluation_arguments: evaluation_args.EvaluationArgs,\n logger: evaluation_logger.EvaluationLogger) -> Tuple[List[agent_actions.AgentAction],\n List[state_delta.StateDelta],\n partial_observation.PartialObservation]:\n if self._end_to_end and not self._plan_predictor:\n raise ValueError('Action predictor must have a plan predictor if evaluating end-to-end.')\n\n action_sequence: List[agent_actions.AgentAction] = [agent_actions.AgentAction.START]\n stopped: bool = False\n timestep: int = 0\n\n rnn_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None\n if self._args.get_decoder_args().use_recurrence():\n rnn_state = self._initialize_rnn(1)\n\n resulting_game_state = copy.deepcopy(game_server.get_game_info())\n visited_states: List[state_delta.StateDelta] = [resulting_game_state]\n current_observation: partial_observation.PartialObservation = example.get_first_partial_observation()\n\n while (timestep < evaluation_arguments.get_maximum_generation_length() or\n evaluation_arguments.get_maximum_generation_length() < 0) and not stopped:\n\n visible_cards = current_observation.get_card_beliefs()\n all_card_positions = sorted(list(set([visible_card.get_position() for visible_card in visible_cards])))\n if logger.active():\n logger.log('-- #%r at position %r and rotation %r' % (\n timestep, current_observation.get_follower().get_position(),\n current_observation.get_follower().get_rotation()))\n\n logger.log('Goal cards:')\n for goal_card in example.get_touched_cards():\n visibility: str = 'Not visible!' if goal_card.get_position() not in all_card_positions else ''\n logger.log('\\t' + str(goal_card) + '\\t' + visibility)\n\n # Compute the updated timestep map given the most recent partial observation.\n if self._plan_predictor:\n # TODO: everything needs to go through the mask before being passed to the rest of the model.\n # Call the plan predictor.\n predictions = self._plan_predictor.get_predictions(example, current_observation)\n\n avoid_probabilities = None\n if auxiliary.Auxiliary.AVOID_LOCS in predictions:\n avoid_probabilities = predictions[auxiliary.Auxiliary.AVOID_LOCS].squeeze()\n\n goal_probabilities = None\n if auxiliary.Auxiliary.FINAL_GOALS in predictions:\n goal_probabilities = predictions[auxiliary.Auxiliary.FINAL_GOALS].squeeze()\n\n if logger.active():\n logger.log('Card predictions:')\n predicted_positions = sorted(list(set(plan_metrics.get_hexes_above_threshold(\n goal_probabilities, all_card_positions))))\n\n for visible_card in visible_cards:\n if visible_card.get_position() in predicted_positions:\n logger.log('\\t' + str(visible_card))\n logger.log('')\n\n obstacle_probabilities = None\n if auxiliary.Auxiliary.OBSTACLES in predictions:\n obstacle_probabilities = predictions[auxiliary.Auxiliary.OBSTACLES].squeeze()\n\n trajectory_distribution = None\n if auxiliary.Auxiliary.TRAJECTORY in predictions:\n trajectory_distribution = plan_metrics.normalize_trajectory_distribution(\n predictions[auxiliary.Auxiliary.TRAJECTORY]).squeeze()\n\n if logger.active():\n for believed_card in current_observation.get_card_beliefs():\n card_position = believed_card.get_position()\n logger.log(str(believed_card) + '\\t' + '{0:.2f}'.format(100. * goal_probabilities[\n card_position.x][card_position.y]) + '\\t' + '{0:.2f}'.format(\n 100. * avoid_probabilities[card_position.x][card_position.y]))\n\n else:\n\n # Note: when training with gold distribution inputs, if the agent gets off the path,\n # the old path distribution isn't useful whereas when training end-to-end it should be updated wrt. the\n # agent's current path distribution.\n # TODO: Everything needs to go through the mask\n trajectory_distribution = torch.tensor(example.get_correct_trajectory_distribution(\n self._args.get_decoder_args().weight_trajectory_by_time(),\n full_observability=False,\n observed_positions=current_observation.currently_observed_positions())).float()\n\n goal_probabilities = torch.zeros(environment_util.ENVIRONMENT_WIDTH, environment_util.ENVIRONMENT_DEPTH)\n avoid_probabilities = torch.zeros(environment_util.ENVIRONMENT_WIDTH,\n environment_util.ENVIRONMENT_DEPTH)\n target_cards = example.get_touched_cards()\n for believed_card in current_observation.get_card_beliefs():\n card_position = believed_card.get_position()\n if believed_card in target_cards:\n goal_probabilities[card_position.x][card_position.y] = 1.\n elif card_position != example.get_initial_state().follower.get_position():\n avoid_probabilities[card_position.x][card_position.y] = 1.\n\n # Obstacle probabilities\n obstacle_probabilities = np.zeros(\n (environment_util.ENVIRONMENT_WIDTH, environment_util.ENVIRONMENT_DEPTH))\n for pos in sorted(example.get_obstacle_positions()):\n assert pos not in example.get_visited_positions()\n obstacle_probabilities[pos.x][pos.y] = 1.\n state_mask = np.zeros((environment_util.ENVIRONMENT_WIDTH, environment_util.ENVIRONMENT_DEPTH))\n for viewed_position in current_observation.lifetime_observed_positions(\n self._args.get_state_rep_args().get_observation_memory_size()):\n state_mask[viewed_position.x][viewed_position.y] = 1.\n obstacle_probabilities = torch.tensor(obstacle_probabilities * state_mask).float()\n\n if evaluation_arguments.visualize_auxiliaries():\n # Send the auxiliaries\n assert isinstance(game_server, unity_game.UnityGame)\n distribution_visualizer.visualize_probabilities(goal_probabilities.numpy(),\n trajectory_distribution.numpy(),\n obstacle_probabilities.numpy(),\n avoid_probabilities.numpy(),\n game_server)\n\n timestep_map = self._combine_distributions(goal_probabilities, trajectory_distribution,\n obstacle_probabilities,\n avoid_probabilities)\n\n predicted_action, rnn_state, resulting_game_state = \\\n self._predict_one_action(action_sequence,\n game_server,\n timestep_map.to(util.DEVICE),\n rnn_state)\n logger.log('Predicted action: %r' % predicted_action)\n visited_states.append(resulting_game_state)\n\n current_observation = partial_observation.update_observation(current_observation, resulting_game_state)\n\n action_sequence.append(predicted_action)\n if predicted_action == agent_actions.AgentAction.STOP or not game_server.valid_state():\n stopped = True\n\n timestep += 1\n\n return action_sequence[1:], visited_states, current_observation\n\n def load(self, save_file: str) -> None:\n \"\"\" Loads model parameters from a specified filename.\n\n Arguments:\n save_file: str. The file to load from.\n \"\"\"\n self.load_state_dict(torch.load(save_file, map_location=util.DEVICE))\n\n def save(self, save_file: str) -> None:\n \"\"\" Saves the model parameters to a specified location.\n\n Args:\n save_file: str. The location to save to.\n \"\"\"\n torch.save(self.state_dict(), save_file)\n\n def batch_inputs(self, examples: List[instruction_example.InstructionExample]) -> List[torch.Tensor]:\n \"\"\" Batches the examples into inputs for the network.\n\n Arguments:\n examples: List[Example]. The examples to batch.\n \"\"\"\n # INPUT BATCHING PREPARATION\n action_lengths_tensor: torch.Tensor = None\n action_index_tensor: torch.Tensor = None\n\n # [0] Batch the action sequences (if applicable)\n if self._args.get_decoder_args().use_recurrence():\n action_index_tensor, action_lengths_tensor = batch_util.batch_action_sequences(examples,\n self._action_embedder)\n\n # [1] Get the gold distributions\n max_action_sequence_length = max([len(example.get_state_deltas()) for example in examples]) + 1\n\n batched_map_components: List[torch.Tensor] = \\\n batch_util.batch_map_distributions(examples,\n environment_util.ENVIRONMENT_WIDTH,\n environment_util.ENVIRONMENT_DEPTH,\n self._args.get_decoder_args().weight_trajectory_by_time(),\n self._args.get_state_rep_args().full_observability(),\n max_action_sequence_length,\n self._args.get_state_rep_args().get_observation_memory_size())\n\n # [2] Get the rotations\n positions, rotations = batch_util.batch_agent_configurations(examples, max_action_sequence_length)\n\n # This has eight elements so far: the four GOLD distributions, and all positions/rotations and actions.\n tensors: List[torch.Tensor] = list(batched_map_components[:-1]) + [positions,\n rotations,\n action_lengths_tensor,\n action_index_tensor]\n\n # [3] If the model is end to end, also batch the environment information.\n if self._end_to_end:\n if self._args.get_state_rep_args().full_observability():\n tensors = tensors \\\n + self._plan_predictor.batch_inputs([(example, None) for example in examples], True) \\\n + [batched_map_components[-1]]\n else:\n # This includes all static information for every instruction.\n # - Instruction indices/lengths.\n # - Initial position/rotation of the follower.\n # - Static environment information, including locations of props and terrain. This MUST be masked\n # later.\n static_batched_tensors: List[torch.Tensor] = self._plan_predictor.batch_inputs(\n [(example, None) for example in examples], True, compute_dynamic_tensors=False)[:13]\n\n # Stacks dynamic information about the environment:\n # - Sequence length of N is the number of types of input tensors\n # - Individual sequence length of M is the batch size\n # - First dimension of each tensor is K_m, the action sequence length K of the mth example. This\n # should be action_lengths_tensor - 1 across all examples.\n # This keeps track only of information that will change as the agent moves, e.g., card properties,\n # the observability mask, and the leader's location.\n stacked_dynamic_information: List[List[torch.Tensor]] = list()\n\n for i, example in enumerate(examples):\n # First dimension here is the \"batch size\", in this case the sequence length.\n batched_example_tensors: List[torch.Tensor] = self._plan_predictor.batch_inputs(\n [(example, observation) for observation in example.get_partial_observations()], True,\n compute_static_tensors=False)[4:]\n\n if i == 0:\n stacked_dynamic_information = [[tensor] for tensor in batched_example_tensors]\n else:\n for j in range(len(stacked_dynamic_information)):\n stacked_dynamic_information[j].append(batched_example_tensors[j])\n\n concat_dynamic_information = list()\n for tensor_type in stacked_dynamic_information:\n concat_dynamic_information.append(torch.cat(tuple(tensor_type)))\n\n # concat_plan_inputs is of length N, with tensors of size \\sum K_m for all m examples x 25 x 25.\n assert concat_dynamic_information[0].size(0) == torch.sum(action_lengths_tensor - 1)\n\n # Add static information (instruction, initial position/rotation, static props), dynamic information\n # (cards, leader, observability), and card mask.\n tensors = tensors + static_batched_tensors + concat_dynamic_information + [batched_map_components[-1]]\n\n device_tensors = []\n for tensor in tensors:\n if tensor is not None:\n device_tensors.append(tensor.to(util.DEVICE))\n else:\n device_tensors.append(None)\n\n return device_tensors\n\n def forward(self, *args) -> Tuple[torch.Tensor, Dict[auxiliary.Auxiliary, torch.Tensor]]:\n \"\"\" Forward pass for the CardPredictorModel.\n\n B = batch size\n L_in = maximum input sequence length\n V_in = vocabulary size of input\n C_static = number of static channels in the environment\n C_dynamic = number of dynamic states in the environment\n H = height of the environment\n W = width of the environment\n \"\"\"\n args: List[torch.Tensor] = list(args)\n\n # First, if training end-to-end, get the predicted distributions\n auxiliary_predictions: Dict[auxiliary.Auxiliary, torch.Tensor] = dict()\n if self._end_to_end:\n # Predict card and trajectory distributions (and any other auxiliaries) using the hex predictor\n card_mask: torch.Tensor = args[-1]\n\n action_lengths = None\n\n # If partial observability, need to stack things so the forward pass on the plan predictor is efficient.\n if not self._args.get_state_rep_args().full_observability():\n # Subtract 1 because these are one extra due to the START token.\n action_lengths = (args[6] - 1).tolist()\n new_card_mask = list()\n for i, length in enumerate(action_lengths):\n new_card_mask.append(card_mask[i][0:length])\n card_mask = torch.cat(tuple(new_card_mask)).unsqueeze(1)\n\n auxiliary_predictions = self._plan_predictor(*args[8:-1], action_sequence_lengths=action_lengths)\n\n # Card distributions should be put through a sigmoid and masked.\n goal_probabilities = None\n if auxiliary.Auxiliary.FINAL_GOALS in auxiliary_predictions:\n goal_probabilities = torch.sigmoid(auxiliary_predictions[auxiliary.Auxiliary.FINAL_GOALS]) * card_mask\n\n avoid_probabilities = None\n if auxiliary.Auxiliary.AVOID_LOCS in auxiliary_predictions:\n # Put through a sigmoid and a mask.\n avoid_probabilities = torch.sigmoid(auxiliary_predictions[auxiliary.Auxiliary.AVOID_LOCS]) * card_mask\n\n # Normalize the trajectory.\n trajectory_distributions = None\n if auxiliary.Auxiliary.TRAJECTORY in auxiliary_predictions:\n trajectory_distributions = plan_metrics.normalize_trajectory_distribution(\n auxiliary_predictions[auxiliary.Auxiliary.TRAJECTORY])\n\n obstacle_probabilities = None\n if auxiliary.Auxiliary.OBSTACLES in auxiliary_predictions:\n # Need to put this through a sigmoid.\n obstacle_probabilities = torch.sigmoid(auxiliary_predictions[auxiliary.Auxiliary.OBSTACLES])\n\n # Need to reshape the inputs to the next part of the model so that it is back to batch x seq_len x ...\n if action_lengths:\n def reshape_and_pad(prediction: torch.Tensor):\n # prediction is sum of K_m x ...\n new_tensor: List[torch.Tensor] = list()\n start_index: int = 0\n for action_length in action_lengths:\n prediction_slice: torch.Tensor = prediction[start_index:start_index + action_length]\n\n # Pad it with zeroes if the prediction. Add one to the padding length because there needs to\n # be an empty dimension at the end.\n padding: torch.Tensor = torch.zeros(tuple([max(action_lengths) - action_length + 1] + list(\n prediction[0].size()))).to(util.DEVICE)\n prediction_slice = torch.cat((prediction_slice, padding))\n start_index += action_length\n\n new_tensor.append(prediction_slice)\n return torch.cat(tuple(new_tensor), 1).permute(1, 0, 2, 3).contiguous()\n goal_probabilities = reshape_and_pad(goal_probabilities)\n avoid_probabilities = reshape_and_pad(avoid_probabilities)\n trajectory_distributions = reshape_and_pad(trajectory_distributions)\n obstacle_probabilities = reshape_and_pad(obstacle_probabilities)\n\n else:\n # Using the gold distributions\n trajectory_distributions: torch.Tensor = args[0]\n goal_probabilities: torch.Tensor = args[1]\n obstacle_probabilities: torch.Tensor = args[2]\n avoid_probabilities: torch.Tensor = args[3]\n\n embedded_state = self._encode_and_expand_map_distributions(goal_probabilities,\n trajectory_distributions,\n obstacle_probabilities,\n avoid_probabilities,\n args[4], # position\n args[5]) # rotation\n\n if self._args.get_decoder_args().use_recurrence():\n # The last element (sequence-wise) for action_embeddings and embedded_state don't matter -- this is the\n # embedding of the STOP token and the last environment state (the same as second to last because STOP\n # results in the same environment state). Loss is not computed over the final output of the RNN.\n #\n # In other words, the ith item represents the embedding of the token generated in step i-1 and\n # the embedding of the world state at time i.\n\n action_embeddings: torch.Tensor = self._action_embedder(args[7]) # action indices\n\n # args[7] is action lengths\n rnn_outputs = rnn.fast_run_rnn(args[6], torch.cat((action_embeddings, embedded_state), dim=2), self._rnn)\n\n return self._output_layer(torch.cat((rnn_outputs, embedded_state), dim=2)), auxiliary_predictions\n\n # If not using recurrence, these are already the action scores.\n return embedded_state, auxiliary_predictions\n\n def get_predictions(self,\n example: instruction_example.InstructionExample,\n game_server: game.Game,\n evaluation_arguments: evaluation_args.EvaluationArgs,\n logger: evaluation_logger.EvaluationLogger,\n goal_probabilities: torch.Tensor = None,\n trajectory_distribution: torch.Tensor = None,\n obstacle_probabilities: torch.Tensor = None,\n avoid_probabilities: torch.Tensor = None) -> Tuple[\n List[agent_actions.AgentAction], Dict[auxiliary.Auxiliary, torch.Tensor],\n List[state_delta.StateDelta], Optional[partial_observation.PartialObservation]]:\n \"\"\" Gets predictions for a model doing inference (i.e., not gold forcing).\n\n Arguments:\n example: Example. The example to get outputs for.\n game_server: Game. The game server to use and query during inference.\n evaluation_arguments: EvalArgs. The arguments for evaluation.\n goal_probabilities: torch.Tensor. An optional distribution over cards.\n trajectory_distribution: torch.Tensor. An optional distribution over trajectories.\n obstacle_probabilities: torch.Tensor. An optional distribution over impassable locations.\n avoid_probabilities: torch.Tensor. An optional distribution over locations to avoid.\n logger: evaluation_logger.EvaluationLogger. A logger for logging evaluation results.\n \"\"\"\n if evaluation_arguments is None:\n raise ValueError('Evaluation arguments must be passed if providing a game server.')\n\n auxiliary_predictions: Dict[auxiliary.Auxiliary, Any] = dict()\n last_observation: partial_observation.PartialObservation = None\n\n if self._args.get_state_rep_args().full_observability():\n # TODO: Use logger for full observability.\n\n # If full observability, first compute the distributions, then use them to compute the action sequence.\n if trajectory_distribution is None:\n if self._end_to_end:\n # Outputs of this should be masked if necessary.\n assert isinstance(self._plan_predictor, plan_predictor_model.PlanPredictorModel)\n auxiliary_predictions = self._plan_predictor.get_predictions(example)\n\n avoid_probabilities = None\n if auxiliary.Auxiliary.AVOID_LOCS in auxiliary_predictions:\n # This has already gone through sigmoid (and mask if masked).\n avoid_probabilities = auxiliary_predictions[auxiliary.Auxiliary.AVOID_LOCS].unsqueeze(1)\n\n # These need to be normalized -- hex_predictor does not return normalized trajectories.\n trajectory_distribution = None\n if auxiliary.Auxiliary.TRAJECTORY in auxiliary_predictions:\n trajectory_distribution = \\\n SpatialSoftmax2d()(\n # 1 x 25 x 25\n auxiliary_predictions[auxiliary.Auxiliary.TRAJECTORY]).unsqueeze(1)\n\n # These are already masked and put through a sigmoid.\n goal_probabilities = auxiliary_predictions[auxiliary.Auxiliary.FINAL_GOALS].unsqueeze(1)\n\n obstacle_probabilities = None\n if auxiliary.Auxiliary.OBSTACLES in auxiliary_predictions:\n # This is already put through a sigmoid.\n obstacle_probabilities = auxiliary_predictions[\n auxiliary.Auxiliary.OBSTACLES].unsqueeze(1)\n else:\n (trajectory_distribution,\n goal_probabilities,\n obstacle_probabilities,\n avoid_probabilities,\n _) = batch_util.batch_map_distributions([example],\n environment_util.ENVIRONMENT_WIDTH,\n environment_util.ENVIRONMENT_DEPTH,\n self._args.get_decoder_args().weight_trajectory_by_time())\n\n if evaluation_arguments.visualize_auxiliaries():\n if not isinstance(game_server, unity_game.UnityGame):\n raise ValueError('Can only visualize auxiliaries with a Unity game.')\n\n action_sequence, visited_states = self._predict_actions_full_observability(\n goal_probabilities.squeeze(),\n trajectory_distribution.squeeze(),\n obstacle_probabilities.squeeze(),\n avoid_probabilities.squeeze(),\n game_server,\n evaluation_arguments)\n\n else:\n # If partial observability, need to recompute distributions at each step.\n action_sequence, visited_states, last_observation = self._predict_actions_partial_observability(\n example, game_server, evaluation_arguments, logger)\n\n return action_sequence, auxiliary_predictions, visited_states, last_observation\n","sub_path":"agent/model/models/action_generator_model.py","file_name":"action_generator_model.py","file_ext":"py","file_size_in_byte":43325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"255017311","text":"# Copyright 2021-2022 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\nimport mindspore.nn as nn\nimport mindspore.ops as ops\n\ndef conv_bn_relu(in_channel, out_channel, kernel_size, stride, depthwise, activation='relu6'):\n output = []\n output.append(nn.Conv2d(in_channel, out_channel, kernel_size, stride, pad_mode=\"same\",\n group=1 if not depthwise else in_channel))\n output.append(nn.BatchNorm2d(out_channel))\n if activation:\n output.append(nn.get_activation(activation))\n return nn.SequentialCell(output)\n\n\nclass MobileNetV1(nn.Cell):\n \"\"\"\n MobileNet V1 backbone\n \"\"\"\n def __init__(self, class_num=1001, features_only=False):\n super(MobileNetV1, self).__init__()\n self.features_only = features_only\n cnn = [\n conv_bn_relu(3, 32, 3, 2, False), # Conv0\n\n conv_bn_relu(32, 32, 3, 1, True), # Conv1_depthwise\n conv_bn_relu(32, 64, 1, 1, False), # Conv1_pointwise\n conv_bn_relu(64, 64, 3, 2, True), # Conv2_depthwise\n conv_bn_relu(64, 128, 1, 1, False), # Conv2_pointwise\n\n conv_bn_relu(128, 128, 3, 1, True), # Conv3_depthwise\n conv_bn_relu(128, 128, 1, 1, False), # Conv3_pointwise\n conv_bn_relu(128, 128, 3, 2, True), # Conv4_depthwise\n conv_bn_relu(128, 256, 1, 1, False), # Conv4_pointwise\n\n conv_bn_relu(256, 256, 3, 1, True), # Conv5_depthwise\n conv_bn_relu(256, 256, 1, 1, False), # Conv5_pointwise\n conv_bn_relu(256, 256, 3, 2, True), # Conv6_depthwise\n conv_bn_relu(256, 512, 1, 1, False), # Conv6_pointwise\n\n conv_bn_relu(512, 512, 3, 1, True), # Conv7_depthwise\n conv_bn_relu(512, 512, 1, 1, False), # Conv7_pointwise\n conv_bn_relu(512, 512, 3, 1, True), # Conv8_depthwise\n conv_bn_relu(512, 512, 1, 1, False), # Conv8_pointwise\n conv_bn_relu(512, 512, 3, 1, True), # Conv9_depthwise\n conv_bn_relu(512, 512, 1, 1, False), # Conv9_pointwise\n conv_bn_relu(512, 512, 3, 1, True), # Conv10_depthwise\n conv_bn_relu(512, 512, 1, 1, False), # Conv10_pointwise\n conv_bn_relu(512, 512, 3, 1, True), # Conv11_depthwise\n conv_bn_relu(512, 512, 1, 1, False), # Conv11_pointwise\n\n conv_bn_relu(512, 512, 3, 2, True), # Conv12_depthwise\n conv_bn_relu(512, 1024, 1, 1, False), # Conv12_pointwise\n conv_bn_relu(1024, 1024, 3, 1, True), # Conv13_depthwise\n conv_bn_relu(1024, 1024, 1, 1, False), # Conv13_pointwise\n ]\n\n if self.features_only:\n self.network = nn.CellList(cnn)\n else:\n self.network = nn.SequentialCell(cnn)\n self.fc = nn.Dense(1024, class_num)\n\n def construct(self, x):\n output = x\n if self.features_only:\n features = ()\n for block in self.network:\n output = block(output)\n features = features + (output,)\n return features\n output = self.network(x)\n output = ops.ReduceMean()(output, (2, 3))\n output = self.fc(output)\n return output\n\nclass FeatureSelector(nn.Cell):\n \"\"\"\n Select specific layers from an entire feature list\n \"\"\"\n def __init__(self, feature_idxes):\n super(FeatureSelector, self).__init__()\n self.feature_idxes = feature_idxes\n\n def construct(self, feature_list):\n selected = ()\n for i in self.feature_idxes:\n selected = selected + (feature_list[i],)\n return selected\n\nclass MobileNetV1Feature(nn.Cell):\n \"\"\"\n MobileNetV1 with FPN as SSD backbone.\n \"\"\"\n def __init__(self, config):\n super(MobileNetV1Feature, self).__init__()\n self.mobilenet_v1 = MobileNetV1(features_only=True)\n\n self.selector = FeatureSelector([14, 26])\n\n self.layer_indexs = [14, 26]\n\n def construct(self, x):\n features = self.mobilenet_v1(x)\n features = self.selector(features)\n return features\n\ndef mobilenet_v1(class_num=1001):\n return MobileNetV1(class_num)\n\ndef mobilenet_v1_Feature(config):\n return MobileNetV1Feature(config)\n","sub_path":"official/cv/SSD/src/mobilenet_v1.py","file_name":"mobilenet_v1.py","file_ext":"py","file_size_in_byte":4868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"278505313","text":"import matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\nimport numpy as np\nimport cv2\n\n# Read in the image\nimage = mpimg.imread('images/car_green_screen.jpg')\n\n# Print out the image dimensions (height, width, and depth (color))\nprint('Image dimensions:', image.shape)\n\n# Display the image\nplt.imshow(image)\n\n# Define our color selection boundaries in RGB values\nlower_green = np.array([0,180,0])\nupper_green = np.array([100,255,100])\n\n# Define the masked area\nmask = cv2.inRange(image, lower_green, upper_green)\n\n# Vizualize the mask\nplt.imshow(mask, cmap='gray')\n\n# Mask the image to let the car show through\nmasked_image = np.copy(image)\n\nmasked_image[mask != 0] = [0, 0, 0]\n\n# Display it!\nplt.imshow(masked_image)\n","sub_path":"computer_vision/masking.py","file_name":"masking.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"206471520","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: Soufiane Mourragui\n\nComputing proportion of each component for one value of gamma.\n\"\"\"\n\nimport sys\nimport pandas as pd\nimport numpy as np\nfrom joblib import Parallel, delayed\nfrom transact.pv_computation import PVComputation\nfrom transact.interpolation import Interpolation\nfrom transact.matrix_operations import _center_kernel, _right_center_kernel, _left_center_kernel\nfrom transact.kernel_computer import KernelComputer\nfrom transact.TRANSACT import TRANSACT\n\nsys.path.insert(0, '../src/')\nfrom taylor_expansion import *\n\ndef compute_proportion(gamma,\n n_pc,\n n_pv,\n normalized_data_df,\n source_data_key,\n target_data_key,\n n_interpolation=100,\n n_jobs=30,\n clf=None):\n \n # Fit domain adaptation classifier\n print('FIT CLASSIFIER')\n if clf is None:\n PRECISE_clf = PRECISE(kernel='rbf',\n kernel_params={'gamma':gamma},\n n_components=n_pc,\n n_jobs=n_jobs,\n verbose=1)\n PRECISE_clf.fit(normalized_data_df[source_data_key],\n normalized_data_df[target_data_key],\n n_pv=n_pv,\n step=n_interpolation,\n with_interpolation=True)\n else:\n PRECISE_clf = clf\n \n # Angular coefficients\n optimal_time = PRECISE_clf.optimal_time\n source_angular = PRECISE_clf.interpolation_._gamma_interpolations(optimal_time)\n target_angular = PRECISE_clf.interpolation_._xi_interpolations(optimal_time)\n\n source_angular = np.diag(source_angular)\n target_angular = np.diag(target_angular)\n \n # Gaussian depth, i.e. offset\n print('COMPUTE GAUSSIAN DEPTH')\n source_gaussian_depth, target_gaussian_depth = compute_gaussian_depth(gamma, normalized_data_df, source_data_key, target_data_key)\n \n sigma_offset_source = PRECISE_clf.principal_vectors_.gamma_coef['source'].dot(source_gaussian_depth)\n sigma_offset_target = PRECISE_clf.principal_vectors_.gamma_coef['target'].dot(target_gaussian_depth)\n sigma_offset = source_angular.dot(sigma_offset_source) + target_angular.dot(sigma_offset_target)\n \n offset_contribution = {\n 'source': np.square(sigma_offset_source),\n 'target': np.square(sigma_offset_target),\n 'consensus': np.square(sigma_offset_source)\n }\n \n # Linear term\n print('COMPUTE LINEAR CONTRIBUTION')\n p = normalized_data_df[source_data_key].shape[1]\n source_basis_eval = Parallel(n_jobs=n_jobs, verbose=1)(delayed(basis_function)(normalized_data_df[source_data_key],\n i,\n gamma)\n for i in range(p))\n target_basis_eval = Parallel(n_jobs=n_jobs, verbose=1)(delayed(basis_function)(normalized_data_df[target_data_key],\n i,\n gamma)\n for i in range(p))\n target_basis_eval = np.array(target_basis_eval).T\n source_basis_eval = np.array(source_basis_eval).T\n \n sigma_linear_source = PRECISE_clf.principal_vectors_.gamma_coef['source'].dot(source_basis_eval)\n sigma_linear_target = PRECISE_clf.principal_vectors_.gamma_coef['target'].dot(target_basis_eval)\n\n sigma_linear = source_angular.dot(sigma_linear_source) + target_angular.dot(sigma_linear_target)\n linear_contribution = {\n 'source': np.square(np.linalg.norm(sigma_linear_source, axis=1)),\n 'target': np.square(np.linalg.norm(sigma_linear_target, axis=1)),\n 'consensus': np.square(np.linalg.norm(sigma_linear, axis=1))\n }\n \n # Interaction term\n print('COMPUTE INTERACTION CONTRIBUTION')\n loadings = Parallel(n_jobs=n_jobs, verbose=1)(delayed(interaction_loadings_genes)(i, gamma,\n PRECISE_clf,\n normalized_data_df,\n source_data_key,\n target_data_key)\n for i in range(p))\n\n loadings = np.array([np.array(e) for e in loadings])\n source_interaction_contribution = [np.sum(np.square(e[:,0,:]), axis=0) for e in loadings]\n source_interaction_contribution = np.array(source_interaction_contribution)\n source_interaction_contribution = np.sum(source_interaction_contribution, axis=0)\n \n target_interaction_contribution = [np.sum(np.square(e[:,1,:]), axis=0) for e in loadings]\n target_interaction_contribution = np.array(target_interaction_contribution)\n target_interaction_contribution = np.sum(target_interaction_contribution, axis=0)\n \n consensus_interaction_contribution = [np.sum(np.square(e[:,2,:]), axis=0) for e in loadings]\n consensus_interaction_contribution = np.array(consensus_interaction_contribution)\n consensus_interaction_contribution = np.sum(consensus_interaction_contribution, axis=0)\n \n interaction_contribution = {\n 'source': source_interaction_contribution,\n 'target': target_interaction_contribution,\n 'consensus': consensus_interaction_contribution\n }\n \n return PRECISE_clf, {\n 'offset': offset_contribution,\n 'linear': linear_contribution, \n 'interaction': interaction_contribution\n }\n ","sub_path":"figure_3/compute_proportion.py","file_name":"compute_proportion.py","file_ext":"py","file_size_in_byte":5923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"491117805","text":"import socket\r\n\r\n##mysock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n##mysock.bind(('127.0.0.1',1337))\r\n##clientdata, addr = mysock.recvfrom(2048)\r\n##print(clientdata)\r\n\r\nimport threading\r\nimport os\r\n\r\ndef Retrfile(name,sock):\r\n ## Function to send the file to client\r\n## filename = sock.recvfrom(1024)\r\n print(filename)\r\n if os.path.isfile(filename):\r\n\r\n x = \"EXIST\"\r\n length = str(os.path.getsize(filename))\r\n \r\n sock.sendto(x.encode('ascii'))\r\n sock.sendto(length.encode('ascii'))\r\n userResponse = sock.recvfrom(1024).decode('ascii')\r\n\r\n if userResponse[:2] == \"ok\":\r\n with open(filename, 'rb') as f:\r\n ## rb == read binary\r\n bytesToSend = f.read(100)\r\n sock.sendto(bytesToSend)\r\n while bytesToSend != \"\":\r\n bytesToSend = f.read(100)\r\n sock.sendto(bytesToSend)\r\n\r\n else:\r\n y = \"ERR\".encode(\"ascii\")\r\n sock.sendto(y)\r\n print(\"a\")\r\n\r\n sock.close()\r\n\r\ndef Main():\r\n host = \"192.168.43.132\"\r\n port = 1337\r\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n s.bind((host,port))\r\n## s.listen(5)\r\n\r\n print(\"Server ready\")\r\n \r\n## clientdata, addr = s.recvfrom(2048)\r\n## filename = s.recvfrom(1024)\r\n## print(filename)\r\n while True:\r\n## c,addr = s.accept()\r\n print(\"Client connected\")\r\n data = s.recvfrom(1024)\r\n print(data)\r\n \r\n #t = threading.Thread(target=Retrfile,args=('retrThread',clientdata))\r\n #t.start()\r\n\r\n s.close()\r\n\r\nif __name__ == \"__main__\" :\r\n\r\n Main()\r\n","sub_path":"UDP/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"494039847","text":"import asyncio\n\nfrom tartiflette.executors.types import ExecutionContext\n\n\nasync def _execute(root_resolvers, exec_ctx, request_ctx):\n coroutines = [\n resolver(exec_ctx, request_ctx) for resolver in root_resolvers\n ]\n return await asyncio.gather(*coroutines, return_exceptions=False)\n\n\ndef _get_datas(root_nodes):\n data = {}\n for node in root_nodes:\n if node.cant_be_null and node.marshalled is None:\n return None\n data[node.name] = node.marshalled\n\n return data\n\n\nasync def execute(root_nodes, request_ctx):\n results = {\"data\": {}, \"errors\": []}\n exec_ctx = ExecutionContext()\n\n await _execute(root_nodes, exec_ctx, request_ctx)\n\n results[\"errors\"] += [err.coerce_value() for err in exec_ctx.errors if err]\n results[\"data\"] = _get_datas(root_nodes)\n\n if not results[\"errors\"]:\n del results[\"errors\"]\n\n return results\n","sub_path":"tartiflette/executors/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"429317576","text":"# -*- conding:utf-8 -*-\n# @Time :2019/4/8 20:49\n# @Author :yahs0105\n# @FileName:深淺拷貝.py\n# @Ide :PyCharm\n\n\n\n# s = [l,'aaa','bbb','ccc']\n#\n# s1 = [l,'aaa','bbb','ccc']\n# s1[0] = 2\n# print(s)\n# print(s1)\n\n# 淺拷貝\n# s = [l,'aaa','bbb','ccc']\n# s2 = s.copy()\n# print(s2)\n#\n# s2[0] = 3\n# print(s)\n# print(s2)\n\n# s = [[1,2],'aaa','bbb','ccc']\n# s3 = s.copy()\n# print(s3)\n# # s3[1] = 'JerryYeh'\n# # print(s3)\n# # print(s)\n# s3[0][1] ='a'\n# print('s3',s3)\n# print('s',s)\n\n# 深拷貝\n\nimport copy\nhusband = [\"Jerry\",123,[10000,8000]]\n\nwife = husband.copy()\n# wife = copy.copy(husband) #shallow copy\nwife[0] = \"KiKi\"\nwife[1] = 345\n\njing = copy.deepcopy(husband)\n\njing[0] = \"Jing\"\njing[1] = 666\n\njing[2][1] -=1000\n\nhusband[2][1] -=3000\n\nprint(wife)\nprint(husband)\nprint(jing)\n","sub_path":"day14/深淺拷貝.py","file_name":"深淺拷貝.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"6149757","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 ('register', '0003_auto_20150812_2302'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='record',\n old_name='time_record',\n new_name='time_end_record',\n ),\n migrations.AddField(\n model_name='record',\n name='time_start_record',\n field=models.TimeField(default=datetime.datetime(2015, 8, 13, 0, 12, 58, 589728)),\n preserve_default=False,\n ),\n ]\n","sub_path":"register/migrations/0004_auto_20150813_0012.py","file_name":"0004_auto_20150813_0012.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"10106777","text":"# Search for optimal regularization parameter for linear regression model\nfrom main import *\n\nfrom matplotlib.pylab import (figure, semilogx, loglog, xlabel, ylabel, legend, title, subplot, show, grid)\nimport numpy as np\nimport sklearn.linear_model as lm\nfrom sklearn import model_selection\nfrom toolbox_02450 import rlr_validate\n\n\n# Add offset attribute and set attributeNames\ndata = np.concatenate((np.ones((data.shape[0],1)),data),1)\nattributeNames = np.asarray(df.columns[0:13])\nattributeNames = np.append(['Offset'], attributeNames)\n\n#Sæt data op som i bogen: X, N, M, y\nfeatures = [0, 3, 5, 7, 9] # Husk offset(0). Vi ville predicte ud fra features Creatinine phosphate(3), plattelets(7) and Serum sodium(9).\ntargets = [8] # Already added offset, so ejection fratction is 5 and serum creatinine 8\ncvf = 10 # 10-fold cross-validation\nK = cvf\n\n# Values of lambda\n#lambdas = np.power(10.,range(-5,9)) \nlambdas = np.power(2., range(-10,20)) #!!! omkring 10^2 er interessant\n\nfor target in targets: \n y = data[:,target]\n X = data[:,features] \n N,M = X.shape # som indre loop i 2-level cross_val vil dette N svare til |Dpar|\n \n #function rlr_validate from toolbox_02450\n CV = model_selection.KFold(cvf, shuffle=True)\n w = np.empty((M,cvf,len(lambdas)))\n train_error = np.empty((cvf,len(lambdas)))\n val_error = np.empty((cvf,len(lambdas)))\n f = 0\n y = y.squeeze()\n fold_size = np.empty(K)\n \n for train_index, val_index in CV.split(X,y):\n X_train = X[train_index]\n y_train = y[train_index]\n X_val = X[val_index]\n y_val = y[val_index]\n fold_size[f] = len(val_index) # |D-val| om man vil\n \n # Standardize the training set and validation set based on training set moments (not the offset)\n mu = np.mean(X_train[:, 1:], 0)\n sigma = np.std(X_train[:, 1:], 0)\n X_train[:, 1:] = (X_train[:, 1:] - mu) / sigma\n X_val[:, 1:] = (X_val[:, 1:] - mu) / sigma\n \n # precompute terms\n Xty = X_train.T @ y_train\n XtX = X_train.T @ X_train\n \n for l in range(0,len(lambdas)):\n # Compute parameters for current value of lambda and current CV fold\n lambdaI = lambdas[l] * np.eye(M)\n lambdaI[0,0] = 0 # remove bias regularization\n #Train model - get weights\n w[:,f,l] = np.linalg.solve(XtX+lambdaI,Xty).squeeze()\n # Evaluate training and val performance\n train_error[f,l] = np.power(y_train-X_train @ w[:,f,l].T,2).mean(axis=0)\n val_error[f,l] = np.power(y_val-X_val @ w[:,f,l].T,2).mean(axis=0)\n \n f=f+1 \n \n \n #Generalization errors for different values of lambda (algorithm 5)\n Gen_error = np.zeros(len(lambdas))\n Train_error = np.zeros(len(lambdas))\n for s in range(len(lambdas)):\n for k in range(0,K):\n Gen_error[s] += val_error[k][s]*fold_size[k]/N #fold_size[k] er |D_val| i fold k N er størrelsen på det dataset funktionen fodres med, dvs |Dpar| \n Train_error[s]+= train_error[k][s]*fold_size[k]/N\n \n #Optimal model (optimal regularization value)\n opt_lambda = lambdas[np.argmin(Gen_error)]\n opt_lambda_idx = np.argmin(Gen_error)\n \n \n\n # Display results\n print('\\n Regularized linear regression for predicting {0}:'.format(attributeNames[target]))\n print('Optimal regularization constant(lambda) suggested by {0}-fold crossvalidation is around {1}'.format(K, opt_lambda))\n print('The generalization error for this optimal model in this inner loop was {0}. \\n NOTE: this is ONLY 1-level cross-validation.'.format(Gen_error[opt_lambda_idx]))\n\n print('\\n The means of the weights over the 10 folds using the optimal model were:')\n for feature in range(M):\n print('The weight of attribute {0} was {1} '.format(attributeNames[features[feature]], np.mean(w[feature,:,opt_lambda_idx])))\n\n \n #Vis generlaization error og train error som funktion af lambda\n figure(figsize=(10,10)) \n title('Optimal lambda: {0}'.format(opt_lambda))\n semilogx(lambdas,Train_error,'b.-', lambdas, Gen_error, 'r.-')\n xlabel('Regularization factor')\n ylabel('Mean squared error (crossvalidation)')\n legend(['Weighted averaged train error','Generalization error'])\n grid()\n show() \n\n # Vis du forskellige vægte (ikke biasvægt) som funktion af lambda\n figure(figsize=(12,12))\n semilogx(lambdas,np.mean(w[1:,:,:], axis=1).T,'.-') # Don't plot the bias term\n xlabel('Regularization factor')\n ylabel('Mean Coefficient Values')\n grid()\n legend(attributeNames[features[1:]], loc='best') #!!! omit this\n show()\n \n \n \n #!!!Slet alt herunder\n \n # figure(figsize=(10,10))\n # semilogx(lambdas, Gen_error,'r.-')\n # ylabel('Generalization error')\n # xlabel('Regularization strength, $\\log_{10}(\\lambda)$')\n # title('Estimated generalization error as a function of $\\lambda$')\n # grid()\n # show()\n \n \n # figure(figsize=(8,8)) \n # title('Optimal lambda: 1e{0}'.format(np.log10(opt_lambda)))\n # loglog(lambdas,Train_error,'b.-')\n # xlabel('Regularization factor')\n # ylabel('Squared error (crossvalidation)')\n # legend(['Train error','Validation error'])\n # grid()\n # show() \n \n\n \n \n","sub_path":"Scripts/Linear_regression.py","file_name":"Linear_regression.py","file_ext":"py","file_size_in_byte":5319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"20584054","text":"import discord\n\nCLIENT = discord.Client()\n\n@CLIENT.event\nasync def on_ready():\n \"\"\" Print when the bot is ready \"\"\"\n print('Logged in as')\n print(CLIENT.user.name)\n print(CLIENT.user.id)\n print(CLIENT.user.display_name)\n print('------')\n\n@CLIENT.event\nasync def on_message(message):\n await RemoveProfanity(message)\n await innapropriateMessage(message)\n await AddProfanity(message)\n \nasync def innapropriateMessage(message):\n \"\"\" Profainity Filter, it runs when a new message gets sent \"\"\"\n ProfanityList = []\n with open(\"ProfanityList.txt\", \"r\") as myfile:\n ProfanityList = myfile.read().split(\"\\n\")\n newSentence = message.content # The sentence that is gonna replace the innapropriate message\n for word in range(0, len(ProfanityList)):\n if((message.content.lower().find(ProfanityList[word].lower())) != -1 \\\n and not message.author.bot and ProfanityList[word] != \"\"): # Profanity word comes from ProfanityList.txt\n newWord = \"\" # New Profanity word to match casing\n for letter in range(0, len(ProfanityList[word])):\n messageLetter = message.content.lower().find(ProfanityList[word][letter]) # index of bad word and letter\n if (message.content[messageLetter].isupper()):\n newWord += ProfanityList[word][letter].upper()\n else:\n newWord += ProfanityList[word][letter].lower()\n newSentence = newSentence.replace(newWord, \"|BADWORD|\")\n if newSentence != message.content and not message.author.bot:\n await CLIENT.delete_message(message)\n await CLIENT.send_message(message.channel, \"**{}** {}\".format(message.author.display_name, newSentence))\n newSentence = \"\"\n \nasync def AddProfanity(message):\n \"\"\" Add profanities from the list \"\"\"\n if message.content.lower().startswith(\"!addprofanity\") and not message.author.bot \\\n and isModerator(message): # If true, it will append to a file called ProfanityList.txt\n if isProfanity(message.content.lower().replace(\"!addprofanity \", \"\")) != 1:\n with open(\"ProfanityList.txt\", \"a\") as myfile:\n myfile.write(message.content.lower().replace(\"!addprofanity \", \"\") + \"\\n\")\n else:\n CLIENT.send_message(message.channel, \"Profanity already exists.\")\n\nasync def RemoveProfanity(message):\n \"\"\" Remove profanities from the list \"\"\"\n if message.content.lower().startswith(\"!removeprofanity\") and not message.author.bot \\\n and isModerator(message): # If true, it will append to a file called ProfanityList.txt\n ProfanityList = []\n with open(\"ProfanityList.txt\", \"r\") as myfile:\n ProfanityList = myfile.read().split(\"\\n\")\n for i in range(len(ProfanityList)):\n if ProfanityList[i] == message.content.lower().replace(\"!removeprofanity \", \"\"):\n ProfanityList[i] = \"\"\n with open(\"ProfanityList.txt\", \"w\") as myfile:\n for i in range(len(ProfanityList)):\n if ProfanityList[i] != \"\":\n myfile.write(ProfanityList[i] + \"\\n\")\n\ndef isModerator(message):\n for i in range(0, len(message.author.roles)):\n if str(message.author.roles[i]).lower() == \"moderator\" or str(message.author.roles[i]).lower() == \"admin\":\n return True\n return False\n\ndef isProfanity(profanity):\n ProfanityList = []\n with open(\"ProfanityList.txt\", \"r\") as myfile:\n ProfanityList = myfile.read().split(\"\\n\")\n for i in range(0, len(ProfanityList)):\n if ProfanityList[i] == profanity:\n return 1\n return 0\n\nCLIENT.run(\"NDgyMjY2NjAxMDk0MzgxNTY5.DmCZdQ.OHUGv5BatIQPqW2ayVDZrf98hiA\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"395052762","text":"'''\nTime Complexity: O(log Y) -> as we do /2 atleast once\nSpace Complexity: O(n)\nDid this code successfully run on Leetcode : Yes\nExplanation:\nFor Y>X\nStart from the reverse ie Start from Y to X and change * to / and + to -. So whenever even we divide so\nwe get whole number and whenever odd we subtract. Do this until YY we can get number of steps by doing X-Y.\nAt the end we need to do number of steps + X-Y to account for missing a step due to YY cases.\n\nFor eg.\nEg 5 and 8\n steps = 1 and now Y int:\n # Idea start from back\n '''\n can't do this\n if X > Y:\n return X-Y add this in the end.\n Eg 5 and 8\n steps = 1 and now Y X:\n if Y % 2 == 0:\n Y = Y // 2\n else:\n Y += 1\n count += 1\n\n # Adding X-Y case for X>Y here\n return count + X - Y\n","sub_path":"brokenCalculator.py","file_name":"brokenCalculator.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"156226739","text":"import pdb\nimport time\nimport queue\nimport logging\nimport asyncio\n\nimport src.utils.string_utils as string_utils\n\nfrom src.entities.action import TimedAction, Action, EntityType\nfrom src.managers.region_manager import RegionManager\nfrom src.managers.room_manager import RoomManager\nfrom src.managers.portal_manager import PortalManager\nfrom src.managers.character_manager import CharacterManager\nfrom src.managers.item_manager import ItemManager\nfrom src.managers.command_manager import CommandManager\n\nclass GameManager(object):\n class __GameManager(object):\n# ----------------------------------------------------------------------\n def __init__(self):\n # Time is in milliseconds\n self._last_query_time = None\n self._running_time = 0\n\n self._timer_registry = queue.PriorityQueue()\n\n self._region_manager = RegionManager()\n self._room_manager = RoomManager()\n self._portal_manager = PortalManager()\n self._character_manager = CharacterManager()\n self._item_manager = ItemManager()\n self._command_manager = CommandManager()\n\n self._connected_characters = []\n\n def get_connected_characters(self):\n return self._connected_characters\n\n def __update_time(self):\n if self._last_query_time:\n current_time = self.__system_time_ms()\n self._running_time = self._running_time + (current_time - self._last_query_time)\n\n self._last_query_time = current_time\n\n def __system_time_ms(self):\n return int(round(time.time() * 1000))\n\n def get_time(self):\n self.__update_time()\n return self._running_time\n\n def reset_time(self):\n self.__update_time()\n self._running_time = 0\n\n def __add_timed_action(self, timed_action):\n if isinstance(timed_action, TimedAction):\n self._timer_registry.put(timed_action)\n\n # def add_action_relative(self, relative_time_ms, action_type, entities, data_string):\n # action = Action(action_type, entities, data_string)\n # self.add_action_relative(relative_time_ms, action)\n\n def add_action_relative(self, relative_time_ms, action):\n self.add_action_absolute(self.__system_time_ms() + relative_time_ms, action)\n\n # def add_action_absolute(self, absolute_time_ms, action_type, entities, data_string):\n # action = Action(action_type, entities, data_string)\n # self.add_action_absolute(absolute_time_ms, action)\n\n def add_action_absolute(self, absolute_time_ms, action):\n timed_action = TimedAction(self.__system_time_ms(), action)\n self.__add_timed_action(timed_action)\n\n def execute_timed_actions(self):\n current_time = self.__system_time_ms()\n\n while not self._timer_registry.empty():\n timed_action = self._timer_registry.get()\n if timed_action.get_execution_time() > current_time:\n self._timer_registry.put(timed_action)\n break\n\n if timed_action.valid:\n self.do_action(timed_action.get_action())\n asyncio.get_event_loop().call_later(.1, self.execute_timed_actions)\n\n def do_action(self, action):\n # logging.info('Game recieved action: ' + action.action_type)\n if action.action_type == 'chat' or action.action_type == 'announce':\n self.__action_to_realm_players(action)\n elif action.action_type == \"do\":\n self.__route_action(action)\n elif action.action_type == 'modifyattribute':\n self.__modify_attribute(action)\n elif action.action_type == 'vision':\n self.__action_to_room_characters(action, action.room_id)\n elif action.action_type == 'enterrealm':\n self.__login(action.character_id)\n elif action.action_type == 'leaverealm':\n self.__logout(action.character_id)\n elif action.action_type == 'attemptsay':\n self.__say(action.character_id, action.data['msg'])\n elif action.action_type == 'command':\n self.__do_command(action.character_id, action.data['cmd'])\n elif action.action_type == 'attemptenterportal':\n self.__enter_portal(action.character_id, action.portal_id, action.data['direction'])\n elif action.action_type == 'attemptseethroughportal':\n self.__see_through_portal(action.character_id, action.portal_id, action.data['direction'])\n elif action.action_type == 'attempttransport':\n self.__transport(action.character_id, action.room_id)\n elif action.action_type == 'forcetransport':\n self.__transport(action.character_id, action.room_id, force=True)\n # elif action.action_type == 'attemptgetitem':\n # self.__get_item(action.character_id, action.item_id, action.quantity) # TODO\n # elif action.action_type == 'attemptdropitem':\n # self.__drop_item(action.character_id, action.item_id, action.quantity) # TODO\n # elif action.action_type == 'attemptgiveitem':\n # self.__give_item(action.character_id, action.other_character_id, action.item_id, action.quantity) # TODO\n # elif action.action_type == 'spawnitem':\n # self.__spawn_item(action.template_id, action.room_id, action.character_id, action.quantity) # TODO\n # elif action.action_type == 'spawncharacter':\n # self.__spawn_character(action.template_id, action.room_id) # TODO\n # elif action.action_type == 'destroyitem':\n # self.__destroy_item(action.item_id) # TODO\n # elif action.action_type == 'destroycharacter':\n # self.__destroy_character(action.character_id) # TODO\n # elif action.action_type == 'cleanup':\n # self.__cleanup() # TODO\n # elif action.action_type == 'savedatabases':\n # self.__save_all() # TODO\n # elif action.action_type == 'saveregion':\n # self.__save_region(action.region_id) # TODO\n # elif action.action_type == 'saveplayers':\n # self.__save_players() # TODO\n # elif action.action_type == 'reloaditems':\n # self.__reload_item_templates(action.data) # TODO\n # elif action.action_type == 'reloadcharacter':\n # self.__reload_character_templates(action.data) # TODO\n elif action.action_type == 'reloadregion':\n self.__reload_region(action.data) # TODO\n elif action.action_type == 'reloadcommandscript':\n self.__reload_command_script(action.data) # TODO\n elif action.action_type == 'reloadlogicscript':\n self.__reload_logic_script(action.data) # TODO\n # elif action.action_type == 'messagelogic':\n # self.__logic_action(action) # TODO\n # elif action.action_type == 'addlogic':\n # self.__add_logic(action) # TODO\n # elif action.action_type == 'removelogic':\n # self.__remove_logic(action) # TODO\n\n def __load_all(self):\n # Is this necesary if the managers load data dynamically from the database?\n pass # TODO\n\n def __load_timers(self):\n pass # TODO\n\n def __reload_item_templates(self):\n pass # TODO\n\n def __reload_charater_templates(self):\n pass # TODO\n\n def __reload_region(self, name):\n pass # TODO\n\n def __reload_command_script(self, name):\n pass # TODO\n\n def __reload_logic_script(self, name):\n pass # TODO\n\n def __save_all(self):\n pass # TODO\n\n def __save_players(self):\n pass # TODO\n\n def save_region(self, region_id):\n pass # TODO\n\n def __save_timers(self):\n pass # TODO\n\n def __clean_up(self):\n pass # TODO\n\n def __transport(self, character_id, room_id, force=False):\n character = self._character_manager.get_character(character_id)\n old_room = self._room_manager.get_room(character.room_id)\n new_room = self._room_manager.get_room(room_id)\n old_region = self._region_manager.get_region(old_room.region_id)\n new_region = self._region_manager.get_region(new_room.region_id)\n changing_regions = old_region.id != new_region.id\n\n\n # \"ask permission\" from the actors to perform the actions\n if not force:\n if changing_regions:\n if old_region.do_action(Action('canleaveregion', character_id=character.id)):\n return\n\n if new_region.do_action(Action('canenterregion', character_id=character.id)):\n return\n\n if character.do_action(Action('canleaveregion', region_id=old_region.id)):\n return\n\n if character.do_action(Action('canenterregion', region_id=new_region.id)):\n return\n\n if old_room.do_action(Action('canleaveroom', character_id=character.id)):\n return\n\n if new_room.do_action(Action('canenterroom', character_id=character.id)):\n return\n\n if character.do_action(Action('canleaveroom', room_id=old_room.id)):\n return\n\n if character.do_action(Action('canenterroom', room_id=new_room.id)):\n return\n\n # Move the character\n if changing_regions:\n old_region.remove_character(character.id)\n character.region_id = new_region.id\n new_region.add_character(character.id)\n\n old_room.remove_character(character.id)\n character.room_id = new_room.id\n new_room.add_character(character.id)\n\n # Notify actors that the event is complete\n if changing_regions:\n old_region.do_action(Action('leaveregion', character_id=character.id))\n character.do_action(Action('leaveregion', region_id=old_region.id))\n\n action = Action('leaveroom', character_id=character.id, room_id=old_room.id)\n old_room.do_action(action)\n character.do_action(action)\n self.__action_to_room_characters(action, old_room.id)\n self.__action_to_room_items(action, old_room.id)\n\n if changing_regions:\n action = Action('enterregion', character_id=character.id, room_id=new_region.id)\n new_region.do_action(action)\n character.do_action(action)\n\n action = Action('enterroom', character_id=character.id, room_id=new_room.id)\n new_room.do_action(action)\n self.__action_to_room_characters(action, new_room.id)\n self.__action_to_room_items(action, new_room.id)\n\n def __action_to_room_characters(self, action, room_id):\n room = self._room_manager.get_room(room_id)\n\n for character_id in room.character_ids:\n character = self._character_manager.get_character(character_id)\n if character:\n character.do_action(action)\n else:\n logging.error('do_action() error: character_id \"{0}\" not found!'.format(character_id))\n\n def __action_to_room_items(self, action, room_id):\n room = self._room_manager.get_room(room_id)\n\n for item_id in room.item_ids:\n item = self._item_manager.get_item(item_id)\n item.do_action(action)\n\n def __action_to_realm_players(self, action):\n for character in self._connected_characters:\n character.do_action(action)\n\n def __route_action(self, action):\n entity = self.__get_entity_from_action(action)\n\n if entity:\n entity.do_action(action)\n\n def __modify_attribute(self, action):\n entity = self.__get_entity_from_action(action)\n\n if entity:\n for key in action.data:\n entity.data[key] = action.data[key]\n\n def __get_entity_from_action(self, action):\n entity = None\n if action.target_type == EntityType.REGION:\n entity = self._region_manager.get_region(action.region_id)\n elif action.target_type == EntityType.ROOM:\n entity = self._room_manager.get_room(action.room_id)\n elif action.target_type == EntityType.PORTAL:\n entity = self._portal_manager.get_portal(action.portal_id)\n elif action.target_type == EntityType.CHARACTER:\n entity = self._character_manager.get_character(action.character_id)\n elif action.target_type == EntityType.ITEM:\n entity = self._item_manager.get_item(action.item_id)\n\n return entity\n\n def __login(self, character_id):\n character = self._character_manager.get_character(character_id)\n room = self._room_manager.get_room(character.room_id)\n region = self._region_manager.get_region(room.region_id)\n\n character.logged_in = True\n self._connected_characters.append(character)\n room.add_character(character_id)\n region.add_character(character_id)\n\n self.__action_to_realm_players(Action('enterrealm', character_id=character.id))\n region.do_action(Action('enterregion', character_id=character.id))\n character.do_action(Action('enterregion', character_id=character.id))\n room.do_action(Action('enterroom', character_id=character.id))\n self.__action_to_room_characters(Action('enterroom', character_id=character.id), room.id)\n self.__action_to_room_items(Action('enterroom', character_id=character.id), room.id)\n\n def __logout(self, character_id):\n character = self._character_manager.get_character(character_id)\n room = self._room_manager.get_room(character.room_id)\n region = self._region_manager.get_region(room.region_id)\n\n self.__action_to_room_items(Action('leaveroom', character_id=character.id), room.id)\n self.__action_to_room_characters(Action('leaveroom', character_id=character.id), room.id)\n room.do_action(Action('leaveroom', character_id=character.id))\n character.do_action(Action('leaveregion', character_id=character.id))\n region.do_action(Action('leaveregion', character_id=character.id))\n self.__action_to_realm_players(Action('leaverealm', character_id=character.id))\n\n room.remove_character(character)\n region.remove_character(character)\n self._connected_characters.remove(character)\n character.logged_in = False\n\n def __say(self, character_id, msg):\n character = self._character_manager.get_character(character_id)\n room = self._room_manager.get_room(character.room_id)\n region = self._region_manager.get_region(room.region_id)\n\n # ask permission\n action = Action('cansay', character_id=character.id, data={msg: msg})\n if character.do_action(action):\n return\n if room.do_action(action):\n return\n if region.do_action(action):\n return\n\n # Event notifications\n action = Action('say', character_id=character.id, data={msg: msg})\n self.__action_to_room_characters(action, room.id)\n room.do_action(action)\n region.do_action(action)\n\n def __enter_portal(self, character_id, portal_id, direction: str):\n character = self._character_manager.get_character(character_id)\n portal = self._portal_manager.get_portal(portal_id)\n old_room = self._room_manager.get_room(character.room_id)\n\n path = portal.find_path_from(old_room.id, direction)\n\n new_room = self._room_manager.get_room(path.end_room_id)\n old_region = self._region_manager.get_region(old_room.region_id)\n new_region = self._region_manager.get_region(new_room.region_id)\n changing_regions = (old_region.id != new_region.id)\n\n # Ask permission\n if changing_regions:\n action = Action('canleaveregion', character_id=character.id, region_id=old_region.id)\n if old_region.do_action(action):\n return\n if character.do_action(action):\n return\n\n action = Action('canenterregion', character_id=character.id, region_id=old_region.id)\n if new_region.do_action(action):\n return\n if character.do_action(action):\n return\n\n action = Action('canleaveroom', character_id=character.id, room_id=old_room.id)\n if old_room.do_action(action):\n return\n if character.do_action(action):\n return\n\n action = Action('canenterroom', character_id=character.id, room_id=new_room.id)\n if new_room.do_action(action):\n return\n if character.do_action(action):\n return\n\n if portal.do_action(Action('canenterportal', character_id=character.id, data={'direction': direction})):\n return\n\n # tell the room that the player is leaving\n if changing_regions:\n action = Action('leaveregion', character_id=character.id, region_id=old_region.id)\n old_region.do_action(action)\n character.do_action(action)\n\n action = Action('leaveroom', character_id=character.id, portal_id=portal.id, room_id=old_room.id, data={'path': path})\n self.__action_to_room_characters(action, old_room.id)\n self.__action_to_room_items(action, old_room.id)\n old_room.do_action(action)\n\n # tell the portal that the player has actually entered\n action = Action('enterportal', character_id=character.id, portal_id=portal)\n portal.do_action(action)\n character.do_action(action)\n\n # actually move the character\n if changing_regions:\n old_region.remove_character(character.id)\n character.region_id = new_region.id\n new_region.add_character(character.id)\n\n old_room.remove_character(character.id)\n character.room_id = new_room.id\n new_room.add_character(character.id)\n\n # tell everyone in the room that the player has entered\n if changing_regions:\n action = Action('enterregion', character_id=character.id, region_id=new_region.id)\n new_region.do_action(action)\n character.do_action(action)\n\n action = Action('enterroom', character_id=character.id, portal_id=portal.id, room_id=new_room.id, data={'path': path})\n new_room.do_action(action)\n self.__action_to_room_characters(action, new_room.id)\n self.__action_to_room_items(action, new_room.id)\n\n def __see_through_portal(self, character_id: str, portal_id: str, direction: str):\n character = self._character_manager.get_character(character_id)\n portal = self._portal_manager.get_portal(portal_id)\n old_room = self._room_manager.get_room(character.room_id)\n\n path = portal.find_path_from(old_room.id, direction)\n\n new_room = self._room_manager.get_room(path.end_room_id)\n old_region = self._region_manager.get_region(old_room.region_id)\n new_region = self._region_manager.get_region(new_room.region_id)\n changing_regions = (old_region.id != new_region.id)\n\n # Ask permission\n if changing_regions:\n action = Action('canseeregion', character_id=character.id, region_id=old_region.id)\n if old_region.do_action(action):\n return\n if character.do_action(action):\n return\n\n action = Action('canseeroom', character_id=character.id, room_id=new_room.id)\n if new_room.do_action(action):\n return\n if character.do_action(action):\n return\n\n if portal.do_action(Action('canenterportal', character_id=character.id, data={'direction': direction})):\n return\n\n # Perform actions\n action = Action('remoteseeroom', character_id=character.id, room_id=new_room.id, portal_id=portal, data={'path': path})\n portal.do_action(action)\n character.do_action(action)\n new_room.do_action(action)\n old_room.do_action(action)\n\n def __do_command(self, character_id: str, cmd_string: str):\n character = self._character_manager.get_character(character_id)\n\n cmd_name = string_utils.parse_word(cmd_string)\n params = string_utils.remove_word(cmd_string)\n\n # logging.info('{0} is attempting to execute \\'{1}\\' with parameters \\'{2}\\''.format(character.name, cmd_name, params))\n full_command_name = character.find_command(cmd_name)\n if full_command_name:\n command = self._command_manager.get(full_command_name)\n command.execute(character, params)\n else:\n character.do_action(Action(\"error\", data={'msg': 'Unrecognized command: {0}<$nl>'.format(cmd_name)}))\n\n\n# ----------------------------------------------------------------------\n instance = None\n\n def __new__(cls):\n if not GameManager.instance:\n GameManager.instance = GameManager.__GameManager()\n return GameManager.instance\n\n def __getattr__(self, name):\n return getattr(self.instance, name)\n\n def __setattr__(self, name, value):\n return setattr(self.instance, name, value)","sub_path":"src/managers/game_manager.py","file_name":"game_manager.py","file_ext":"py","file_size_in_byte":19914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"268745112","text":"\r\n# This program calculates retail prices.\r\n\r\nmark_up = 2.5 # The markup percentage\r\nanother = 'y' # Variable to control the loop.\r\n\r\n# Process one or more items.\r\nwhile another == 'y' or another == 'Y':\r\n # Get the item's wholesale cost.\r\n wholesale = float(input(\"Enter the item's wholesale cost: \"))\r\n\r\n # Validate the wholesale cost.\r\n while wholesale < 0:\r\n print('ERROR: the cost cannot be negative.')\r\n wholesale = float(input('Enter the correct wholesale cost:'))\r\n\r\n # Calculate the retail price.\r\n retail = wholesale * mark_up\r\n\r\n # Display the retail price.\r\n print('Retail price: $', format(retail, ',.2f'))\r\n another = input (\"Do you want to process another item? (Enter y for yes):\")\r\n if (another == 'N') or (another == 'n'):\r\n print (\"Have a nice day!!\")\r\n","sub_path":"while.py","file_name":"while.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"584920823","text":"import qt\nimport numpy as np\nfrom measurement.lib.measurement2.adwin_ssro import pulsar_mbi_espin\n\nexecfile(qt.reload_current_setup)\nimport mbi.mbi_funcs as funcs\nreload(funcs)\n\nSIL_NAME = 'nr1_sil18'\n\ndef run(name, phase = 0, ):\n m = pulsar_mbi_espin.ElectronRamsey(name)\n funcs.prepare(m, SIL_NAME)\n\n ### sweep the length of the second pulse\n MW_pulse_2_durations = np.arange(0, m.params['fast_pi_duration']+10e-9, 8e-9) \n\n pts = len(MW_pulse_2_durations)\n m.params['pts'] = pts\n m.params['reps_per_ROsequence'] = 2000 \n m.params['MW_pulse_delays'] = np.ones(pts) * 20e-6 # Time between the first and second pulse\n \n ## MW pulses\n m.params['MW_pulse_mod_frqs'] = np.ones(pts) * m.params['AWG_MBI_MW_pulse_mod_frq']\n\n ## First pulse\n m.params['MW_pulse_durations'] = np.ones(pts) * m.params['fast_pi2_duration']\n m.params['MW_pulse_amps'] = np.ones(pts) * m.params['fast_pi2_amp']\n m.params['MW_pulse_1_phases'] = np.ones(pts) * 90\n \n ## Second pulse\n m.params['MW_pulse_2_durations'] = MW_pulse_2_durations\n m.params['MW_pulse_2_amps'] = np.ones(pts) * m.params['fast_pi_amp']\n m.params['MW_pulse_2_phases'] = np.ones(pts) * phase\n # for the autoanalysis\n m.params['sweep_name'] = 'MW_pulse_2_duration (ns)'\n m.params['sweep_pts'] = MW_pulse_2_durations/1e-9\n \n funcs.finish(m, debug=False)\n\nif __name__ == '__main__':\n run(SIL_NAME+'pi2_calibration', phase = 0)\n\n","sub_path":"scripts/mbi/mbi_pi2_calibration.py","file_name":"mbi_pi2_calibration.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"121189097","text":"# 이터레이터 객체 - 리스트, 튜플, 문자열, 딕셔너리, range 객체\n\n#__iter__ - iterator 메소드\n#__next__ - iterator 동작 메소드\n\nclass season:\n def __init__(self):\n self.season_list = ['spring', 'summer', 'autumn', 'winter']\n self.idx = 0\n self.max_num = 4\n\n def __iter__(self):\n return self\n def __next__(self):\n if self.idx < self.max_num:\n curr_idx = self.idx\n self.idx += 1\n return self.season_list[curr_idx]\n else:\n raise StopIteration\n\n# for i in season():\n# print(i)\n\nseason_obj = season().__iter__() #iter 객체 생성\nprint(season_obj.__next__()) #iter 객체 하나 출력","sub_path":"Python Advanced/3.iterator_study.py","file_name":"3.iterator_study.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"142302679","text":"#!/usr/bin/env python3\n\nimport sys\nimport math\nimport base64\nimport tkinter\n\nfrom io import BytesIO\nfrom PIL import Image as PILImage\n\n## NO ADDITIONAL IMPORTS ALLOWED!\n\nclass Image:\n def __init__(self, width, height, pixels):\n self.width = width\n self.height = height\n self.pixels = pixels\n\n def get_pixel(self, x, y):\n j = y*self.width+x\n return self.pixels[j]\n\n def mod_get_pixel(self, x, y): #modified get pixel for out of range cells\n # ***can be condensed so it uses get_pixel!\n x_new = x\n y_new = y\n if x<0: #if out of range, map cells to nearest cell in range\n x_new = 0\n elif x>=(self.width):\n x_new = self.width-1\n if y<0:\n y_new = 0\n elif y>=(self.height):\n y_new = self.height-1\n return self.get_pixel(x_new, y_new)\n\n def apply_kernel(self, x, y, kernel, result): #find new value for each pixel\n r = int((((len(kernel))**(1/2))-1)/2)#this is the amount of squares forwards and backwards the kernel will be applied to in the image\n c = 0.0 #initialize new color \n k = 0 #index of kernel that we multiply the coordinate by\n for y_temp in range(-r, r+1): #iterate over range around the pixel that the kernel covers\n for x_temp in range(-r, r+1):\n c += self.mod_get_pixel(x+x_temp, y+y_temp)*kernel[k] #add to new color value\n k += 1\n result.set_pixel(x, y, c)\n return c\n\n def clip(self, x, y): #clip negative values to 0, >255 values to 255, and round all values to ints\n color = self.get_pixel(x, y)\n if color < 0:\n newcolor = 0\n elif color > 255:\n newcolor = 255\n else:\n newcolor = int(round(color))\n self.set_pixel(x, y, newcolor)\n\n\n def set_pixel(self, x, y, c):\n k = y*self.width+x\n self.pixels[k] = c\n\n def apply_per_pixel(self, func):\n result = Image.new(self.width, self.height)\n for x in range(result.width):\n for y in range(result.height):\n color = self.get_pixel(x, y)\n newcolor = func(color)\n result.set_pixel(x, y, newcolor)\n return result\n\n def create_kernel(self, n): #create blur kernel of the size we need where al the values are the same and sum to 1\n kernel = []\n for i in range(n*n):\n kernel.append(1/(n*n))\n return kernel\n\n def inverted(self):\n return self.apply_per_pixel(lambda c: 255-c)\n\n def correlation(self, kernel):\n result = Image.new(self.width, self.height)\n for x in range(result.width):\n for y in range(result.height):\n self.apply_kernel(x, y, kernel, result)\n result.clip(x, y)\n return result\n\n def blurred(self, n): #create kernel and apply it to image\n kernel = self.create_kernel(n)\n return self.correlation(kernel)\n\n def sharpened(self, n):\n kernel = self.create_kernel(n)\n result = Image.new(self.width, self.height) #same size as initial image\n for x in range(result.width):\n for y in range(result.height):\n newcolor = int(round(2*self.get_pixel(x, y)-self.apply_kernel(x, y, kernel, result))) #equation for sharpening\n result.set_pixel(x, y, newcolor) #set new pixel color\n result.clip(x, y)\n return result\n\n\n def edges(self):\n kx = [-1, 0, 1, -2, 0, 2, -1, 0 , 1]\n ky = [-1, -2, -1, 0, 0, 0, 1, 2, 1]\n result = Image.new(self.width, self.height)\n for x in range(result.width):\n for y in range(result.height):\n newcolor_x = self.apply_kernel(x, y, kx, result) #apply kx\n newcolor_y = self.apply_kernel(x, y, ky, result) #apply ky\n newcolor = int(round(((newcolor_x)**2+(newcolor_y)**2)**(1/2))) #equation for edge detection\n result.set_pixel(x, y, newcolor)\n result.clip(x, y) #round values after all correlations have happened\n return result\n\n def find_low_energy(self):\n min_x = 0\n min_e = 1000000\n for x in range(self.width):\n temp_sum = 0 #find minimum energy column by summing energies in each column\n for y in range(self.height):\n temp_sum += self.get_pixel(x, y)\n if temp_sum < min_e:\n min_e = temp_sum\n min_x = x\n return min_x #store the column index that we need to remove\n\n def remove_column(self, col):\n result = Image.new(self.width-1, self.height)\n for x in range(self.width-1):\n for y in range(self.height):\n if x < col: #if column is less than the one removed, nothing changes\n newcolor = self.get_pixel(x, y)\n result.set_pixel(x, y, newcolor)\n else: #otherwise, we need to shift each column to the left by one\n newcolor = self.get_pixel(x+1, y)\n result.set_pixel(x, y, newcolor)\n return result\n\n def smart_crop(self, c): #input number of columns we need to remove\n new_image = Image.new(self.width, self.height)\n for x in range(self.width):\n for y in range(self.height):\n newcolor = self.get_pixel(x, y)\n new_image.set_pixel(x, y, newcolor) #create initial new image that is the same as input\n for i in range(c): #for every column we need to remove, repeat this process\n edges = new_image.edges() #find edges\n min_x = edges.find_low_energy() #find lowest energy column\n new_image = new_image.remove_column(min_x) #remove lowest energy column\n return new_image\n\n # Below this point are utilities for loading, saving, and displaying\n # images, as well as for testing.\n\n def __eq__(self, other):\n return all(getattr(self, i) == getattr(other, i)\n for i in ('height', 'width', 'pixels'))\n\n @classmethod\n def load(cls, fname):\n \"\"\"\n Loads an image from the given file and returns an instance of this\n class representing that image. This also performs conversion to\n grayscale.\n\n Invoked as, for example:\n i = Image.load('test_images/cat.png')\n \"\"\"\n with open(fname, 'rb') as img_handle:\n img = PILImage.open(img_handle)\n img_data = img.getdata()\n if img.mode.startswith('RGB'):\n pixels = [round(.299*p[0] + .587*p[1] + .114*p[2]) for p in img_data]\n elif img.mode == 'LA':\n pixels = [p[0] for p in img_data]\n elif img.mode == 'L':\n pixels = list(img_data)\n else:\n raise ValueError('Unsupported image mode: %r' % img.mode)\n w, h = img.size\n return cls(w, h, pixels)\n\n @classmethod\n def new(cls, width, height):\n \"\"\"\n Creates a new blank image (all 0's) of the given height and width.\n\n Invoked as, for example:\n i = Image.new(640, 480)\n \"\"\"\n return cls(width, height, [0 for i in range(width*height)])\n\n def save(self, fname, mode='PNG'):\n \"\"\"\n Saves the given image to disk or to a file-like object. If fname is\n given as a string, the file type will be inferred from the given name.\n If fname is given as a file-like object, the file type will be\n determined by the 'mode' parameter.\n \"\"\"\n out = PILImage.new(mode='L', size=(self.width, self.height))\n out.putdata(self.pixels)\n if isinstance(fname, str):\n out.save(fname)\n else:\n out.save(fname, mode)\n out.close()\n\n def gif_data(self):\n \"\"\"\n Returns a base 64 encoded string containing the given image as a GIF\n image.\n\n Utility function to make show_image a little cleaner.\n \"\"\"\n buff = BytesIO()\n self.save(buff, mode='GIF')\n return base64.b64encode(buff.getvalue())\n\n def show(self):\n \"\"\"\n Shows the given image in a new Tk window.\n \"\"\"\n global WINDOWS_OPENED\n if tk_root is None:\n # if tk hasn't been properly initialized, don't try to do anything.\n return\n WINDOWS_OPENED = True\n toplevel = tkinter.Toplevel()\n # highlightthickness=0 is a hack to prevent the window's own resizing\n # from triggering another resize event (infinite resize loop). see\n # https://stackoverflow.com/questions/22838255/tkinter-canvas-resizing-automatically\n canvas = tkinter.Canvas(toplevel, height=self.height,\n width=self.width, highlightthickness=0)\n canvas.pack()\n canvas.img = tkinter.PhotoImage(data=self.gif_data())\n canvas.create_image(0, 0, image=canvas.img, anchor=tkinter.NW)\n def on_resize(event):\n # handle resizing the image when the window is resized\n # the procedure is:\n # * convert to a PIL image\n # * resize that image\n # * grab the base64-encoded GIF data from the resized image\n # * put that in a tkinter label\n # * show that image on the canvas\n new_img = PILImage.new(mode='L', size=(self.width, self.height))\n new_img.putdata(self.pixels)\n new_img = new_img.resize((event.width, event.height), PILImage.NEAREST)\n buff = BytesIO()\n new_img.save(buff, 'GIF')\n canvas.img = tkinter.PhotoImage(data=base64.b64encode(buff.getvalue()))\n canvas.configure(height=event.height, width=event.width)\n canvas.create_image(0, 0, image=canvas.img, anchor=tkinter.NW)\n # finally, bind that function so that it is called when the window is\n # resized.\n canvas.bind('', on_resize)\n toplevel.bind('', lambda e: canvas.configure(height=e.height, width=e.width))\n\n\ntry:\n tk_root = tkinter.Tk()\n tk_root.withdraw()\n tcl = tkinter.Tcl()\n def reafter():\n tcl.after(500,reafter)\n tcl.after(500,reafter)\nexcept:\n tk_root = None\nWINDOWS_OPENED = False\n\n\n\nif __name__ == '__main__':\n # code in this block will only be run when you explicitly run your script,\n # and not when the tests are being run. this is a good place for\n # generating images, etc.\n i = Image.load('test_images/pigbird.png')\n Image.show(i)\n #j=Image.inverted(i)\n #Image.show(j)\n #Image.save(j, 'test_images/blue_gills_2.png', mode = 'PNG')\n #kernel = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \n #0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n k = Image.smart_crop(i, 100)\n #Image.show(k)\n Image.save(k, 'test_images/pigbirdcrop.png', mode = 'PNG')\n\n # the following code will cause windows from Image.show to be displayed\n # properly, whether we're running interactively or not:\n if WINDOWS_OPENED and not sys.flags.interactive:\n tk_root.mainloop()\n","sub_path":"lab.py","file_name":"lab.py","file_ext":"py","file_size_in_byte":11280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"151309232","text":"\"\"\"Support for UK Met Office weather service.\"\"\"\n\nimport logging\n\nfrom homeassistant.components.weather import WeatherEntity\nfrom homeassistant.const import LENGTH_KILOMETERS, TEMP_CELSIUS\nfrom homeassistant.core import callback\nfrom homeassistant.helpers.typing import ConfigType, HomeAssistantType\n\nfrom .const import (\n ATTRIBUTION,\n CONDITION_CLASSES,\n DEFAULT_NAME,\n DOMAIN,\n METOFFICE_COORDINATOR,\n METOFFICE_DATA,\n METOFFICE_NAME,\n VISIBILITY_CLASSES,\n VISIBILITY_DISTANCE_CLASSES,\n)\n\n_LOGGER = logging.getLogger(__name__)\n\n\nasync def async_setup_entry(\n hass: HomeAssistantType, entry: ConfigType, async_add_entities\n) -> None:\n \"\"\"Set up the Met Office weather sensor platform.\"\"\"\n hass_data = hass.data[DOMAIN][entry.entry_id]\n\n async_add_entities(\n [\n MetOfficeWeather(\n entry.data,\n hass_data,\n )\n ],\n False,\n )\n\n\nclass MetOfficeWeather(WeatherEntity):\n \"\"\"Implementation of a Met Office weather condition.\"\"\"\n\n def __init__(self, entry_data, hass_data):\n \"\"\"Initialise the platform with a data instance.\"\"\"\n self._data = hass_data[METOFFICE_DATA]\n self._coordinator = hass_data[METOFFICE_COORDINATOR]\n\n self._name = f\"{DEFAULT_NAME} {hass_data[METOFFICE_NAME]}\"\n self._unique_id = f\"{self._data.latitude}_{self._data.longitude}\"\n\n self.metoffice_now = None\n\n @property\n def name(self):\n \"\"\"Return the name of the sensor.\"\"\"\n return self._name\n\n @property\n def unique_id(self):\n \"\"\"Return the unique of the sensor.\"\"\"\n return self._unique_id\n\n @property\n def condition(self):\n \"\"\"Return the current condition.\"\"\"\n return (\n [\n k\n for k, v in CONDITION_CLASSES.items()\n if self.metoffice_now.weather.value in v\n ][0]\n if self.metoffice_now\n else None\n )\n\n @property\n def temperature(self):\n \"\"\"Return the platform temperature.\"\"\"\n return (\n self.metoffice_now.temperature.value\n if self.metoffice_now and self.metoffice_now.temperature\n else None\n )\n\n @property\n def temperature_unit(self):\n \"\"\"Return the unit of measurement.\"\"\"\n return TEMP_CELSIUS\n\n @property\n def visibility(self):\n \"\"\"Return the platform visibility.\"\"\"\n _visibility = None\n if hasattr(self.metoffice_now, \"visibility\"):\n _visibility = f\"{VISIBILITY_CLASSES.get(self.metoffice_now.visibility.value)} - {VISIBILITY_DISTANCE_CLASSES.get(self.metoffice_now.visibility.value)}\"\n return _visibility\n\n @property\n def visibility_unit(self):\n \"\"\"Return the unit of measurement.\"\"\"\n return LENGTH_KILOMETERS\n\n @property\n def pressure(self):\n \"\"\"Return the mean sea-level pressure.\"\"\"\n return (\n self.metoffice_now.pressure.value\n if self.metoffice_now and self.metoffice_now.pressure\n else None\n )\n\n @property\n def humidity(self):\n \"\"\"Return the relative humidity.\"\"\"\n return (\n self.metoffice_now.humidity.value\n if self.metoffice_now and self.metoffice_now.humidity\n else None\n )\n\n @property\n def wind_speed(self):\n \"\"\"Return the wind speed.\"\"\"\n return (\n self.metoffice_now.wind_speed.value\n if self.metoffice_now and self.metoffice_now.wind_speed\n else None\n )\n\n @property\n def wind_bearing(self):\n \"\"\"Return the wind bearing.\"\"\"\n return (\n self.metoffice_now.wind_direction.value\n if self.metoffice_now and self.metoffice_now.wind_direction\n else None\n )\n\n @property\n def attribution(self):\n \"\"\"Return the attribution.\"\"\"\n return ATTRIBUTION\n\n async def async_added_to_hass(self) -> None:\n \"\"\"Set up a listener and load data.\"\"\"\n self.async_on_remove(\n self._coordinator.async_add_listener(self._update_callback)\n )\n self._update_callback()\n\n @callback\n def _update_callback(self) -> None:\n \"\"\"Load data from integration.\"\"\"\n self.metoffice_now = self._data.now\n self.async_write_ha_state()\n\n @property\n def should_poll(self) -> bool:\n \"\"\"Entities do not individually poll.\"\"\"\n return False\n\n @property\n def available(self):\n \"\"\"Return if state is available.\"\"\"\n return self.metoffice_now is not None\n","sub_path":"homeassistant/components/metoffice/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":4612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"398678285","text":"#!/lusr/bin/python\n\n'''\nTaylor Fausak and Kimberly Lee\nCS 373 Project 4\nMarch 7, 2010\n'''\n\n# Used to quickly map ratings to integers (faster than calling int())\nratings_map = {'1' : 1, '2' : 2, '3' : 3, '4' : 4, '5' : 5}\n\ndef average_customer_rating (customers):\n\t'''\n\tCalculates the average rating for all customers.\n\t@param customers a dict that maps customer IDs to a rolling sum of ratings and the number of ratings they've given\n\t@return the average rating for all customers (modifies the customers dict in place)\n\t'''\n\tS = N = A = 0\n\n\tfor customer in customers:\n\t\ts = customers[customer][0]\n\t\tn = customers[customer][1]\n\t\tS += s\n\t\tN += n\n\t\tn = float(n) # Avoid integer division\n\t\ta = s / n\n\t\tassert 1.0 <= a <= 5.0\n\t\tcustomers[customer] = a\n\t\n\tN = float(N)\n\tA = S / N\n\tassert 1.0 <= A <= 5.0\n\t\n\treturn A\n\ndef parse_training_data (reader, customers):\n\t'''\n\tParses training data for the Netflix Prize. Calculates the average movie rating and tracks each rating by customer.\n\t@param reader a file reader, usually to 'mv_1234567.txt' or similar\n\t@param customers a dict that maps customer IDs to a rolling sum of ratings and the number of ratings they've given\n\t@return the movie ID and the average rating for that movie (modifies the customers dict in place)\n\t'''\n\tglobal ratings_map\n\n\ts = 0\n\tn = 0\n\tmovie = reader.readline()\n\tmovie = movie[:-2]\n\n\tfor line in reader:\n\t\t# Don't convert customer ID to an integer. It's slower than string hashing.\n\t\tcustomer = line[:-14]\n\t\trating = line[-13:-12]\n\t\trating = ratings_map[rating]\n\t\tassert 1 <= rating <= 5\n\n\t\t# Calculate the average rating for this movie\n\t\ts += rating\n\t\tn += 1\n\n\t\t# Track each customer's ratings\n\t\tif customer not in customers:\n\t\t\tcustomers[customer] = [0, 0]\n\t\tcustomers[customer][0] += rating\n\t\tcustomers[customer][1] += 1\n\n\tn = float(n) # Avoid integer division\n\taverage = s / n\n\n\treturn movie, average\n\ndef predict_rating (average, movie, customer):\n\t'''\n\t@param average the average ratings for all movies\n\t@param movie the average rating given to this movie\n\t@param customer the average rating given by this customer\n\t@return a prediction of this customer's rating of this movie\n\t'''\n\tprediction = 0.476 * movie + 0.524 * customer\n\n\treturn prediction\n","sub_path":"cs373/4/Netflix.py","file_name":"Netflix.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"275495865","text":"##################################################################\n# this uses byte objects\n# good values: 90 150\n##################################################################\nimport sys\nimport argparse\nimport pyaudio\nimport numpy as np\nimport wave\nimport statistics \nimport json\nimport talkey\nfrom signal import signal, SIGINT\nfrom pyfiglet import Figlet\n\nCHUNK = 512\nsample_format = pyaudio.paInt16 # 16 bits per sample\nchannels = 1\n#RATE = 16000\nRATE = 32000\n\n##################################################################\n# set up command-line arguments\n##################################################################\nparser = argparse.ArgumentParser(prog=sys.argv[0], description='Train Yes, No, Quit', allow_abbrev=False)\nparser.add_argument('-s', '--max-bg-start', type=int, dest='maxBackgroundStart')\nparser.add_argument('--max-bg-start-volume', type=int, dest='maxBackgroundStartVolume')\nparser.add_argument('--max-bg-start-crossings', type=int, dest='maxBackgroundStartCrossings')\nparser.add_argument('-l', '--length', type=int, dest='seconds')\nparser.add_argument('-j', '--json-file', type=str, dest='jsonFile')\nparser.set_defaults(\n maxBackgroundStartVolume=9, \n maxBackgroundStartCrossings=24, \n seconds=5, \n jsonFile='yes.no.quit.json')\n\nargs = parser.parse_args()\n\n\n\n##################################################################\n#init program global variables\n##################################################################\nphrase=''\nmaxBackgroundStartVolume=args.maxBackgroundStartVolume\nmaxBackgroundStartCrossings=args.maxBackgroundStartCrossings\nseconds=args.seconds\njsonFile=args.jsonFile\n#frames = []\nnumActualRecordedFrames = 0\nmaxFramesBeforeTrim = int(RATE / CHUNK * seconds)\n\n#textToSpeech = talkey.Talkey()\ntextToSpeech = talkey.Talkey(preferred_language=['en'])\n\np = pyaudio.PyAudio() # Create an interface to PortAudio\nf = Figlet()\n\nphrasesArray = []\n\nquitProgram = False\nnewPhraseAddedThisTime = False\n\n##################################################################\ndef listPhrasesTrained():\n\n listedPhrases = []\n for phrase in phrasesArray:\n print(phrase.keys())\n if not phrase['phrase'] in listedPhrases:\n listedPhrases.append(phrase['phrase'])\n print(phrase['phrase'])\n\n\n##################################################################\ndef signalHandler(signalReceived, frame):\n print('Got CTRL-C...')\n\n\n # Terminate the PortAudio interface\n global p\n p.terminate()\n\n global newPhraseAddedThisTime\n global phrasesArray\n\n if newPhraseAddedThisTime and len(phrasesArray) > 0:\n print('Saving meta data as JSON file...')\n phrasesFile = open(jsonFile,'w')\n phrasesFile.write(json.dumps(phrasesArray, indent=4, sort_keys=True))\n phrasesFile.close()\n\n print('Done.')\n\n sys.exit(0)\n\n\n##################################################################\ndef isValidSound(frame, maxBackgroundVolume, maxBackgroundCrossings):\n jsonArray = []\n data = np.frombuffer(frame, dtype=np.int16)\n peak = np.amax(np.abs(data))\n bars = int(255*peak/2**16)\n #print('#'*bars)\n crossings = numZeroCrossings(data)\n #print('vol:', bars,' freq:', crossings)\n if bars > maxBackgroundVolume:\n return True, 'bars', bars, crossings\n if crossings > maxBackgroundCrossings:\n return True, 'crossings', bars, crossings\n else:\n return False, 'nothing', bars, crossings\n\n##################################################################\ndef recordAudio():\n\n stream = p.open(format=sample_format,\n channels=channels,\n rate=RATE,\n frames_per_buffer=CHUNK,\n input=True)\n\n frames = [] # Initialize array to store frames\n\n print('recording...')\n\n isFirstValidSound = False\n lastSoundWasInvalid = False\n numConsecutiveInvalidSounds = 0\n for i in range(0, int(RATE / CHUNK * seconds)):\n data = stream.read(CHUNK, exception_on_overflow=False)\n if not isFirstValidSound:\n resultTrue, why, bars, crossings = isValidSound(data, maxBackgroundStartVolume, maxBackgroundStartCrossings)\n if resultTrue:\n print('.......capturing..... reason:', why, ' vol:', bars, ' crossings:', crossings)\n print('.......capturing..... reason:', why, ' vol:', bars, ' crossings:', crossings)\n print('.......capturing..... reason:', why, ' vol:', bars, ' crossings:', crossings)\n isFirstValidSound = True\n if isFirstValidSound:\n isValid, why, bars, crossings = isValidSound(data, maxBackgroundStartVolume, maxBackgroundStartCrossings)\n if lastSoundWasInvalid and not isValid:\n numConsecutiveInvalidSounds += 1\n elif not isValid:\n numConsecutiveInvalidSounds = 1\n lastSoundWasInvalid = True\n else:\n lastSoundWasInvalid = False\n\n if numConsecutiveInvalidSounds > 15:\n print('...Aborting capture..... reason:', why, ' vol:', bars, ' crossings:', crossings)\n print('...Aborting capture..... reason:', why, ' vol:', bars, ' crossings:', crossings)\n print('...Aborting capture..... reason:', why, ' vol:', bars, ' crossings:', crossings)\n break\n\n if isFirstValidSound:\n frames.append(data)\n\n global numActualRecordedFrames\n numActualRecordedFrames = len(frames)\n\n # Stop and close the stream \n stream.stop_stream()\n stream.close()\n\n return frames\n\n##################################################################\ndef compareTwoPhraseMetaData(phrase1, phrase2):\n\n numFrames = phrase1['numRecFrames']\n\n crossingsDiff = 0\n peakDiff = 0\n for i in range(numFrames):\n data1 = phrase1['frameData'][i]\n data2 = phrase2['frameData'][i]\n crDiff = abs(data1['crossings'] - data2['crossings'])\n pkDiff = abs(data1['peak'] - data2['peak'])\n crossingsDiff += crDiff\n peakDiff += pkDiff\n\n numFramesDiff = abs(phrase1['numRecFrames'] - phrase2['numRecFrames'])\n return crossingsDiff, peakDiff, numFramesDiff\n\n##################################################################\ndef findBestMatch(latestPhrase, phrasesArray):\n\n numPhrases = len(phrasesArray)\n\n leastDiff = sys.maxsize\n bestMatchIndex = -1\n previousPhrase = ''\n numMatches = 0\n print('findBestMatch(): numPhrases to compare against: ', numPhrases)\n for i in range(numPhrases):\n phrase = phrasesArray[i]\n #print('comparing ' + latestPhrase['phrase'] +', ' + str(latestPhrase['numRecFrames']) + \n #' against ' + phrase['phrase'] + ', ' + str(phrase['numRecFrames']))\n crDiff, pkDiff, numFramesDiff = compareTwoPhraseMetaData(latestPhrase, phrase)\n difference = crDiff + pkDiff + numFramesDiff\n if leastDiff > difference:\n leastDiff = difference\n bestMatchIndex = i\n print('findBestMatch():' + phrase['phrase'], ' leastDiff: ', leastDiff)\n\n if phrase['phrase'] == previousPhrase:\n numMatches += 1\n #print('currPhrase EQUALS previousPhrase', numMatches)\n else:\n numMatches = 0\n previousPhrase = phrase['phrase']\n #print('currPhrase NOT previousPhrase', numMatches)\n\n\n print('findBestMatch(): leastDiff ', leastDiff)\n return leastDiff, numMatches, phrasesArray[bestMatchIndex]\n\n##################################################################\ndef numZeroCrossings(data):\n length = data.size\n i = 0\n crossings = 0\n while i < length - 1:\n if (data[i] > 0 and data[i+1] < 0) or (data[i] < 0 and data[i+1] > 0):\n crossings += 1\n i += 2\n return crossings\n\n##################################################################\ndef getAudioMetaData(frames):\n\n jsonArray = []\n for i in range(len(frames)):\n data = np.frombuffer(frames[i], dtype=np.int16)\n crossings = numZeroCrossings(data)\n peak = np.amax(np.abs(data))\n bars = int(255*peak/2**16)\n #dispbars = '#'*int(255*peak/2**16)\n #print(dispbars)\n jsonStr = {\"crossings\": crossings, \"peak\": bars}\n jsonArray.append(jsonStr)\n\n jsonObject = {\n \"phrase\": phrase, \n \"recLimitSecs\": seconds, \n \"framesLimit\": maxFramesBeforeTrim, \n \"numRecFrames\": numActualRecordedFrames, \"frameData\": jsonArray }\n return jsonObject\n\n##################################################################\ndef addFakeAudioMetaDataForFillerFrames(metaData):\n\n numRecFrames = metaData['numRecFrames']\n framesLimit = metaData['framesLimit']\n numFillFrames = framesLimit - numRecFrames\n frameData = metaData['frameData']\n for i in range(numFillFrames):\n frameData.append({\"crossings\": 0, \"peak\": 0})\n #metaData['numRecFrames'] = framesLimit\n\n##################################################################\ndef countVolumeValue(data, value):\n count = 0\n for i in range(len(data)):\n if data[i] == value:\n count += 1\n return count\n\n##################################################################\ndef isValidStartingSound(data, maxBackground):\n\n try:\n\n mode = statistics.mode(data)\n volCount = countVolumeValue(data, mode)\n\n if mode > 250 and volCount>= maxBackground:\n return False\n if mode < 3 and volCount >= maxBackground:\n return False\n\n return True\n\n except:\n #print('exception')\n return False\n\n##################################################################\n\n\nif __name__ == '__main__':\n signal(SIGINT, signalHandler)\n\n\n\n\nprint('Load Existing JSON meta data from file...')\ntry:\n phrasesFile = open(jsonFile,'r')\n phrasesString = phrasesFile.read()\n phrasesFile.close()\n phrasesArray = json.loads(phrasesString)\n print('Existing JSON meta data loaded from file.')\nexcept json.decoder.JSONDecodeError:\n print('')\n print('bad JSON file data..')\n print('')\n sys.exit(1)\nexcept FileNotFoundError:\n print('')\n print('No JSON file Data..')\n print('')\n\n\nwhile not quitProgram:\n\n listPhrasesTrained()\n\n userInput = input('Press to record, or \\'q\\' to quit program: ')\n\n if userInput == 'q':\n break\n\n\n phraseFrames = recordAudio()\n\n print('phrase frames: ', len(phraseFrames), ' vol thre: ', maxBackgroundStartVolume, ', cros the:' , maxBackgroundStartCrossings)\n\n\n if len(phraseFrames) > 0:\n \n\n metaDataForLatestRecordedPhrase = getAudioMetaData(phraseFrames)\n addFakeAudioMetaDataForFillerFrames(metaDataForLatestRecordedPhrase)\n\n if len(phrasesArray) > 0:\n difference, numMatches, bestMatch = findBestMatch(metaDataForLatestRecordedPhrase, phrasesArray)\n print('best Yes No Quit Match: ', bestMatch['phrase'], ' numMatches: ', numMatches)\n if difference < 200 and numMatches > 6:\n print(f.renderText(bestMatch['phrase']))\n textToSpeech.say('You said, ' + bestMatch['phrase'])\n needPhrase = bestMatch['phrase']\n else:\n print(f.renderText(bestMatch['phrase']))\n textToSpeech.say(bestMatch['phrase'] + '?')\n isThisCorrect = input('Correct ? :')\n if isThisCorrect == 'y':\n needPhrase = bestMatch['phrase']\n else:\n needPhrase = input('Need to assign new phrase to this latest recording:')\n else:\n needPhrase = input('Need to assign new phrase to this latest recording:')\n\n if len(needPhrase) > 0:\n metaDataForLatestRecordedPhrase['phrase'] = needPhrase\n phrasesArray.append(metaDataForLatestRecordedPhrase)\n newPhraseAddedThisTime = True\n else:\n print('Throwing new recording away....')\n else:\n print('Nothing Recorded ....')\n print('Nothing Recorded ....')\n print('Nothing Recorded ....')\n\n\n\n# Terminate the PortAudio interface\np.terminate()\n\nif newPhraseAddedThisTime:\n print('Saving meta data as JSON file...')\n phrasesFile = open(jsonFile,'w')\n phrasesFile.write(json.dumps(phrasesArray, indent=4, sort_keys=True))\n phrasesFile.close()\n print('Done.')\n\n\n","sub_path":"Python/Audio/Voice.Recognition/Phase3/train.yes.no.quit.py","file_name":"train.yes.no.quit.py","file_ext":"py","file_size_in_byte":12474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"455332305","text":"# puzzle 1 - valid\n# \t\t0001\n# \t\t0010\n# \t\t0100\n# \t\t0000\n# puzzle 2 - not valid\n# \t\t0001\n# \t\t0010\n# \t\t0100\n# \t\t1000\t\n# # boolean isValid(int[][] puzzle):\n# is_interrupted=false\n# # components=[]\n# for r in puzzle:\n# for i,s in enumerate(r):\n# if (r[i]=!r[i+1]) or (r[i]=!r[i-1]):\n# is_interrupted=true\n\ndef isValid(puzzle):\n # obtain dimensions of the puzzle assuming it's a rectangular nxm\n rows=len(puzzle)\n cols=len(puzzle[0])\n \n start=(0,0) #<- find starting point, e.g. pick randomly until it's white, \n\n visited=[] # init visited squares\n visited.append([start[0], start[1]]) # mark starting square as visited\n\n def move(square):\n \n new_square = [0,0] # initialise new loc\n valid_moves=[(1,0),(-1,0),(0,1),(0,-1)] \n \n for m in valid_moves:\n # make a move\n new_square[0]=square[0]+m[0]\n new_square[1]=square[1]+m[1]\n # if the move is within bounds\n if (0<=new_square[0] in effect a depth-first search\n move([new_square[0], new_square[1]])\n \n # determine number of white squares \n n_white_square=rows*cols-sum([sum(r) for r in puzzle]) \n \n # traverse the puzzle \n move([start[0], start[1]])\n \n # check if traversal visited all white squares\n return n_white_square==len(visited)\n \npuzzle=[[0,0,0,1],\n\t\t[0,1,0,0],\n\t\t[1,1,1,0],\n\t\t[1,0,0,0]]\n\nprint(isValid(puzzle))","sub_path":"graph/dfs.py","file_name":"dfs.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"404666824","text":"#!/usr/bin/env python\n\"\"\" This script provisions the required environment for the robustToolbox.\n\"\"\"\n\n# standard library\nimport shutil\nimport os\n\n# Module-wide variables\nGUEST, HOST = '/home/vagrant', '/vagrant'\n\n''' Provisioning\n'''\nos.system('apt-get update -y')\n\n\n# Additional system-wide software.\npackages = ['build-essential', 'gfortran', 'python3-pip', 'python-pip', 'git',\n 'libblas-dev', 'libatlas-base-dev', 'liblapack-dev',\n 'libyaml-cpp-dev', 'cython3', 'python-dev', 'python3-dev',\n 'libevent-dev', 'python3-matplotlib', 'python3-numpy',\n 'python3-scipy', 'python3-pandas', 'libfreetype6-dev', 'libxft-dev']\n\nfor package in packages:\n\n os.system('apt-get install -y ' + package)\n\n# Download development environment\nos.chdir(GUEST)\n\nif not os.path.exists('robustToolbox'):\n \n os.mkdir('robustToolbox')\n\n os.chdir('robustToolbox')\n\n os.system('git clone https://github.com/robustToolbox/package.git')\n\n os.mkdir('documentation')\n\n os.chdir('documentation')\n\n os.system('git clone https://github.com/robustToolbox/documentation.git')\n\n os.system('git clone https://github.com/robustToolbox/robustToolbox.github.io.git')\n\n os.chdir('../../')\n\n\nshutil.copyfile(HOST + '/bin/pull.py', GUEST + '/robustToolbox/pull')\n\nos.system('chmod 755 ' + GUEST + '/robustToolbox/pull')\n\n# Create and prepare virtual environment. This is still required\n# as the toolbox is written in Python 3.\nos.system('pip install virtualenv virtualenvwrapper')\n\nif 'virtualenvwrapper' not in open(GUEST + '/.profile').read():\n \n with open(GUEST + '/.profile', 'a+') as file_:\n\n file_.write('\\n' + 'export WORKON_HOME=' + GUEST + '/.envs')\n\n file_.write('\\n' + 'source /usr/local/bin/virtualenvwrapper.sh')\n\n# Initialize virtual environment for development.\nos.system('sudo /vagrant/bin/initialize_envs.sh')\n\n# Integration of robustToolbox.\nif 'ROBUPY' not in open(GUEST + '/.profile').read():\n\n with open(GUEST + '/.profile', 'a+') as file_:\n\n file_.write('\\n' + 'export ROBUPY=$HOME/robustToolbox/package')\n\n# Cleanup permissions.\nfor path in [HOST, GUEST]:\n\n os.system('chown -R vagrant:vagrant ' + path)\n","sub_path":"development/vagrant/bin/provisioning.py","file_name":"provisioning.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"508464222","text":"#coding: utf-8\n\nimport numpy as np\nimport cv2\nimport sys \n\n@profile\ndef FAST_freak(img):\n\timg1 = cv2.imread(\"../imgReferencia/img00.jpg\", 0)\n\n\tfast = cv2.FastFeatureDetector_create(threshold=25)\n\tfreak = cv2.xfeatures2d.FREAK_create()\n\tbf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\n\n\tkp1 = fast.detect(img1,None)\n\tkp1, des1 = freak.compute(img1, kp1)\n\n\timg2 = cv2.imread(\"../imgTeste/img\"+str(img)+\".jpg\", 0)\n\n\tkp2 = fast.detect(img2,None)\n\tkp2, des2 = freak.compute(img2, kp2)\n\tmatches = bf.match(des1,des2)\n\nif __name__ == '__main__':\n\timgNumero = sys.argv[1]\n\tFAST_freak(imgNumero)","sub_path":"Desempenho/FAST/FAST_freak.py","file_name":"FAST_freak.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"9207273","text":"from flask import Flask, request, jsonify\r\nfrom pymongo import MongoClient\r\nimport os, json, redis\r\n\r\n# App\r\napplication = Flask(__name__)\r\n\r\n# connect to MongoDB\r\nmongoClient = MongoClient('mongodb://' + os.environ['MONGODB_USERNAME'] + ':' + os.environ['MONGODB_PASSWORD'] + '@' + os.environ['MONGODB_HOSTNAME'] + ':27017/' + os.environ['MONGODB_AUTHDB'])\r\ndb = mongoClient[os.environ['MONGODB_DATABASE']]\r\n\r\n# connect to Redis\r\nredisClient = redis.Redis(host=os.environ.get(\"REDIS_HOST\", \"localhost\"), port=os.environ.get(\"REDIS_PORT\", 6379), db=os.environ.get(\"REDIS_DB\", 0))\r\n\r\n@application.route('/')\r\ndef index():\r\n body ='

    MongoDB Exercises - Array

    '\r\n body += '

    Alphabet Guessing Game v1.0

    '\r\n body += 'Start'\r\n return body\r\n\r\n@application.route('/sample')\r\ndef sample():\r\n doc = db.test.find_one()\r\n # return jsonify(doc)\r\n body = '
    '\r\n body += '

    Python

    '\r\n body += '

    '\r\n body += 'Flask v1.1.x Quickstart'\r\n body += ' | '\r\n body += 'PyMongo v3.11.2 Tutorial'\r\n body += ' | '\r\n body += 'redis-py v3.5.3 Git'\r\n body += '

    '\r\n body += '
    '\r\n body += '

    MongoDB

    '\r\n body += '
    '\r\n    body += json.dumps(doc, indent=4)\r\n    body += '
    '\r\n res = redisClient.set('Hello', 'World')\r\n if res == True:\r\n # Display MongoDB & Redis message.\r\n body += '

    Redis

    '\r\n body += 'Get Hello => '+redisClient.get('Hello').decode(\"utf-8\")\r\n return body\r\n\r\nif __name__ == \"__main__\":\r\n ENVIRONMENT_DEBUG = os.environ.get(\"FLASK_DEBUG\", True)\r\n ENVIRONMENT_PORT = os.environ.get(\"FLASK_PORT\", 5000)\r\n application.run(host='0.0.0.0', port=ENVIRONMENT_PORT, debug=ENVIRONMENT_DEBUG)","sub_path":"Alphabet_guessing_game/app/sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"301679282","text":"#!/usr/bin/env python3\n\nimport csv\nfrom math import erf, sqrt\nfrom randomness import randnr\nfrom regression import linear_regression_least_squares, covariance, variance, mean, predict\nfrom decimal import *\n\nrand = randnr(3)\ngetcontext().prec = 3\ndef in_random_order(x):\n # \"Returns an iterator that presents the list x in a random order\"\n indices = [i for i, _ in enumerate(x)]\n # \"inside-out\" Fisher-Yates shuffle. Step through the list, and at\n # each point, exchange the current element with a random element\n # in the list (including itself)\n for i in range(len(indices)):\n j = (rand.randint() // 65536) % (i+1) # The lower bits of our random generator are correlated!\n indices[i], indices[j] = indices[j], indices[i]\n for i in indices:\n yield x[i]\n\n# Functions go here!\n\n\ndef step(v, d, step_size):\n return [v[i] + d[i] * step_size for i in range(len(v))]\n\n\ndef stochastic_minimize(f, df, x: list, y: list, theta0, alpha0=0.001, iterations=50):\n # Finds the parameters theta giving the minimum\n # The alpha parameter will reduce as we continue\n data = list(zip(x, y))\n min_theta, min_value = None, float('inf')\n alpha, theta = alpha0, theta0\n iterations_without_imporvement = 0\n iter = 0\n while iterations_without_imporvement < iterations:\n # iterate all 500 datas(move theta along gradient 500 times)\n iter += 1\n\n # full value\n value = 0\n for i in range(len(x)):\n x_i = x[i]\n y_i = y[i]\n value = value + f(x_i, y_i, theta)\n\n if value < min_value:\n iterations_without_imporvement = 0\n alpha = alpha0\n min_value, min_theta = value, theta\n\n if value >= min_value:\n iterations_without_imporvement += 1\n theta = min_theta\n alpha *= .9\n\n for x_i, y_i in in_random_order(data):\n gradient = df(x_i, y_i, theta)\n for i in range(len(theta)):\n theta[i] -= alpha * gradient[i]\n if iter % 1000 == 0: print(theta)\n\n return min_theta\n\n\ndef loss(x_i, y_i, beta):\n sub_sum = sum(beta[i + 1] * x_i[i] for i in range(len(x_i)))\n return (beta[0] + sub_sum - y_i) ** 2\n\n\ndef dloss(x_i, y_i, beta):\n sub_sum = sum(beta[i+1] * x_i[i] for i in range(len(x_i)))\n ret = [2 * sub_sum - y_i]\n for i in range(len(x_i)):\n ret.append(2 * x_i[i] * sub_sum - y_i)\n return ret\n\n\ndef full_loss(f, x, y, beta):\n return sum(f(x_i, y_i, beta) for x_i, y_i in zip(x, y))\n\n\ndef R_2(f, x, y, beta):\n SSR_2 = sum((f(x_i, y_i, beta)) ** 2 for x_i, y_i in zip(x, y))\n mean_y = sum(y_i for y_i in y) / len(y)\n SST_2 = sum((y_i - mean_y) ** 2 for y_i in y)\n return 1 - SSR_2 / SST_2\n\n\nif __name__ == \"__main__\":\n # Here, we load the boston dataset\n boston = csv.reader(open('boston.csv')) # The boston housing dataset in csv format\n # First line contains the header, short info for each variable\n header = boston.__next__() # In python2, you might need boston.next() instead\n # Data will hold the 13 data variables, target is what we are trying to predict\n data, target = [], []\n for row in boston:\n # All but the last are the data points\n data.append([float(r) for r in row[:-1]])\n # The last is the median house value we are trying to predict\n target.append(float(row[-1]))\n # Now, use the dataset with your regression functions to answer the exercise questions\n '''\n print(\"Names of the columns\")\n print(header)\n print(\"First row of data ->variable to predict\")\n print(data[0], \" -> \", target[0])\n'''\n\n # The alpha parameter must be tuned low so that we don't jump too far\n # take the starting parameters as 0 for beta0 then the intercepts from the individual fits\n start = [0.011592,-0.041112,-0.066247,0.212368,6.314068,-33.892962,8.915683,0.041870,0.680705,0.069403,0.007788,-1.576933,0.014066,-0.147525]\n output = stochastic_minimize(loss, dloss, data, target, start, 1e-6)\n # Also need to calculate the full R^2!\n #print(R_2(loss, data, target, output))\n\n # Example of writing out the results.txt file\n fout = open('results.txt', 'w')\n for param in output:\n fout.write('%f\\n' % (param))# One line per variable\n fout.write('R squared %f' % (R_2(loss, data, target, output)))\n fout.close()\n\n","sub_path":"05-logistic/dae_multiple.py","file_name":"dae_multiple.py","file_ext":"py","file_size_in_byte":4378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"478539934","text":"\nimport webapp2\nimport jinja2\nimport os\nfrom models import Sporocilo\nfrom google.appengine.api import users\nfrom google.appengine.api import urlfetch\nimport json\n\n\n\ntemplate_dir = os.path.join(os.path.dirname(__file__), \"template\")\njinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=False)\n\n\nclass BaseHandler(webapp2.RequestHandler):\n\n def write(self, *a, **kw):\n return self.response.out.write(*a, **kw)\n\n def render_str(self, template, **params):\n t = jinja_env.get_template(template)\n return t.render(params)\n\n def render(self, template, **kw):\n return self.write(self.render_str(template, **kw))\n\n def render_template(self, view_filename, params=None):\n if not params:\n params = {}\n template = jinja_env.get_template(view_filename)\n return self.response.out.write(template.render(params))\n\n\nclass MainHandler(BaseHandler):\n def get(self):\n user = users.get_current_user()\n if user:\n logiran = True\n logout_url = users.create_logout_url(\"/\")\n params = {\"logiran\": logiran, \"logout_url\": logout_url, \"user\": user}\n else:\n logiran = False\n login_url = users.create_login_url(\"/\")\n params = {\"logiran\": logiran, \"login_url\": login_url, \"user\": user}\n return self.render_template(\"index.html\", params)\n\n\nclass RezultatHandler(BaseHandler):\n def post(self):\n rezultat = self.request.get(\"vnos\")\n rezultat1 = self.request.get(\"datum\")\n sporocilo = Sporocilo(vnos=rezultat, datum=rezultat1)\n sporocilo.put()\n return self.write(rezultat + \" do \" + rezultat1)\n\n\nclass SeznamSporocilHandler(BaseHandler):\n def get(self):\n seznam = Sporocilo.query().fetch()\n params = {\"seznam\": seznam}\n return self.render_template(\"seznam_sporocil.html\", params=params)\n\n\napp = webapp2.WSGIApplication({\n webapp2.Route('/', MainHandler),\n webapp2.Route('/rezultat', RezultatHandler),\n webapp2.Route('/seznam-opravil', SeznamSporocilHandler),\n\n}, debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"205995603","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 10 13:29:04 2018\n\n@author: a118905\n\"\"\"\n\n#Importing the libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\n#loading the dataset, dependant and independant variable\ndataset = pd.read_csv('Churn_Modelling.csv')\n\nX = dataset.iloc[:, 3:13].values\ny = dataset.iloc[:, 13].values\n\n# Encoding categorical (independant) data\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nlabelencoder_X_1 = LabelEncoder()\nX[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])\nlabelencoder_X_2 = LabelEncoder()\nX[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])\n\nonehotencoder = OneHotEncoder(categorical_features= [1])\nX = onehotencoder.fit_transform(X).toarray()\nX = X[:, 1:]\n\n#Spliting dataset training and test\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)\n\n# Feature Scaling \nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)\n\n\n","sub_path":"ANN/ann.py","file_name":"ann.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"617216475","text":"#step #1\n#Change random number\nimport random\ndef change_number(start, end):\n if end > start:\n return(random.randrange(start, end)), start, end\n else:\n print('...The end of the range is less than the beginning')\n return change_number(*input_num())\n\n\n#step #2\n#verified\ndef verified(input_number, sel_number, start, end):\n if start > input_number or input_number > end:\n print('...Nope, this out of range from', start, 'to', end)\n elif input_number > sel_number:\n print('...Nope, this number is too large!')\n return False\n elif input_number < sel_number:\n print('...Nope, this number is too small!')\n return False\n elif input_number == sel_number:\n #congratilation()\n return True \n \n#Welcome banner\ndef welcome_banner(s):\n if s:\n s = 'Welcome to'\n else:\n s = 'You are played in'\n c = 'the game \"Guess Number\"!'\n for i in range(2):\n print('*' * len(s + c))\n print(s, c)\n for i in range(2):\n print('*' * len(s + c))\n\ndef input_num(): \n try:\n start, end = input('Please, choose range: ').split(' ')\n #if end > start: \n # return int(start), int(end)\n #else:\n # print('End range smalled')\n return int(start), int(end)\n except ValueError as e:\n error = str(e)\n if error == 'too many values to unpack (expected 2)':\n print('...Please, input two numbers')\n return input_num()\n elif error.find('invalid literal for int() with base 10:') != -1:\n print('...Please, input only numbers')\n return input_num()\n elif error.find('empty range for randrange') != -1:\n print('...The end of the range is less than the beginning')\n return input_num()\n\n#welcome to game!\nwelcome_banner(1)\n#change number\nsel_number, start, end = change_number(*input_num())\nprint('...So, you choose range from', start, 'to', end)\n\ndef body(sel_number, start, end):\n try:\n s = verified(int(input('Guess, what?: ')), sel_number, start, end)\n except ValueError as e:\n error = str(e)\n if error == 'too many values to unpack':\n print('...Please, input one number')\n elif error.find('invalid literal for int() with base 10:') != -1:\n print('...Please, input only one number')\n s = False\n while not s:\n try:\n inp = int(input('Come on, repeat!: '))\n s = verified(inp, sel_number, start, end)\n except ValueError as e:\n error = str(e)\n if error == 'too many values to unpack':\n print('...Please, input one number')\n elif error.find('invalid literal for int() with base 10:') != -1:\n print('...Please, input only one number')\n s = False\n else:\n print('Yes! You win!')\n #good bye banner\n welcome_banner(0)\n \ntry:\n body(sel_number, start, end) \nexcept ValueError as e:\n error = str(e)\n if error == 'too many values to unpack':\n print('...Please, input one number')\n elif error.find('invalid literal for int() with base 10:') != -1:\n print('...Please, input only one number')\n try:\n body(sel_number, start, end)\n except:\n print('Sorry. Critical error, you input bad value')","sub_path":"python3/Course/guess_number_the_game.py","file_name":"guess_number_the_game.py","file_ext":"py","file_size_in_byte":3387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"364206631","text":"class Othello(object):\n\n def __init__(self):\n super().__init__()\n self.maps = [['#'] * 8 for _ in range(8)]\n self.maps[3][3] = 'W'\n self.maps[4][4] = 'W'\n self.maps[3][4] = 'B'\n self.maps[4][3] = 'B'\n self.d_list = ['U', 'D', 'R', 'L', 'RU', 'RD', 'LU', 'LD']\n\n def set_d(self, color):\n flg = 'W' if color == 'B' else 'B'\n for d in self.d_list:\n yield flg, d\n\n def reverse(self, d, x, y, flg, color):\n c = 0\n while True:\n c += 1\n x, y = self.move(d, x, y)\n result = self.check_stone(x, y, flg)\n if result == 'fail':\n return\n elif result == 'next':\n continue\n elif result == 'decision':\n return c\n\n def check_stone(self, x, y, flg):\n if x < 0 or 7 < x or y < 0 or 7 < y:\n return 'fail'\n elif self.maps[y][x] == '#':\n return 'fail'\n elif self.maps[y][x] == flg:\n return 'next'\n else:\n return 'decision'\n\n def change_color(self, d, x, y, c, color):\n self.maps[y][x] = color\n for _ in range(c):\n x, y = self.move(d, x, y)\n self.maps[y][x] = color\n\n def move(self, d, x, y):\n if d == 'U':\n y -= 1\n elif d == 'D':\n y += 1\n elif d == 'R':\n x += 1\n elif d == 'L':\n x -= 1\n elif d == 'RU':\n x += 1\n y -= 1\n elif d == 'RD':\n x += 1\n y += 1\n elif d == 'LU':\n x -= 1\n y -= 1\n elif d == 'LD':\n x -= 1\n y += 1\n return x, y\n\n def display_result(self):\n B = W = 0\n for line in self.maps:\n for s in line:\n if s == 'B':\n B += 1\n elif s == 'W':\n W += 1\n if W < B:\n print('{0:0>2}-{1:0>2} The black won!'.format(B, W))\n elif B < W:\n print('{0:0>2}-{1:0>2} The white won!'.format(B, W))\n else:\n print('{0:0>2}-{1:0>2} Draw!'.format(B, W))\n\n\ndef f(x, y, color):\n for flg, d in othello.set_d(color):\n res = othello.reverse(d, x, y, flg, color)\n if res:\n othello.change_color(d, x, y, res, color)\n\n\nothello = Othello()\nfor _ in range(int(input())):\n _color, _x, _y = input().split()\n _x, _y = map(int, [_x, _y])\n f(_x - 1, _y - 1, _color)\n\nothello.display_result()\n","sub_path":"takumiy/A/A003_2.py","file_name":"A003_2.py","file_ext":"py","file_size_in_byte":2548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"26055220","text":"#!/usr/bin/python3\n# coding: utf-8\n\"\"\"Classe DeputadoEstadual \"\"\"\n\nfrom Politico import Politico\n\n\nclass DeputadoEstadual(Politico):\n \"\"\" Classe Deputado Estadual \"\"\"\n\n def __init__(self, nome, partido, estado):\n \"\"\" Construtor da classe DeputadoEstadual \"\"\"\n Politico.__init__(self)\n self.set_nome(nome)\n self.set_salario(10000)\n self.set_partido(partido)\n self.set_estado(estado)\n self.set_funcao(\"propor as leis estaduais de interesse da população \")\n\n def apresentacao(self):\n super(DeputadoEstadual, self).apresentacao()\n print ('sou deputado estadual')\n print ('Minha função é ' + self.get_funcao())\n print ('Fui eleito por ' + self.get_estado())\n print ('============================')\n","sub_path":"POO/arquivos-livro/Projetos/Políticos/Python3/DeputadoEstadual.py","file_name":"DeputadoEstadual.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"481805415","text":"\"\"\"\nThis module implements all Humbug methods related to generating reports and publishing them to\nBugout knowledge bases.\n\"\"\"\nimport atexit\nimport concurrent.futures\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nimport os\nimport pkg_resources\nimport sys\nimport time\nimport traceback\nfrom typing import List, Optional\nimport uuid\n\nfrom bugout.app import Bugout\n\nfrom .consent import HumbugConsent\nfrom .system_information import (\n SystemInformation,\n generate as generate_system_information,\n)\n\n\n@dataclass\nclass Report:\n title: str\n content: str\n tags: List[str] = field(default_factory=list)\n\n\nclass Modes(Enum):\n DEFAULT = 0\n SYNCHRONOUS = 1\n\n\nclass Reporter:\n def __init__(\n self,\n name: str,\n consent: HumbugConsent,\n client_id: Optional[str] = None,\n session_id: Optional[str] = None,\n system_information: Optional[SystemInformation] = None,\n bugout_token: Optional[str] = None,\n bugout_journal_id: Optional[str] = None,\n timeout_seconds: int = 10,\n mode: Modes = Modes.DEFAULT,\n ):\n self.name = name\n self.consent = consent\n self.client_id = client_id\n if session_id is not None:\n self.session_id = session_id\n else:\n self.session_id = str(uuid.uuid4())\n if system_information is None:\n system_information = generate_system_information()\n self.system_information = system_information\n self.bugout = Bugout()\n self.bugout_token = bugout_token\n self.bugout_journal_id = bugout_journal_id\n self.timeout_seconds = timeout_seconds\n\n self.report_futures: List[concurrent.futures.Future] = []\n atexit.register(self.wait)\n\n self.executor: Optional[concurrent.futures.Executor] = None\n if mode == Modes.DEFAULT:\n self.executor = concurrent.futures.ThreadPoolExecutor(\n max_workers=1, thread_name_prefix=\"humbug_reporter\"\n )\n\n self.is_excepthook_set = False\n\n def wait(self) -> None:\n concurrent.futures.wait(\n self.report_futures, timeout=float(self.timeout_seconds)\n )\n if self.executor is not None:\n self.executor.shutdown()\n\n def system_tags(self) -> List[str]:\n tags = [\n \"humbug\",\n \"source:{}\".format(self.name),\n \"os:{}\".format(self.system_information.os),\n \"arch:{}\".format(self.system_information.machine),\n \"python:{}\".format(self.system_information.python_version_major),\n \"python:{}.{}\".format(\n self.system_information.python_version_major,\n self.system_information.python_version_minor,\n ),\n \"python:{}\".format(self.system_information.python_version),\n \"session:{}\".format(self.session_id),\n ]\n if self.client_id is not None:\n tags.append(\"client:{}\".format(self.client_id))\n\n return tags\n\n def publish(self, report: Report, wait: bool = False) -> None:\n if not self.consent.check():\n return\n if self.bugout_token is None or self.bugout_journal_id is None:\n return\n\n try:\n report.tags = list(set(report.tags))\n if wait or self.executor is None:\n self.bugout.create_entry(\n token=self.bugout_token,\n journal_id=self.bugout_journal_id,\n title=report.title,\n content=report.content,\n tags=report.tags,\n timeout=self.timeout_seconds,\n )\n else:\n report_future = self.executor.submit(\n self.bugout.create_entry,\n token=self.bugout_token,\n journal_id=self.bugout_journal_id,\n title=report.title,\n content=report.content,\n tags=report.tags,\n timeout=self.timeout_seconds,\n )\n self.report_futures.append(report_future)\n except:\n pass\n\n def custom_report(\n self,\n title: str,\n content: str,\n tags: Optional[List[str]] = None,\n publish: bool = True,\n wait: bool = False,\n ) -> Report:\n \"\"\"\n Generates (and optionally publishes) a custom report in which the title, tags, and content\n are defined by the caller of this method.\n \"\"\"\n if tags is None:\n tags = []\n report = Report(title=title, content=content, tags=tags)\n if publish:\n self.publish(report, wait=wait)\n return report\n\n def system_report(\n self, tags: Optional[List[str]] = None, publish: bool = True, wait: bool = False\n ) -> Report:\n title = \"{}: System information\".format(self.name)\n content = \"\"\"### User timestamp\n```\n{user_time}\n```\n\n### OS\n```\n{os}\n```\n\nRelease: `{os_release}`\n\n### Processor\n```\n{machine}\n```\n\n### Python\n```\n{python_version}\n```\"\"\".format(\n user_time=int(time.time()),\n os=self.system_information.os,\n os_release=self.system_information.os_release,\n machine=self.system_information.machine,\n python_version=self.system_information.python_version,\n )\n report = Report(title=title, content=content, tags=self.system_tags())\n if tags is not None:\n report.tags.extend(tags)\n report.tags.append(\"type:system\")\n\n if publish:\n self.publish(report, wait=wait)\n\n return report\n\n def error_report(\n self,\n error: Exception,\n tags: Optional[List[str]] = None,\n publish: bool = True,\n wait: bool = False,\n ) -> Report:\n title = \"{} - {}\".format(self.name, type(error).__name__)\n error_content = \"\"\"### User timestamp\n```\n{user_time}\n```\n\n### Exception summary\n```\n{error_summary}\n```\n\n### Traceback\n```\n{error_traceback}\n```\"\"\".format(\n user_time=int(time.time()),\n error_summary=repr(error),\n error_traceback=\"\".join(\n traceback.format_exception(\n etype=type(error),\n value=error,\n tb=error.__traceback__,\n )\n ),\n )\n if tags is None:\n tags = []\n tags.append(\"type:error\")\n tags.extend(self.system_tags())\n\n report = Report(title=title, content=error_content, tags=tags)\n\n if publish:\n self.publish(report, wait=wait)\n\n return report\n\n def env_report(\n self,\n title: Optional[str] = None,\n tags: Optional[List[str]] = None,\n publish: bool = True,\n wait: bool = False,\n ) -> Report:\n \"\"\"\n Creates and optionally publishes a report containing the environment variables defined in\n the current process.\n \"\"\"\n if title is None:\n title = \"Environment variables\"\n if tags is None:\n tags = []\n tags.append(\"type:env\")\n\n env_vars = [\"{}={}\".format(key, value) for key, value in os.environ.items()]\n content = \"```\\n{}\\n```\".format(\"\\n\".join(env_vars))\n\n report = Report(title=title, content=content, tags=tags)\n if publish:\n self.publish(report, wait=wait)\n return report\n\n def packages_report(\n self,\n title: Optional[str] = None,\n tags: Optional[List[str]] = None,\n publish: bool = True,\n wait: bool = False,\n ) -> Report:\n \"\"\"\n Creates and optionally publishes a report containing the packages (and versions of those\n packages) available in the current Python process.\n \"\"\"\n if title is None:\n title = \"Available packages\"\n if tags is None:\n tags = []\n tags.append(\"type:dependencies\")\n\n available_packages = [\n str(package_info) for package_info in pkg_resources.working_set\n ]\n content = \"```\\n{}\\n```\".format(\"\\n\".join(available_packages))\n report = Report(title, content, tags)\n if publish:\n self.publish(report, wait=wait)\n return report\n\n def compound_report(\n self,\n reports: List[Report],\n title: Optional[str] = None,\n tags: Optional[List[str]] = None,\n publish: bool = True,\n wait: bool = False,\n ) -> Report:\n if tags is None:\n tags = []\n for component in reports:\n tags.extend(component.tags)\n\n if title is None:\n title = \"Composite report\"\n\n content = \"\\n\\n- - -\\n\\n\".join(component.content for component in reports)\n\n report = Report(title=title, content=content, tags=tags)\n if publish:\n self.publish(report, wait=wait)\n return report\n\n def setup_excepthook(self, tags: Optional[List[str]] = None, publish: bool = True):\n \"\"\"\n Adds error_report with python Exceptions.\n Only one excepthook will be added to stack, no matter how many\n times you call this method.\n\n Docs: https://docs.python.org/3/library/sys.html#sys.excepthook\n \"\"\"\n if not self.is_excepthook_set:\n original_excepthook = sys.excepthook\n\n def _hook(exception_type, exception_instance, traceback):\n self.error_report(error=exception_instance, tags=tags, publish=publish)\n original_excepthook(exception_type, exception_instance, traceback)\n\n sys.excepthook = _hook\n\n self.is_excepthook_set = True\n\n def setup_notebook_excepthook(self, tags: Optional[List[str]] = None):\n \"\"\"\n Excepthook for ipython, works with jupiter notebook.\n \"\"\"\n ipython_shell = get_ipython() # type: ignore\n old_showtraceback = ipython_shell.showtraceback\n\n def showtraceback(*args, **kwargs):\n _, exc_instance, _ = sys.exc_info()\n self.error_report(exc_instance, tags=tags, publish=True)\n old_showtraceback(*args, **kwargs)\n\n ipython_shell.showtraceback = showtraceback\n self.setup_excepthook(publish=True, tags=tags)\n","sub_path":"python/humbug/report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":10297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"376830562","text":"#\n# Copyright 2016 Dohop hf.\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\"\"\"\nTests for the inclusion logic\n\"\"\"\n\nimport os\n\nfrom logstash_notifier import get_value_from_input\nfrom .compat import TestCase\n\n\nclass TestIncludeParser(TestCase):\n \"\"\"\n Tests the parsing of the include options\n \"\"\"\n def test_key_val_parsing(self):\n # Test parsing of keyval strings\n self.assertEqual(\n get_value_from_input('fruits=\"pear,kiwi,banana\"'),\n {'fruits': '\"pear,kiwi,banana\"'}\n )\n self.assertEqual(\n get_value_from_input('berries='),\n {'berries': ''}\n )\n self.assertEqual(\n get_value_from_input('pythagoras=a2+b2=c2'),\n {'pythagoras': 'a2+b2=c2'}\n )\n\n def test_environ_extraction(self):\n # Test inclusion of variables from the environ\n os.environ['vegetables'] = '\"carrot,peas,green beans\"'\n os.environ['smellythings'] = ''\n self.assertEqual(\n get_value_from_input('vegetables'),\n {'vegetables': '\"carrot,peas,green beans\"'}\n )\n self.assertEqual(\n get_value_from_input('smellythings'),\n {'smellythings': ''}\n )\n\n def test_combination(self):\n # Test having both environment vars and arbitrary keyvals\n os.environ['bears'] = 'polar,brown,black'\n os.environ['notbears'] = 'unicorn,griffin,sphinx,otter'\n command_line = ['bears', 'notbears', 'e=mc2', 'v=iR', 'qwertyuiop']\n expected = {\n 'bears': 'polar,brown,black',\n 'notbears': 'unicorn,griffin,sphinx,otter',\n 'e': 'mc2',\n 'v': 'iR',\n }\n result = {}\n for variable in command_line:\n result.update(get_value_from_input(variable))\n\n self.assertDictEqual(result, expected)\n","sub_path":"tests/test_include.py","file_name":"test_include.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"318711696","text":"\"\"\"\nUtility for computing ideal sonar readings\n\"\"\"\n# Updated to use the new Soar's geometry classes\nfrom soar.sim.world import *\nfrom soar.robot.pioneer import PioneerRobot\nfrom soar.sim.geometry import Pose\nfrom lib601 import sonarDist\n\nSONAR_MAX = 1.5\n\n######################################################################\n### Compute ideal readings\n######################################################################\n\ndef compute_ideal_readings(world_path, xMin, xMax, y, numStates, numObs):\n \"\"\"\n @param world_path: string naming file to read the world description from\n @param xMin: minimum x coordinate for center of robot\n @param xMax: maximum x coordinate for center of robot\n @param y: constant y coordinate for center of robot\n @param numStates: number of discrete states into which to divide\n the range of x coordinates\n @param numObs: number of discrete observations into which to\n divide the range of good sonar observations, between 0 and C{goodSonarRange}\n @returns: list of C{numStates} values, each of which is between 0\n and C{numObs-1}, which lists the ideal discretized sonar reading\n that the robot would receive if it were at the midpoint of each of\n the x bins.\n \"\"\"\n\n xStep = (xMax - xMin) / float(numStates)\n readings = []\n # Start in the middle of the first box\n x = xMin + (xStep / 2.0)\n world_namespace = {}\n exec(open(world_path, 'r').read(), world_namespace)\n world = world_namespace['world'] # Grab the world object\n for ix in range(numStates):\n # left-hand sonar reading assuming we're heading to the right\n sensor_pose = sonarDist.sonarPoses[0].x, sonarDist.sonarPoses[0].y, sonarDist.sonarPoses[0].theta\n readings.append(discrete_sonar(ideal_sonar_reading(Pose(x, y, 0), sensor_pose, world), numObs))\n x += xStep\n return readings\n \ndef ideal_sonar_reading(robot_pose, sensor_pose, world):\n \"\"\"\n @param robot_pose: C{util.Pose} representing pose of robot in world\n @param sensor_pose: c{util.Pose} representing pose of sonar sensor\n with respect to the robot\n @param world: C{soarWorld.SoarWorld} representing obstacles in the world\n @returns: length of ideal sonar reading; if the distance is\n longer than C{sonarDist.sonarMax} or there is no hit at all, then\n C{sonarDist.sonarMax} is returned. \n \"\"\"\n # Translate and turn by the robot's pose, then rotate about its center\n origin = robot_pose.transform(sensor_pose).rotate(robot_pose.point(), robot_pose.t)\n sonar_ray = Ray(origin, length=SONAR_MAX, dummy=True)\n # Find all collisions that don't take place with a robot\n collisions = world.find_all_collisions(sonar_ray, eps=1e-3, condition=lambda obj: not isinstance(obj, PioneerRobot))\n if collisions:\n distances = [origin.distance(p) for _, p in collisions]\n distances.sort()\n return distances[0]\n else:\n return SONAR_MAX\n\ndef discrete_sonar(d, numBins, sonarMax = None):\n \"\"\"\n @param d: value of a sonar reading\n @param numBins: number of bins into which to divide the interval\n between 0 and C{sonardist.sonarMax}\n @returns: number of the bin into which this sonar reading should\n fall; any reading greater than or equal to c{sonarDist.sonarMax}\n is put into bin C{numBins - 1}.\n \"\"\"\n if not sonarMax:\n sonarMax = SONAR_MAX\n binSize = sonarMax / numBins\n return int(d / binSize)\n\ndef inv_discrete_sonar(id, numBins, sonarMax = None):\n if not sonarMax:\n sonarMax = sonarDist.sonarMax\n binSize = sonarMax / numBins\n return id * binSize\n\n# Old name, defined here in case somebody depends on it...\ndiscreteSonarValue = discreteSonar = discrete_sonar\n","sub_path":"src/idealReadings.py","file_name":"idealReadings.py","file_ext":"py","file_size_in_byte":3739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"274970159","text":"# import references\nimport copy\n\n\ndef isdict(x):\n return isinstance(x, dict)\ndef istuple(x):\n return isinstance(x, tuple)\ndef isiterable(x):\n return getattr(x, '__iter__', False)\n# def isgensonref(x):\n# return isinstance(x, ScopedReference)\ndef isgensonevaluable(x):\n return getattr(x, '__genson_eval__', False)\n\n\n\n\ndef resolve(x, context = []):\n if isgensonevaluable(x):\n return resolve(x.__genson_eval__(context), context)\n elif isdict(x):\n # build a new copy of the dict\n return_dict = {}\n\n # push down object context stack\n context.append(return_dict)\n\n for k,v in x.items():\n val = resolve(v, context)\n\n # check if we need to do a splat\n if istuple(k):\n if istuple(val):\n if len(k) is not len(val):\n raise Exception(\"Invalid splat\")\n\n for (splat_key,splat_val) in zip(k,val):\n return_dict[splat_key] = resolve(splat_val, context)\n else:\n for splat_key in k:\n return_dict[splat_key] = resolve(val, context)\n else:\n return_dict[k] = val\n\n # pop object context stack\n context.pop()\n\n return return_dict\n # elif isgensonref(x):\n # val = resolve_scoped_reference(copy.deepcopy(x), copy.copy(context))\n # return resolve( val, context )\n\n elif istuple(x):\n return_list = []\n for v in x:\n return_list.append(resolve(v, context))\n return tuple(return_list)\n elif isiterable(x):\n return_list = []\n for v in x:\n return_list.append(resolve(v, context))\n return return_list\n else:\n return x\n","sub_path":"genson/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"375627920","text":"import shutil\nfrom pathlib import Path\n\nimport pytest\nimport requests\n\nfrom pandas_profiling.controller import console\n\n\n@pytest.fixture(scope=\"module\")\ndef data_dir(tmpdir_factory):\n data_path = Path(str(tmpdir_factory.mktemp(\"test_console\")))\n file_name = data_path / \"rows.csv\"\n if not file_name.exists():\n data = requests.get(\n \"https://data.nasa.gov/api/views/gh4g-9sfh/rows.csv?accessType=DOWNLOAD\"\n )\n file_name.write_bytes(data.content)\n yield data_path\n shutil.rmtree(str(data_path))\n\n\ndef test_console_multiprocessing(data_dir):\n report = data_dir / \"test_samples.html\"\n console.main([\"-s\", \"--pool_size\", \"0\", str(data_dir / \"rows.csv\"), str(report)])\n assert report.exists(), \"Report should exist\"\n\n\ndef test_console_single_core(data_dir):\n report = data_dir / \"test_single_core.html\"\n console.main([\"-s\", \"--pool_size\", \"1\", str(data_dir / \"rows.csv\"), str(report)])\n assert report.exists(), \"Report should exist\"\n","sub_path":"tests/unit/test_console.py","file_name":"test_console.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"346067258","text":"import operator\n\nfrom ..utils import Sentinel\n\n\nclass IndexCallable:\n \"\"\"Provide getitem syntax for functions\n\n >>> def inc(x):\n ... return x + 1\n\n >>> I = IndexCallable(inc)\n >>> I[3]\n 4\n\n Vendored from dask\n \"\"\"\n\n __slots__ = (\"fn\",)\n\n def __init__(self, fn):\n self.fn = fn\n\n def __getitem__(self, key):\n return self.fn(key)\n\n\nclass IndexersMixin:\n \"\"\"\n Provides slicable attributes keys_indexes, items_indexer, values_indexer.\n\n Must be mixed in with a class that defines methods:\n\n * ``_item_by_index``\n * ``_keys_slice``\n * ``_items_slice``\n \"\"\"\n\n __slots__ = (\n \"keys_indexer\",\n \"items_indexer\",\n \"values_indexer\",\n )\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.keys_indexer = IndexCallable(self._keys_indexer)\n self.items_indexer = IndexCallable(self._items_indexer)\n self.values_indexer = IndexCallable(self._values_indexer)\n\n # There is some code reptition here, but let's live with it rather than add\n # yet more depth to the call stack....\n\n def _keys_indexer(self, index_or_slice):\n if isinstance(index_or_slice, int):\n if index_or_slice < 0:\n index_or_slice = -1 - index_or_slice\n direction = -1\n else:\n direction = 1\n key, _value = self._item_by_index(index_or_slice, direction)\n return key\n elif isinstance(index_or_slice, slice):\n start, stop, direction = slice_to_interval(index_or_slice)\n return list(self._keys_slice(start, stop, direction))\n else:\n raise TypeError(\n f\"{index_or_slice} must be an int or slice, not {type(index_or_slice)}\"\n )\n\n def _items_indexer(self, index_or_slice):\n if isinstance(index_or_slice, int):\n if index_or_slice < 0:\n index_or_slice = -1 - index_or_slice\n direction = -1\n else:\n direction = 1\n return self._item_by_index(index_or_slice, direction)\n elif isinstance(index_or_slice, slice):\n start, stop, direction = slice_to_interval(index_or_slice)\n return list(self._items_slice(start, stop, direction))\n else:\n raise TypeError(\n f\"{index_or_slice} must be an int or slice, not {type(index_or_slice)}\"\n )\n\n def _values_indexer(self, index_or_slice):\n if isinstance(index_or_slice, int):\n if index_or_slice < 0:\n index_or_slice = -1 - index_or_slice\n direction = -1\n else:\n direction = 1\n _key, value = self._item_by_index(index_or_slice, direction)\n return value\n elif isinstance(index_or_slice, slice):\n start, stop, direction = slice_to_interval(index_or_slice)\n return [value for _key, value in self._items_slice(start, stop, direction)]\n else:\n raise TypeError(\n f\"{index_or_slice} must be an int or slice, not {type(index_or_slice)}\"\n )\n\n\ndef slice_to_interval(slice_):\n \"\"\"\n Convert slice object to (start, stop, direction).\n \"\"\"\n start = slice_.start or 0 # Handles case where slice_.start is None.\n step = slice_.step or 1 # Handles case where slice_.step is None.\n if step == 1:\n if start < 0:\n raise ValueError(\n \"Tree sequence slices with start < 0 must have step=-1. \"\n f\"Use for example [{slice_.start}:{slice_.stop}:-1]\"\n \"(This is a limitation of slicing on Tree sequences \"\n \"that does not apply to Python sequences in general.)\"\n )\n if (slice_.stop is not None) and (slice_.stop < start):\n raise ValueError(\n \"Tree sequence slices with step=1 must have stop >= start. \"\n \"(This is a limitation of slicing on Tree sequences \"\n \"that does not apply to Python sequences in general.)\"\n )\n start_ = start\n stop_ = slice_.stop\n direction = 1\n elif step == -1:\n if start >= 0:\n raise ValueError(\n \"Tree sequence slices with start >= 0 must have step=1. \"\n \"(This is a limitation of slicing on Tree sequences \"\n \"that does not apply to Python sequences in general.)\"\n )\n if slice_.stop is not None:\n if slice_.stop > start:\n raise ValueError(\n \"Tree sequence slices with step=-1 must have stop <= start.\"\n )\n stop_ = 1 - slice_.stop\n else:\n stop_ = slice_.stop\n start_ = 1 - start\n direction = -1\n else:\n raise ValueError(\n \"Only step of 1 or -1 is supported in a Tree sequence slice. \"\n f\"Step {slice_.step} is disallowed.\"\n )\n assert start_ >= 0\n assert (stop_ is None) or (stop_ >= start_)\n return start_, stop_, direction\n\n\nUNCHANGED = Sentinel(\"UNCHANGED\")\n\n\ndef tree_repr(tree, sample):\n sample_reprs = list(map(repr, sample))\n out = f\"<{type(tree).__name__} {{\"\n # Always show at least one.\n if sample_reprs:\n out += sample_reprs[0]\n # And then show as many more as we can fit on one line.\n counter = 1\n for sample_repr in sample_reprs[1:]:\n if len(out) + len(sample_repr) > 60: # character count\n break\n out += \", \" + sample_repr\n counter += 1\n approx_len = operator.length_hint(tree) # cheaper to compute than len(tree)\n # Are there more in the tree that what we displayed above?\n if approx_len > counter:\n out += f\", ...}} ~{approx_len} entries>\"\n else:\n out += \"}>\"\n return out\n","sub_path":"tiled/trees/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"103496269","text":"'''\nThis module contains the functions needed for parsing the necessary information\nfrom the ADF output file for calculating the Raman peak intensities based on\nthe Polarizability Tensor, centers of vibration, atom positions, bonds,\nand Polarizability Gradient.\n'''\n\nimport math\nimport re\nimport numpy as np\n\n# Finds positions for the atoms\ndef find_atoms(filename):\n\n '''\n This function finds the atoms and their x, y, z coordinates.\n '''\n\n atom_data = np.array([])\n\n with open(filename) as my_file:\n for num, line in enumerate(my_file, 1):\n if 'ATOMS' in line:\n atoms_num = num\n break\n for num, line in enumerate(my_file, 1):\n if 'END' in line:\n end_num = num + atoms_num\n break\n\n with open(filename) as my_file:\n for num, line in enumerate(my_file, 1):\n if num in range(atoms_num+1, end_num):\n full_atom = np.array(\n re.findall(r\"[-+]?\\d*\\.\\d+|\\d+\", line)).astype(np.float)\n atom_data = np.append(atom_data, full_atom, axis=0)\n my_file.close()\n\n atom_data = np.reshape(atom_data, (len(atom_data)/len(full_atom),\n len(full_atom)))\n atom_data = np.delete(atom_data, 0, 1)\n\n return atom_data\n\ndef find_bonds(filename, atom_data):\n '''\n Finds the bonds between atoms for plotting purposes.\n '''\n\n raw_bond_data = np.array([], dtype=int)\n\n with open(filename) as my_file:\n for num, line in enumerate(my_file, 1):\n if 'GUIBONDS' in line:\n atoms_num = num\n break\n for num, line in enumerate(my_file, 1):\n if 'END' in line:\n end_num = num + atoms_num\n break\n my_file.close()\n\n with open(filename) as my_file:\n for num, line in enumerate(my_file, 1):\n if num in range(atoms_num+1, end_num):\n full_bond = np.array(re.findall(r\"[-+]?\\d*\\.\\d+|\\d+\", line)).astype(np.float)\n raw_bond_data = np.append(raw_bond_data, full_bond, axis=0)\n my_file.close()\n raw_bond_data = np.reshape(raw_bond_data, (len(raw_bond_data)/\n len(full_bond),\n len(full_bond)))\n raw_bond_data = np.delete(raw_bond_data, 0, 1)\n\n bond_data_x = np.array([])\n bond_data_y = np.array([])\n bond_data_z = np.array([])\n\n bond_data_x = np.column_stack(\n (atom_data[raw_bond_data[range(raw_bond_data.shape[0]),\n [0]].astype(int)-1, [0]],\n atom_data[raw_bond_data[range(raw_bond_data.shape[0]),\n [1]].astype(int)-1, [0]]))\n bond_data_y = np.column_stack(\n (atom_data[raw_bond_data[range(raw_bond_data.shape[0]),\n [0]].astype(int)-1, [1]],\n atom_data[raw_bond_data[range(raw_bond_data.shape[0]),\n [1]].astype(int)-1, [1]]))\n bond_data_z = np.column_stack(\n (atom_data[raw_bond_data[range(raw_bond_data.shape[0]),\n [0]].astype(int)-1, [2]],\n atom_data[raw_bond_data[range(raw_bond_data.shape[0]),\n [1]].astype(int)-1, [2]]))\n\n\n return bond_data_x, bond_data_y, bond_data_z\n\ndef find_frequencies(filename):\n '''\n Finds the frequencies from the output file.\n '''\n raw_freq_data = np.array([])\n with open(filename) as my_file:\n freq_len = 0\n not_found = True\n for line in my_file:\n if 'X,X' in line:\n if not_found:\n not_found = False\n freq_len += 1\n with open(filename) as my_file:\n for num, line in enumerate(my_file, 1):\n if 'cm-1' in line:\n # print line\n freq_num = num+2\n with open(filename) as my_file:\n for num, line in enumerate(my_file, 1):\n if num in range(freq_num, freq_num+freq_len):\n full_freq = np.array(\n re.findall(r\"[-+]?\\d*\\.\\d+|\\d+\", line)).astype(np.float)\n raw_freq_data = np.append(raw_freq_data, full_freq, axis=0)\n raw_freq_data = np.reshape(raw_freq_data,\n (len(raw_freq_data)/len(full_freq),\n len(full_freq)))\n frequencies = raw_freq_data[range(freq_len), [0]]\n return frequencies\n\ndef find_alpha_tensor(filename):\n '''\n Find the Polarizability Tensor alpha.\n '''\n\n raw_alpha_data = np.array([])\n\n frequencies = find_frequencies(filename)\n\n with open(filename) as my_file:\n for num, line in enumerate(my_file, 1):\n if 'Polarizability Derivatives' in line:\n # print line\n alpha_num = num\n with open(filename) as my_file:\n for num, line in enumerate(my_file, 1):\n if num in range(alpha_num+5, alpha_num+len(frequencies)+5):\n full_alpha = np.array(\n re.findall(r\"[-+]?\\d*\\.\\d+|\\d+\", line)).astype(np.float)\n raw_alpha_data = np.append(raw_alpha_data, full_alpha, axis=0)\n\n raw_alpha_data = np.reshape(raw_alpha_data,\n (len(raw_alpha_data)/len(full_alpha),\n len(full_alpha)))\n raw_alpha_data = np.delete(raw_alpha_data, 0, 1)\n alpha_tensor = np.zeros((len(raw_alpha_data), 3, 3))\n for num, row in enumerate(raw_alpha_data):\n alpha_tensor[num][0][0] = row[0]\n alpha_tensor[num][0][1] = row[1]\n alpha_tensor[num][0][2] = row[4]\n alpha_tensor[num][1][0] = row[1]\n alpha_tensor[num][1][1] = row[2]\n alpha_tensor[num][1][2] = row[3]\n alpha_tensor[num][2][0] = row[4]\n alpha_tensor[num][2][1] = row[3]\n alpha_tensor[num][2][2] = row[5]\n\n return alpha_tensor\n\ndef find_a_tensor(filename):\n '''\n Finds the Gradient Polarizability Tensor denoted 'A'\n '''\n\n a_tensor = np.array([])\n raw_a_data = np.array([])\n\n with open(filename) as my_file:\n for num, line in enumerate(my_file, 1):\n if 'X,X' in line:\n freq_x_num = num\n break\n\n with open(filename) as my_file:\n for num, line in enumerate(my_file, 1):\n if 'Z,Z' in line:\n freq_z_num = num\n\n with open(filename) as my_file:\n for num, line in enumerate(my_file, 1):\n if num in range(freq_x_num, freq_z_num+1):\n full_a = np.array(re.findall(r\"[-+]?\\d*\\.\\d+|\\d+\", line)).astype(np.float)\n full_a = full_a[range(len(full_a)-3, len(full_a))]\n raw_a_data = np.append(raw_a_data, full_a, axis=0)\n\n raw_a_data = np.reshape(raw_a_data, (len(raw_a_data)/len(full_a),\n len(full_a)))\n\n a_tensor = raw_a_data.reshape(len(raw_a_data)/9, 3, 3, 3)\n\n return a_tensor\n\ndef find_displacement_indicies(filename):\n '''\n Finds the indicies for the displacement funciton.\n '''\n\n atoms_num = []\n end_num = []\n\n with open(filename) as my_file:\n for num, line in enumerate(my_file, 1):\n if 'Vibrations and Normal Modes' in line:\n vibration_start = num\n if 'ATOMS' in line:\n atoms_num.append(num)\n if 'END' in line:\n end_num.append(num)\n\n no_of_atoms = end_num[0] - atoms_num[0] - 1\n\n last_atom = vibration_start + 8 + no_of_atoms\n\n with open(filename) as my_file:\n for num, line in enumerate(my_file, 1):\n if num == last_atom:\n break\n\n last_atom_name = re.findall(r\"[-+]?\\S*\\.\\S+|\\S+\", line)[0]\n last_atoms = np.array([])\n\n with open(filename) as my_file:\n for num, line in enumerate(my_file, 1):\n if last_atom_name in line:\n last_atoms = np.append(last_atoms, num).astype(np.int)\n\n last_atoms = np.array([atom for atom in last_atoms if atom >= last_atom])\n first_atoms = last_atoms - no_of_atoms + 1\n\n indecies = np.hstack([range(first_atoms[i], last_atoms[i]+1) for i in\n range(len(first_atoms))])\n\n return indecies, no_of_atoms\n\ndef find_displacements(filename):\n '''\n Finds the magnitudes of displacement for each vibrational mode.\n '''\n\n indecies, no_of_atoms = find_displacement_indicies(filename)\n\n frequencies = find_frequencies(filename)\n\n temp_displacements = np.array([])\n displacements = np.zeros([len(frequencies), no_of_atoms, 3])\n\n with open(filename) as my_file:\n for num, line in enumerate(my_file, 1):\n if num in indecies:\n full_displacements = np.array(\n re.findall(r\"[-+]?\\d*\\.\\d+|\\d+\", line)).astype(np.float)\n temp_displacements = np.append(\n temp_displacements,\n full_displacements[range(len(full_displacements)-9,\n len(full_displacements))],\n axis=0)\n\n temp_displacements = np.reshape(temp_displacements, (frequencies.shape[0]/3,\n no_of_atoms, 9))\n for array in range(len(temp_displacements)):\n displacements[3*array, :, :] = np.column_stack(\n temp_displacements[array, :, range(3)].reshape(3, no_of_atoms))\n displacements[3*array+1, :, :] = np.column_stack(\n temp_displacements[array, :, range(3, 6)].reshape(3, no_of_atoms))\n displacements[3*array+2, :, :] = np.column_stack(\n temp_displacements[array, :, range(6, 9)].reshape(3, no_of_atoms))\n\n return displacements\n\ndef find_centers(filename, atom_data):\n '''\n Finds centers of vibration for each vibrational frequency\n '''\n\n displacements = find_displacements(filename)\n frequencies = find_frequencies(filename)\n\n # no_of_frequencies = len(frequencies)\n no_of_atoms = len(atom_data)\n\n amplitude = np.zeros(no_of_atoms)\n center_of_vibration = np.zeros(len(frequencies)*3)\n\n for freq in range(len(frequencies)):\n vibration = np.zeros(3)\n for atom_num, atom in enumerate(displacements[freq, :, :]):\n amplitude[atom_num] = math.sqrt(\n (atom[0])**2 + (atom[1])**2 + (atom[2])**2)\n total_amplitude = sum(amplitude)\n\n for atom_num in range(no_of_atoms):\n vibration += atom_data[atom_num]*amplitude[atom_num]/total_amplitude\n center_of_vibration[range(freq*3, freq*3+3)] = vibration\n\n center_of_vibration = center_of_vibration.reshape(\n len(center_of_vibration)/3, 3)\n\n return center_of_vibration\n","sub_path":"src/parse_data.py","file_name":"parse_data.py","file_ext":"py","file_size_in_byte":10738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"631425552","text":"def triangulo(x):\r\n\tfor i in range(1, x + 1):\r\n\t\tfor e in range(1,i):\r\n\t\t\tprint(\"*\", end='')\r\n\t\tprint(\"*\")\r\nreintentar = True\r\nwhile reintentar:\r\n\ttriangulo(int(input(\"ingrese el numero de lineas que desee \\n\")))\r\n\tx = int(input(\"1: reintentar. \\n 2: salir. \\n\"))\t\t\t\r\n\tif x == 1:\r\n\t\treintentar = True\r\n\telse: reintentar = False\t\t\t\t","sub_path":"practicas python/triangulo.py","file_name":"triangulo.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"539386095","text":"# Christina Ou\n# AndrewID: cou\n# term project\n# previous files and versions are in backups folder\n# Used Panda3D and Blender\n# Blender to create the models which are borrowed from turbosquid\n# and to position the models to simulate moving\n\n# Using Panda3D's libraries to enact the 3D model of my aquarium\n\n# Aquarium\n\n# Panda imports to enable what I'm doing\nfrom direct.showbase.ShowBase import ShowBase\nfrom panda3d.core import TextNode, NodePath, LightAttrib\nfrom direct.actor.Actor import Actor\nfrom direct.gui.OnscreenText import OnscreenText\nimport sys\nfrom direct.interval.IntervalGlobal import *\n\nimport random\n\n# FYI: some of the uncommented code is for my own testing purposes\n\n\nclass fishTank(ShowBase):\n\n def __init__(self):\n # Initialize the ShowBase class from which we inherit, which will\n # create a window and set up everything we need for rendering into it.\n ShowBase.__init__(self) # borrowed from Panda3D's showbase class\n\n base.setBackgroundColor(0, 0, 0) # set background black\n # This code puts the standard title and instruction text on screen\n # format borrowed\n self.title = OnscreenText(text=\"\",\n fg=(1, 1, 1, 1), parent=base.a2dBottomRight,\n align=TextNode.ARight, pos=(-0.1, 0.1),\n shadow=(0, 0, 0, .5), scale=.08)\n\n # Set up key input, borrowed\n self.accept('escape', sys.exit)\n\n # set initial camera position\n # base.disableMouse() # Disable mouse-based camera-control\n # x, y, z is actually i, k, j Position the camera\n base.trackball.node().setPos(0, 150, -20) # starting position of camera\n base.trackball.node().setHpr(0,0,0)\n\n # positioning is x, -y, z, where x is i, -y is k, z is j\n self.marker = self.loader.loadModel(\"models/marker_01\")\n self.marker.reparentTo(self.render)\n self.marker.setPos(0, 0, 30)\n\n # positioning is x, -y, z, where x is i, -y is k, z is j\n self.marker3 = self.loader.loadModel(\"models/marker_01\")\n self.marker3.reparentTo(self.render)\n self.marker3.setPos(0, 0, 0)\n\n self.wood = self.loader.loadModel(\"models/wood_0\")\n woodTex = loader.loadTexture(\"tex/L1.jpg\")\n self.wood.setTexture(woodTex)\n self.wood.reparentTo(self.render)\n self.wood.setScale(20,20,20)\n self.wood.setPos(5, 2, 0)\n\n # call method to create tank model\n self.createTank()\n # get the dimensions (scale, width, height, length of present tank)\n tankDims = self.getTankDims()\n\n # keep track of all the fish\n self.fishList = []\n # types of fish; there are 4 right now\n\n # fish1 contains models of fish rightbend, leftbend, and centered\n # also stores the image jpg of the fish for its texture\n fish1 = [\"models/fish1bend-1\", \"models/fish1bend2-1\", \n \"models/fish1front_04\", 'tex/TropicalFish01.jpg']\n # pos1 = (-22, 35, 30)\n pos1 = (0, 0, 15)\n self.fishOne = Fish(fish1, pos1, tankDims) # instantiated in fish class\n\n # repeat for a total of 4 fish\n fish2 = [\"models/tang_right_00\", \"models/tang_left_01\", \n \"models/tang_02\", \"tex/TropicalFish02.jpg\"]\n # pos2 = (22, 35, 30)\n pos2 = (0, 0, 15)\n self.fishTwo = Fish(fish2, pos2, tankDims)\n # 22 35 30 is where top left forward corner is\n\n fish3 = [\"models/nemo_right_2\", \"models/nemo_left_2\", \n \"models/nemo_front_2\", \"tex/TropicalFish12.jpg\"]\n # pos3 = (0, 0, 4)\n pos3 = (0, 0, 15)\n self.fishThree = Fish(fish3, pos3, tankDims)\n\n fish4 = [\"models/yellow_right_0\", \"models/yellow_left_0\", \n \"models/yellow_front_0\", \"tex/TropicalFish05.jpg\"]\n # pos4 = (22, -35, 30)\n pos4 = (0, 0, 15)\n self.fishFour = Fish(fish4, pos4, tankDims)\n\n self.fishList = ([self.fishOne] + [self.fishTwo] + \n [self.fishThree] + [self.fishFour])\n\n # move/run the movement\n for fish in self.fishList:\n fish.move()\n # self.fishThree.move()\n # self.fishTwo.move()\n # self.fishOne.move()\n\n\n def createTank(self):\n # loader.loadModel borrowed from Panda3D's first program example\n # models from Blender\n self.sides = self.loader.loadModel(\"models/tanksides_03\")\n # set texture from image\n sidesTex = loader.loadTexture(\"tex/blue.png\")\n self.sides.setTexture(sidesTex)\n # attach the model to render so it appears in window\n self.sides.reparentTo(self.render)\n\n self.tankLength, self.tankWidth, self.tankHeight = 3, 2, 2\n self.tankScale = 15\n\n # Apply scale and position transforms on the model.\n # make the model 15x larger\n self.sides.setScale(self.tankScale, self.tankScale, self.tankScale)\n self.sides.setPos(0, 0, 0) # set the position\n\n # do same for bottom of tank, bottom is sand color \n self.bottom = self.loader.loadModel(\"models/tankbott_05\")\n bottomTex = loader.loadTexture(\"tex/sand.jpg\")\n self.bottom.setTexture(bottomTex)\n self.bottom.reparentTo(self.render)\n self.bottom.setScale(self.tankScale, self.tankScale, self.tankScale)\n self.bottom.setPos(0,0,0)\n\n def getTankDims(self):\n return self.tankScale, self.tankLength, self.tankWidth, self.tankHeight\n\n# fish class for each instance of the fish\n# need to specify what type, which position\n# everythingFish contains all the methods necessary for a Fish\n# contains more than 1 fish needs, so it's the superclass of Fish\nclass EverythingFish(fishTank):\n\n def __init__(self, fishModel, position, tankDims):\n # I have 3 fish models for each one instance.\n # This is due to me creating an animation out of frames of the fish\n # To make them \"move\", I have a fish with 3 positions: tail straight,\n # tail bending right, and tail bending left\n\n # use loader to load the model of the fish\n # don't need panda's \"actors\" because I'm not utilizig Blender's\n # animation technique\n self.fishR = loader.loadModel(fishModel[0])\n # syntax for loading the fish from Panda3d website\n fishTex = loader.loadTexture(fishModel[3])\n self.fishR.setTexture(fishTex)\n self.fishR.reparentTo(render)\n\n # create alternate fish the left tail position (from fish perspective)\n self.fishL = loader.loadModel(fishModel[1])\n self.fishL.setTexture(fishTex)\n self.fishL.reparentTo(render)\n \n self.fishFront = loader.loadModel(fishModel[2])\n self.fishFront.setTexture(fishTex) # use same previous fishTex\n self.fishFront.reparentTo(render)\n\n # start with just one model\n self.fishR.hide()\n self.fishFront.hide()\n\n # initialize how far the fish moves each time\n self.xPosition = position[0]\n self.yPosition = position[1]\n self.zPosition = position[2]\n\n self.fishL.setPos((self.xPosition, self.yPosition, self.zPosition))\n # starting fish image set to the positions\n\n # initialize initial direction\n # change will see which direction the fish is going next time\n self.yChange = -1 # start by going forward\n self.xChange = 0\n self.zChange = 0\n\n # initialize pitch and heading move each time the fish turns\n self.pitchChange = 0\n self.headingChange = 0\n\n # set a variable so not turning every sequence call\n self.fishTurn = 0\n\n self.tankScale, self.tankLength, self.tankWidth, self.tankHeight = tankDims\n self.hitBound = False\n\n # every time I move the tail, I also move the fish. I take in how much the \n # z and x are changing and increment the positions of the fish's z and x\n\n # When I \"move\" the fish, I am essentially looking at a different snapshot \n # of the fish that is set to a new position so it gives the illusion of \n # \"moving forward\". To accomplish this, I need to hide the other images \n # of the fish, and set the new fish's position to the \"moving forward\" one\n # Then I show that fish, and it has moved forward. Voila!\n def moveTailLeft(self):\n # increment the distance of the fish\n self.checkBounds()\n self.yPosition += self.yChange\n self.xPosition += self.xChange\n self.zPosition += self.zChange\n\n self.fishR.hide()\n self.fishFront.hide()\n # fish is moving in x,z,y space\n self.fishL.setPos((self.xPosition, self.yPosition, self.zPosition))\n self.fishL.show()\n\n def moveTailRight(self):\n self.checkBounds()\n self.yPosition += self.yChange\n self.xPosition += self.xChange\n self.zPosition += self.zChange\n\n self.fishL.hide()\n self.fishFront.hide()\n self.fishR.setPos((self.xPosition, self.yPosition, self.zPosition))\n self.fishR.show()\n\n def moveTailCenter(self):\n self.checkBounds()\n self.yPosition += self.yChange\n self.xPosition += self.xChange\n self.zPosition += self.zChange\n \n self.fishL.hide()\n self.fishR.hide()\n self.fishFront.setPos((self.xPosition, self.yPosition, self.zPosition))\n self.fishFront.show()\n\n # turning the fish 45 degrees each time. need to make sure to change\n # how much x and z changes according to the direction the fish is facing\n def leftRightFish(self, numm):\n self.fishTurn += 1\n # self.fishTurn sets how far the fish moves before turning\n if self.fishTurn < 3: \n return\n else:\n self.fishTurn = 0\n # random which direction\n if numm == 0:\n self.pitchChange = (self.pitchChange+45)%360 # turn left\n elif numm == 1:\n self.pitchChange = (360 + self.pitchChange - 45)%360 # turn right\n # coordinate changes for which way the fish is facing\n # Using the x and z axis\n if self.pitchChange == 0:\n self.xChange, self.yChange = 0, -1\n elif self.pitchChange == 45:\n self.xChange, self.yChange = +1, -1\n elif self.pitchChange == 90:\n self.xChange, self.yChange = +1, 0\n elif self.pitchChange == 135:\n self.xChange, self.yChange = +1, +1\n elif self.pitchChange == 180:\n self.xChange, self.yChange = 0, +1\n elif self.pitchChange == 225:\n self.xChange, self.yChange = -1, +1\n elif self.pitchChange == 270:\n self.xChange, self.yChange = -1, 0\n elif self.pitchChange == 315:\n self.xChange, self.yChange = -1, -1\n self.fishL.setHpr((self.pitchChange, self.headingChange, 0))\n self.fishR.setHpr((self.pitchChange, self.headingChange, 0))\n self.fishFront.setHpr((self.pitchChange, self.headingChange, 0))\n\n # appends these movements for a moveStraight movement\n # eventually also create a turn method that modifies/adds on to the \n # sequence\n # This is the crux of moving the fish. Credits to Panda3D library for \n # helping me figure out how to loop through functions through its Sequence\n # method. In this sequence, I loop through moving the tail from center to\n # left back to center to right. Then I turn the fish. In between each, I \n # have the program wait for a period of time so that we can see each frame.\n def moveStraight(self, seq):\n seq.append(Wait(.15))\n seq.append(Func(self.moveTailCenter))\n seq.append(Wait(.15))\n seq.append(Func(self.moveTailLeft))\n seq.append(Wait(.15))\n seq.append(Func(self.moveTailCenter))\n seq.append(Wait(.15))\n seq.append(Func(self.moveTailRight))\n\n # move fish up or down\n # includes pointing nose of fish up or down, then \"y\" axis shift\n def upDownFish(self, numm):\n # restrict to 30 degree angle\n if numm == 0 and self.headingChange > -30: # moving up\n self.headingChange -= 30 # angle fish pointing up\n self.zChange += 1\n\n elif numm == 1 and self.headingChange < 30: # moving down\n self.headingChange += 30\n self.zChange -= 1\n\n else:\n self.headingChange = 0\n self.zChange = 0\n\n # set the new rotation for each of the models\n self.fishL.setHpr((self.pitchChange, self.headingChange, 0))\n self.fishR.setHpr((self.pitchChange, self.headingChange, 0))\n self.fishFront.setHpr((self.pitchChange, self.headingChange, 0))\n\n def checkBounds(self):\n zLimit = self.tankHeight*self.tankScale\n xLimit = self.tankScale*self.tankLength\n yLimit = self.tankScale*self.tankWidth\n zmargin = 5\n xymargin = 10\n # print(self.xPosition, self.yPosition, self.zPosition)\n if self.zPosition < zmargin - 1: # actual basically bottom is 4\n # print(\"z low\")\n self.upDownFish(0) # make fish move up\n return True\n if self.zPosition > zLimit - zmargin: # actual basically top is 30\n # print(\"z high\")\n self.upDownFish(1)\n return True\n\n if self.xPosition > xLimit - xymargin:\n if self.pitchChange < 90:\n self.leftRightFish(1)\n else: self.leftRightFish(0)\n return True\n\n if self.yPosition > yLimit - xymargin:\n # print(\"y high\")\n if self.pitchChange >= 180 or self.pitchChange == 0:\n self.leftRightFish(0)\n else: self.leftRightFish(1)\n return True\n\n if self.xPosition < -xLimit + xymargin:\n # print(\"x low\")\n if self.pitchChange < 270 and self.pitchChange != 0:\n self.leftRightFish(1)\n else: \n self.leftRightFish(0)\n return True\n\n if self.yPosition < -yLimit + zmargin:\n # print(\"y low\")\n if self.pitchChange < 180:\n self.leftRightFish(0)\n else: self.leftRightFish(1)\n return True\n return False\n\n def UDLRFish(self):\n if self.checkBounds() != True:\n numm = random.randint(0,2) # turnLR or UD 2/3 of the time\n if numm == 1 or numm == 2: # random L or R turn\n leftrightNum = random.randint(0,1)\n self.leftRightFish(leftrightNum)\n # otherwise move up or down\n elif numm == 0: # random U or D motion\n updownNum = random.randint(0, 1)\n self.upDownFish(updownNum)\n\n\n\nclass Fish(EverythingFish):\n\n def __init__(self, fishModel, position, tankDims):\n EverythingFish.__init__(self, fishModel, position, tankDims)\n\n # create a sequence, a loop of functions. call the superclasses' methods\n # to add to the sequence of these fish\n def move(self):\n seq = Sequence()\n self.moveStraight(seq)\n seq.append(Func(self.UDLRFish))\n seq.loop()\n\n\n\n\n\n# Now that our class is defined, we create an instance of it.\n# Doing so calls the __init__ method set up above\ntank = fishTank() # Create an instance of our class\ntank.run() # Run the simulation\n\n\n","sub_path":"backups/noActors.py","file_name":"noActors.py","file_ext":"py","file_size_in_byte":15249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"425996266","text":"import json\nimport urllib\n\nimport re\nfrom bs4 import BeautifulSoup\nfrom decimal import Decimal\n\nfrom storescraper.product import Product\nfrom storescraper.store import Store\nfrom storescraper.utils import session_with_proxy, html_to_markdown, \\\n check_ean13\n\n\nclass MegaMatute(Store):\n @classmethod\n def categories(cls):\n return [\n 'StorageDrive',\n 'ExternalStorageDrive',\n 'MemoryCard',\n 'UsbFlashDrive',\n 'SolidStateDrive',\n ]\n\n @classmethod\n def discover_urls_for_category(cls, category, extra_args=None):\n category_paths = [\n ['C:/164/168/170/', 'StorageDrive'],\n ['C:/164/168/169/', 'ExternalStorageDrive'],\n ['C:/164/168/172/', 'SolidStateDrive'],\n ['C:/164/168/173/', 'UsbFlashDrive'],\n ['C:/8/116/118/', 'MemoryCard'],\n ]\n\n product_urls = []\n session = session_with_proxy(extra_args)\n\n for category_path, local_category in category_paths:\n if local_category != category:\n continue\n\n page = 1\n\n while True:\n category_url = \\\n 'http://www.megamamute.com.br/buscapagina?fq={}&PS=16&' \\\n 'sl=45e718bf-51b0-49c4-8882-725649af0594' \\\n '&cc=3&sm=0&PageNumber={}' \\\n ''.format(urllib.parse.quote(category_path), page)\n\n if page >= 10:\n raise Exception('Page overflow: ' + category_url)\n\n print(category_url)\n\n soup = BeautifulSoup(session.get(category_url).text,\n 'html.parser')\n\n containers = soup.findAll('div', 'x-product')\n\n if not containers:\n if page == 1:\n raise Exception('Empty category: ' + category_url)\n break\n\n for container in containers:\n product_url = container.find('h2').find('a')['href']\n product_urls.append(product_url)\n\n page += 1\n\n return product_urls\n\n @classmethod\n def products_for_url(cls, url, category=None, extra_args=None):\n session = session_with_proxy(extra_args)\n response = session.get(url)\n\n if response.url != url:\n return []\n\n page_source = response.text\n\n pricing_data = re.search(r'vtex.events.addData\\(([\\S\\s]+?)\\);',\n page_source).groups()[0]\n pricing_data = json.loads(pricing_data)\n\n skus_data = re.search(r'var skuJson_0 = ([\\S\\s]+?);',\n page_source).groups()[0]\n skus_data = json.loads(skus_data)\n name = '{} {}'.format(pricing_data['productBrandName'],\n pricing_data['productName'])\n normal_price = Decimal(pricing_data['productPriceTo'])\n\n soup = BeautifulSoup(page_source, 'html.parser')\n\n discount_container = soup.find('div', 'price_box-v1').fetchParents()[0]\n discount_container = discount_container.findAll('p', 'flag')\n if discount_container:\n discount_container = discount_container[-1]\n discount_value = re.search(r'(\\d+)', discount_container.text)\n discount_value = Decimal(discount_value.groups()[0])\n discount_factor = (Decimal(100) - discount_value) / Decimal(100)\n\n offer_price = normal_price * discount_factor\n offer_price = offer_price.quantize(Decimal('0.01'))\n else:\n offer_price = normal_price\n\n picture_urls = [tag['rel'][0].split('?')[0] for tag in\n soup.findAll('a', {'id': 'botaoZoom'})]\n\n description = ''\n panel_classes = ['blc_1', 'blc_2']\n\n for panel_class in panel_classes:\n panel = soup.find('div', panel_class)\n description += html_to_markdown(str(panel)) + '\\n\\n'\n\n products = []\n\n if 'productEans' in pricing_data:\n ean = pricing_data['productEans'][0]\n if len(ean) == 12:\n ean = '0' + ean\n if not check_ean13(ean):\n ean = None\n else:\n ean = None\n\n for sku_data in skus_data['skus']:\n sku = str(sku_data['sku'])\n stock = pricing_data['skuStocks'][sku]\n\n p = Product(\n name,\n cls.__name__,\n category,\n url,\n url,\n sku,\n stock,\n normal_price,\n offer_price,\n 'BRL',\n sku=sku,\n ean=ean,\n description=description,\n picture_urls=picture_urls\n )\n products.append(p)\n\n return products\n","sub_path":"storescraper/stores/mega_mamute.py","file_name":"mega_mamute.py","file_ext":"py","file_size_in_byte":4871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"463551384","text":"from room import Room\nfrom player import Player\n\n# # Declare all the rooms\n# outside = Room(\"Outside Cave Entrance\",\n# \"North of you, the cave mount beckons\", n_to='foyer')\n\n# foyer = Room(\"Foyer\", \"Dim light filters in from the south. Dusty passages run north and east.\",\n# s_to='outside', n_to='overlook', e_to='narrow')\n\n# overlook = Room(\"Grand Overlook\", \"A steep cliff appears before you, falling into the darkness. Ahead to the north, a light flickers in the distance, but there is no way across the chasm.\", s_to='foyer')\n\n# narrow = Room(\"Narrow Passage\", \"The narrow passage bends here from west to north. The smell of gold permeates the air.\",\n# w_to='foyer', n_to='treasure')\n\n# treasure = Room(\"Treasure Chamber\", \"You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by earlier adventurers. The only exit is to the south.\", s_to='narrow')\n# Declare all the rooms\n\nroom = {\n 'outside': Room(\"Outside Cave Entrance\",\n \"North of you, the cave mouth beckons.\"),\n\n 'foyer': Room(\"Foyer\", \"\"\"Dim light filters in from the south. Dusty\npassages run north and east.\"\"\"),\n\n 'overlook': Room(\"Grand Overlook\", \"\"\"A steep cliff appears before you, falling\ninto the darkness. Ahead to the north, a light flickers in\nthe distance, but there is no way across the chasm.\"\"\"),\n\n 'narrow': Room(\"Narrow Passage\", \"\"\"The narrow passage bends here from west\nto north. The smell of gold permeates the air.\"\"\"),\n\n 'treasure': Room(\"Treasure Chamber\", \"\"\"You've found the long-lost treasure\nchamber! Sadly, it has already been completely emptied by\nearlier adventurers. The only exit is to the south.\"\"\"),\n}\n\n\n# Link rooms together\n\nroom['outside'].n_to = room['foyer']\nroom['foyer'].s_to = room['outside']\nroom['foyer'].n_to = room['overlook']\nroom['foyer'].e_to = room['narrow']\nroom['overlook'].s_to = room['foyer']\nroom['narrow'].w_to = room['foyer']\nroom['narrow'].n_to = room['treasure']\nroom['treasure'].s_to = room['narrow']\n\n#\n# Main\n#\n\n# Make a new player object that is currently in the 'outside' room.\nplayer1 = Player(name='Jon', player_room=room['outside'])\n\nprint(f'Hello! You currently playing as {player1.name}.\\n')\nprint(\n f'Your adventure begins {player1.player_room}... {player1.player_room.description}\\n')\n\n# Write a loop that:\n#\n# * Prints the current room name\n# * Prints the current description (the textwrap module might be useful here).\n# * Waits for user input and decides what to do.\n#\n# If the user enters a cardinal direction, attempt to move to the room there.\n# Print an error message if the movement isn't allowed.\n#\n# If the user enters \"q\", quit the game.\n# Input parser\nselection = 't'\nwhile selection not in ['q']:\n selection = input(\n f'Location: {player1.player_room} | Type n, s, e, and w to move north, south, east, or west to move. Type q to quit.\\n')\n try:\n selection = str(selection)\n if selection == 'n':\n print(f'You try to move north.')\n player1.move('n')\n elif selection == 's':\n print(f'You try to move south.')\n player1.move('s')\n elif selection == 'e':\n print(f'You try to move east.')\n player1.move('e')\n elif selection == 'w':\n print(f'You try to move west.')\n player1.move('w')\n elif selection == 'q':\n print(\"So long, partner!\")\n else:\n print('Please type: n, s, e, w, or q!')\n except ValueError:\n print(\"Please enter one of the letters: n, s, e, w, or q\")","sub_path":"src/adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":3610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"989542","text":"# python3\r\n# coding=\r\n\r\n\r\nfrom collections import Iterable\r\nimport warnings\r\nfrom time import sleep\r\nfrom tqdm import tqdm\r\nfrom result import Result\r\n# import rus_corpus_oop\r\n\r\n\r\n# functions = {'rus': rus_corpus_oop}\r\nfunctions = {}\r\n\r\n\r\nclass Query:\r\n def __init__(self, language):\r\n self.language = language\r\n self.__corpus = functions[self.language] \r\n # self.search.__func__.__doc__ = self.__corpus.__doc__\r\n \r\n self.results = list()\r\n self.unsuccessful = list()\r\n self.__warn = 'Nothing found for query \"%s\".\\n' \\\r\n 'Unsuccessful queries are available via Query.unsuccessful'\r\n self.__pbar_desc = 'Query \"%s\"'\r\n self.__type_except = 'Argument `query` must be of type or iterable, got <%s>'\r\n\r\n def search(self, query, sleep_time=1, sleep_each=5, *args, **kwargs):\r\n \"\"\"\r\n sleep_time: int: sleeping time in seconds\r\n sleep_each: int: sleep after each `sleep_each` request\r\n \r\n for more arguments see `params_container.Container`\r\n \r\n __________\r\n \r\n pbar bad behaviour if found < numResults\r\n pbar dies if interrupted\r\n verbose might be more stable\r\n we want to add param \"progress=['bar', 'verbose']\", dont we\r\n \"\"\"\r\n if sleep_each < 1:\r\n raise ValueError('Argument `sleep_each` must be >= 1')\r\n \r\n if isinstance(query, str):\r\n query = [query]\r\n \r\n if not isinstance(query, Iterable):\r\n raise TypeError(self.__type_except % type(query))\r\n \r\n for q in query:\r\n _r = Result(q)\r\n parser = self.__corpus.PageParser(query=q, *args, **kwargs)\r\n q_desc = self.__pbar_desc % q\r\n \r\n for t in tqdm(parser.extract(),\r\n total=kwargs['numResults'],\r\n unit='docs',\r\n desc=q_desc):\r\n _r.add(t)\r\n if _r.N % sleep_each == 0:\r\n sleep(sleep_time)\r\n \r\n self.results.append(_r)\r\n if _r.N == 0:\r\n warnings.warn(self.__warn % q)\r\n self.unsuccessful.append(q)\r\n \r\n return self.results\r\n","sub_path":"refactor2/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"550942733","text":"import sys\nimport glob\nimport os\nimport PIL.Image\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport twutils.plot as twplot\nimport twutils.pre as twpre\nfrom scipy import constants as C\n\nif len(sys.argv)<3:\n\tprint('Usage: python wigner.py slicing=slices real_file,imag_file [panels=a,b] [layout=1x2]')\n\tprint(' [dr=0.0,0.0] [color=viridis,jet] [roi=h0,h1,v0,v1/h0,h1,v0,v1]')\n\tprint('------------------Examples----------------')\n\tprint('Envelope: python wigner.py xyzt=0,0,0 e_real.dvdat,e_imag.dvdat')\n\tprint('Carrier resolved: python wigner.py xyzt=0,0,0 Ex.dvdat,1.0')\n\tprint('-------------------General Notes--------------------')\n\tprint('Extra spaces (e.g. around commas, semicolons, or equals) are not allowed.')\n\tprint('Displays two panels, the field in real space, and the field in Wigner phase space.')\n\tprint('Required arguments are positional, optional arguments are key=value pairs.')\n\tprint('Double values refer to the two plots.')\n\tprint('------------------Arguments-----------------------')\n\tprint('slicing: 4-character string, such as xyzt, where the first axis is the one to transform.')\n\tprint('slices: is a comma delimited list of 3 slice indices.')\n\tprint(' The real space plot only uses the last 2 slices.')\n\tprint('real_file: name of the file with the real part of the field')\n\tprint('imag_file: EITHER name of the file with the imaginary part of the field')\n\tprint(' or the carrier frequency if the data is real.')\n\tprint('layout: can be 1x2 or 2x1')\n\tprint('dr: 0.0 signals full range on linear scale, any other float is the number of decades spanned.')\n\tprint('color: viridis,magma,plasma,inferno,Spectral,bwr,seismic,prism,ocean,rainbow,jet,nipy_spectral')\n\tprint(' Color maps may be inverted by adding \"_r\" to the name')\n\tprint(' Note any Matplotlib color maps can be used.')\n\tprint('roi: select a subdomain to plot, otherwise the full domain is plotted.')\n\tprint('----------------------Animations----------------------')\n\tprint('Put a python range as one of the slices to generate animated GIF.')\n\tprint('For example, zxyt=0,0,2:5 would animate time slices 2,3,4.')\n\texit()\n\ndef WignerTransform(A,ds,eta0):\n\t# If A is in V/m, ds in secs, and eta0 in ohms, returns J/m^2.\n\t# Then, integration over consistent phase space units (dimensionless product) gives the actual fluence.\n\t# The frequency variable is assumed to be an angular frequency (e.g. rad/s)\n\tN = A.shape[0]\n\tM = np.int(N/2) + 1\n\tcorr = np.zeros((N,M)).astype(np.complex)\n\tAi = np.zeros(N*2-1).astype(np.complex)\n\tAi[::2] = A\n\tAi[1::2] = 0.5*(np.roll(Ai,1)+np.roll(Ai,-1))[1::2]\n\tfor j in range(M):\n\t\tcorr[:,j] = (np.conj(np.roll(Ai,j))*np.roll(Ai,-j))[::2]\n\twig = np.fft.hfft(corr,axis=1)*ds/(2*np.pi)\n\twig = np.fft.fftshift(wig,axes=1)\n\t# Fix the units\n\tdw = (2*np.pi/ds) / N\n\tfluence = 0.5*np.sum(np.abs(A)**2)*ds/eta0\n\twigfluence = np.sum(wig)*ds*dw\n\treturn wig*fluence/wigfluence\n\ndef cleanup(wildcarded_path):\n\tcleanstr = glob.glob(wildcarded_path)\n\tfor f in cleanstr:\n\t\tos.remove(f)\n\ndef ParseSlices(dims,ax_list,slice_str_list):\n\t'''Function to generate a list of slice tuples for the movie.\n\tdims = dimensions of all 4 axes\n\tax_list = slicing_spec as list of integer axis identifiers.\n\tslice_str_list = list of slice strings, can be indices or ranges.\n\tReturns slice_tuples,movie.'''\n\tslice_tuples = []\n\trange_tuples = []\n\tmovie = False\n\t# Construct list of range tuples\n\tsax = ax_list[4-len(slice_str_list):]\n\tfor saxi,slice_str in enumerate(slice_str_list):\n\t\trng = slice_str.split(':')\n\t\ttup = ()\n\t\tfor i,el in enumerate(rng):\n\t\t\tif el=='' and i==0:\n\t\t\t\tel = '0'\n\t\t\tif el=='' and i==1:\n\t\t\t\tel = str(dims[sax[saxi]])\n\t\t\tif el=='' and i==2:\n\t\t\t\tel = '1'\n\t\t\ttup += (int(el),)\n\t\trange_tuples.append(tup)\n\t# Determine the range of the movie frames\n\tframe_rng = range(1)\n\tfor rng in range_tuples:\n\t\tmovie = movie or len(rng)>1\n\t\tif len(rng)==2:\n\t\t\tframe_rng = range(rng[0],rng[1])\n\t\tif len(rng)==3:\n\t\t\tframe_rng = range(rng[0],rng[1],rng[2])\n\t# Construct list of slice tuples\n\tfor r in frame_rng:\n\t\ttup = ()\n\t\tfor rng in range_tuples:\n\t\t\tif len(rng)>1:\n\t\t\t\ttup += (r,)\n\t\t\telse:\n\t\t\t\ttup += rng\n\t\tslice_tuples.append(tup)\n\treturn slice_tuples,movie\n\n# normalization constants in mks\n\nn1 = 2.65e17*1e6\nsu = twpre.SimUnits(n1*1e-6)\nt1 = su.t1\nx1 = su.x1\nE1 = su.E1\nU1 = C.m_e*C.c*C.c\nN1 = n1*x1**3\neta0 = np.sqrt(C.mu_0/C.epsilon_0)\n\n# Matplotlib setup and default args\n\nmpl.rcParams.update({'text.usetex' : False , 'font.size' : 10})\ncolor = ['viridis','viridis']\nproportional = False\nif proportional:\n\tmy_aspect = 'equal'\nelse:\n\tmy_aspect = 'auto'\ndyn_range = [0.0,0.0]\nroi = [[],[]]\nask = 'yes'\nlayout = '1x2'\npanels = ''\n\n# Process command line arguments and setup plotter object\n\nslicing_spec = sys.argv[1].split('=')[0]\nprimitive_slices = (sys.argv[1].split('=')[1]).split(',')\nif len(primitive_slices)!=3:\n\traise ValueError('Need three slices.')\nreal_data_file = sys.argv[2].split(',')[0]\nimag_data_file = sys.argv[2].split(',')[1]\nfor keyval in sys.argv[3:]:\n\tkey = keyval.split('=')[0]\n\tval = keyval.split('=')[1]\n\tif key=='panels':\n\t\tpanels = val.split(',')\n\tif key=='layout':\n\t\tlayout = val\n\tif key=='dr':\n\t\tdyn_range = []\n\t\tdyn_range.append(float(val.split(',')[0]))\n\t\tdyn_range.append(float(val.split(',')[1]))\n\tif key=='color':\n\t\tcolor = val.split(',')\n\tif key=='roi':\n\t\tfor s in val.split('/')[0].split(','):\n\t\t\troi[0].append(int(s))\n\t\tfor s in val.split('/')[1].split(','):\n\t\t\troi[1].append(int(s))\n\nplotter_r = twplot.plotter(real_data_file,buffered=False)\ntry:\n\tcarrier = float(imag_data_file)\n\tplotter_i = 0.0\nexcept ValueError:\n\tcarrier = 0.0\n\tplotter_i = twplot.plotter(imag_data_file,buffered=False)\nplotter_r.display_info()\n\n# Set up animation slices\n\naxes = twplot.get_axis_info(slicing_spec)\ndims = plotter_r.dims4()\nslice_tuples,movie = ParseSlices(dims,axes,primitive_slices)\n\n# Check existing image files and clean\n\nimg_files = glob.glob('frame*.png')\nif len(img_files)>0 and ask=='yes':\n\tans = ''\n\twhile ans!='y' and ans!='n':\n\t\tans = input('Found some frame*.png files, OK to clean (y/n) ?')\n\tif ans=='n':\n\t\tprint('STOPPED. Please run script in a directory where there are no important files of the form frame*.png.')\n\t\texit(1)\n\nfor img_file in img_files:\n\tos.remove(img_file)\n\ndef form_envelope(real_field,carrier,dz,ax):\n\tk = 2*np.pi*np.fft.fftfreq(real_field.shape[ax],dz)\n\tdk = k[1]-k[0]\n\tkc = -k[int(real_field.shape[ax]/2)]\n\tcarrier_idx = int(real_field.shape[ax] * carrier / (2*kc))\n\tenv = np.fft.fft(real_field,axis=ax)\n\tif ax==0:\n\t\tenv[int(env.shape[0]/2):,...] = 0.0\n\telse:\n\t\tenv[...,int(env.shape[1]/2):] = 0.0\n\tenv = np.roll(env,-carrier_idx,axis=ax)\n\treturn 2*E1*np.fft.ifft(env,axis=ax)\n\ndef extract_plot_data(plotter_r,plotter_i,slice_now):\n\tif carrier!=0.0:\n\t\treal2d,dict2d = plotter_r.falsecolor2d(slicing_spec,slice_now[1:],dyn_range[0])\n\t\tabcissa,real1d,dict1d = plotter_r.lineout(slicing_spec,slice_now,dyn_range[1])\n\t\tenvelope2d = form_envelope(real2d,carrier,abcissa[1]-abcissa[0],1)\n\t\tenvelope1d = form_envelope(real1d,carrier,abcissa[1]-abcissa[0],0)\n\telse:\n\t\treal2d,dict2d = plotter_r.falsecolor2d(slicing_spec,slice_now[1:],dyn_range[0])\n\t\timag2d,dict2d = plotter_i.falsecolor2d(slicing_spec,slice_now[1:],dyn_range[0])\n\t\tabcissa,real1d,dict1d = plotter_r.lineout(slicing_spec,slice_now,dyn_range[1])\n\t\tabcissa,imag1d,dict1d = plotter_i.lineout(slicing_spec,slice_now,dyn_range[1])\n\t\tenvelope2d = E1*(real2d + 1j*imag2d)\n\t\tenvelope1d = E1*(real1d + 1j*imag1d)\n\tz_extent = list(dict1d['extent'][:2])\n\tdz = (z_extent[1]-z_extent[0]) / envelope1d.shape[0]\n\tk_extent = [-np.pi/dz,np.pi/dz]\n\twig_ext = z_extent + k_extent\n\treturn envelope2d,dict2d['extent'],WignerTransform(envelope1d,dz*x1/C.c,eta0),wig_ext\n\n\n# Determine the global color scale bounds for both plots\n# If a movie we have to do all the transforms first\n# We don't save the data, just do redundant transforms later\n\nglobal_min1 = 1e50\nglobal_max1 = -1e50\nglobal_min2 = 1e50\nglobal_max2 = -1e50\nfor slice_now in slice_tuples:\n\tenvelope2d,ext1,wigner,ext2=extract_plot_data(plotter_r,plotter_i,slice_now)\n\tlocal_min = np.min(np.abs(envelope2d))\n\tlocal_max = np.max(np.abs(envelope2d))\n\tif local_minglobal_max1:\n\t\tglobal_max1 = local_max\n\tlocal_min = np.min(wigner)\n\tlocal_max = np.max(wigner)\n\tif local_minglobal_max2:\n\t\tglobal_max2 = local_max\n\n# Make a movie or display single frame\n\nfor file_idx,slice_now in enumerate(slice_tuples):\n\n\tif layout=='1x2':\n\t\tplt.figure(file_idx,figsize=(8,3.5),dpi=150)\n\telse:\n\t\tplt.figure(file_idx,figsize=(3.5,7),dpi=150)\n\n\tenvelope2d,ext1,wigner,ext2=extract_plot_data(plotter_r,plotter_i,slice_now)\n\tif layout=='1x2':\n\t\tplt.subplot(121)\n\telse:\n\t\tplt.subplot(211)\n\tplt.imshow(np.abs(envelope2d)*1e-12*1e-2,\n\t\torigin='lower',\n\t\taspect=my_aspect,\n\t\textent=ext1,\n\t\tvmin=global_min1*1e-12*1e-2,\n\t\tvmax=global_max1*1e-12*1e-2,\n\t\tcmap=color[0])\n\tb = plt.colorbar()\n\tb.set_label(r'${\\cal E}$ (TV/cm)',size=12)\n\tif len(roi[0])==4:\n\t\tplt.xlim(roi[0][0],roi[0][1])\n\t\tplt.ylim(roi[0][2],roi[0][3])\n\telse:\n\t\troi[0] = ext1\n\tplt.xlabel(r'$\\omega_p(z/c - t)$',size=12)\n\tplt.ylabel(r'$\\omega_p\\rho/c$',size=12)\n\tif not panels=='':\n\t\tplt.text(roi[0][0],roi[0][3]+0.03*(roi[0][3]-roi[0][2]),'('+panels[0]+')')\n\n\tif layout=='1x2':\n\t\tplt.subplot(122)\n\telse:\n\t\tplt.subplot(212)\n\tplt.imshow(wigner.swapaxes(0,1)*1e-6*1e-4,\n\t\torigin='lower',\n\t\taspect=my_aspect,\n\t\textent=ext2,\n\t\tvmin=global_min2*1e-6*1e-4,\n\t\tvmax=global_max2*1e-6*1e-4,\n\t\tcmap=color[1])\n\tb = plt.colorbar()\n\tb.set_label(r'${\\cal N}$ (MJ/cm$^2$)',size=12)\n\tif len(roi[1])==4:\n\t\tplt.xlim(roi[1][0],roi[1][1])\n\t\tplt.ylim(roi[1][2],roi[1][3])\n\telse:\n\t\troi[1] = ext2\n\tplt.xlabel(r'$\\omega_p(z/c - t)$',size=12)\n\tplt.ylabel(r'$\\delta\\omega/\\omega_p$',size=12)\n\tif not panels=='':\n\t\tplt.text(roi[1][0],roi[1][3]+0.03*(roi[1][3]-roi[1][2]),'('+panels[1]+')')\n\n\tplt.tight_layout()\n\n\tif movie:\n\t\timg_file = 'frame{:03d}.png'.format(file_idx)\n\t\tprint('saving',img_file,'...')\n\t\tplt.savefig(img_file)\n\t\tplt.close()\n\nif movie:\n\tprint('Consolidating into movie file...')\n\timages = []\n\tframeRateHz = 5\n\timg_files = sorted(glob.glob('frame*.png'))\n\tfor f in img_files:\n\t\timages.append(PIL.Image.open(f))\n\timages[0].save('mov.gif',save_all=True,append_images=images[1:],duration=int(1000/frameRateHz),loop=0)\n\tcleanup('frame*.png')\n\tprint('Done.')\nelse:\n\tplt.show()\n","sub_path":"tools/extras/wigner.py","file_name":"wigner.py","file_ext":"py","file_size_in_byte":10385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"335086297","text":"#coding: utf-8\r\n\r\nfrom apiclient.discovery import build\r\nimport requests\r\nimport json\r\n\r\n\r\nAPI_KEY=\"\"\r\nTAG_TRAILLER=\" movie trailer\"\r\n\r\ndef pesquisarVideo(nomeFilme):\r\n youtube = build('youtube', 'v3', developerKey=API_KEY)\r\n req = youtube.search().list(q=nomeFilme + TAG_TRAILLER, part='snippet', type='video', maxResults=1)\r\n resp = req.execute()\r\n if(len(resp['items'])) > 0:\r\n return resp['items'][0]['id']\r\n else:\r\n return ''\r\n","sub_path":"flask_server/service/youtube.py","file_name":"youtube.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"520900211","text":"# -*- coding: utf-8 -*-\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.datasets import load_boston\nfrom sklearn.externals import joblib\n\nboston = load_boston()\nprint(boston.keys())\nprint(boston.data.shape)\n#print(boston.DESCR)\n\n#creamos el dataframe\nbos=pd.DataFrame(boston.data)\nprint(bos.head())\n\nbos.columns=boston.feature_names\nprint(bos.head())\n\n#Aquí es donde están los precios\nprint(boston.target[:5])\n\n#Los colocamos dentro del dataframe\nbos['PRICE']=boston.target\n\n#Para generar X quitamos la columna del precio\nX= bos.drop(\"PRICE\",axis=1)\nY=bos['PRICE']\n\n#Creamos el modelo\nlm= LinearRegression()\nprint(lm)\n\n#Creamos las muestras de entrenamiento y pruebas\nX_train, X_test,Y_train, Y_test = train_test_split(X,Y, test_size=0.25\n , random_state=2\n )\nprint(X_train.shape)\nprint(Y_train.shape)\nprint(X_test.shape)\nprint(Y_test.shape)\n\n#Entrenamos el Modelo\nlm.fit(X_train,Y_train)\n\nscore=lm.score(X_test,Y_test)\nprint(\"Score Modelo:\",score)\n\n\n#Guardar el modelo para usarlo más adelante\nlocalizacion_modelo=\"./modelos/modelo_regresion_linear_boston.pkl\"\njoblib.dump(lm,localizacion_modelo)\n\n#recuperar el modelo guardado anteriormente\nlm=joblib.load(localizacion_modelo)\nscore=lm.score(X_test,Y_test)\nprint(\"Score guardado:\",score)\n\n\n\nplt.scatter(lm.predict(X_train),lm.predict(X_train)- Y_train, c=\"b\",s=40, alpha=0.5)\nplt.scatter(lm.predict(X_test),lm.predict(X_test)- Y_test, c=\"g\",s=40,)\nplt.hlines(y=0, xmax=50, xmin=0)\nplt.title(\"Diagrama de dispersión de entrenamiento (azul), y pruebas (verde)\")\nplt.show()","sub_path":"04_01_01_algortimos_regresion_linear.py","file_name":"04_01_01_algortimos_regresion_linear.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"179018216","text":"from collections import deque\n\nfrom math import inf\n\n\ndef preprocess(arr: list) -> deque:\n minimum = deque()\n minimum.append(None)\n\n last = inf\n\n for i in reversed(range(len(arr))):\n e = arr[i]\n\n if e < last:\n last = e\n minimum.append(i)\n\n if e == arr[0]:\n break\n\n return minimum\n\n\ndef longest_sub_array(arr: list):\n minimum = preprocess(arr)\n\n smaller = minimum.pop()\n\n max_size = 1\n max_start = 0\n\n for i in range(len(arr)):\n while smaller is not None and arr[i] > arr[smaller]:\n if smaller - i + 1 > max_size:\n max_size = smaller - i + 1\n max_start = i\n\n smaller = minimum.pop()\n\n if smaller is None:\n break\n\n return [] if max_size == 1 else arr[max_start:max_start + max_size]\n\n\nif __name__ == '__main__':\n arr = [-5, -1, 7, 5, 1, -2]\n\n print(longest_sub_array(arr))\n print(preprocess(arr))\n","sub_path":"dynamicProgramming/SubArray.py","file_name":"SubArray.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"528683685","text":"# -*- coding: utf-8 -*-\n\"\"\"\nTokenize string input.\nCreated on Wed Sep 18 13:18:07 2019\n\n@author: eliphat\n\"\"\"\nimport collections\nimport lcommons as commons\n\n\nwhitespaces = {' ', '\\t', '\\r', '\\n'}\nend_tokens = collections.defaultdict(list)\nfor op in commons.ops:\n end_tokens[op[0]].append(op)\nfor op in commons.spec:\n end_tokens[op[0]].append(op)\n\n\ndef put_word(tokens, string):\n if len(string) > 0:\n if string in commons.keywords:\n tokens.append(('keyword', string))\n elif string in commons.ops:\n tokens.append(('op', string))\n elif string in commons.spec:\n tokens.append(('special', string))\n else:\n tokens.append(('token', string))\n\n\ndef put_chlist(tokens, chlist):\n put_word(tokens, ''.join(chlist))\n chlist.clear()\n\n\ndef tokenize(s):\n tokens = []\n p = []\n i = 0\n while i < len(s):\n ch = s[i]\n i += 1\n if ch in whitespaces:\n put_chlist(tokens, p)\n elif ch in end_tokens:\n put_chlist(tokens, p)\n possibilities = end_tokens[ch]\n ac = False\n for end_tk in possibilities:\n if len(end_tk) == 1 or s[i - 1: i - 1 + len(end_tk)] == end_tk:\n ac = True\n put_word(tokens, end_tk)\n i = i - 1 + len(end_tk)\n if not ac:\n raise Exception(\"Requires \" + str(possibilities)\n + \"at '%s'\" % ch)\n else:\n p.append(ch)\n if p:\n put_chlist(tokens, p)\n put_word(tokens, '&EOF')\n return tokens\n","sub_path":"ltokenizer.py","file_name":"ltokenizer.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"334089918","text":"class Solution:\n def coinChange(self, coins: List[int], amount: int,memo = None) -> int:\n \n \n tab = [0] + [float('inf')] * amount\n \n for coin in coins:\n for x in range(coin,amount+1):\n tab[x] = min(tab[x],tab[x-coin] + 1)\n return tab[amount] if tab[amount] != float('inf') else -1","sub_path":"leetcode/322_coin_change.py","file_name":"322_coin_change.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"615665311","text":"import pygame as pg\nimport basic\nfrom settings import *\nimport json\nimport math\nimport random\nimport HUD\nimport importlib.util\n\nimport os\nfrom language_manager import language_text as get_text\nimport language_manager\nvec=pg.math.Vector2\n\ndef give_named_item_code(name,game):\n i=0\n while True:\n with open(items_file) as file:\n data=json.load(file)\n i+=1\n item=Item(game,0,0,i)\n item.kill()\n if item.name==name:\n break\n \n return item\nclass Player(pg.sprite.Sprite):\n\n def __init__(self, game, x, y):\n self.groups = game.all_sprites, game.heroes\n pg.sprite.Sprite.__init__(self, self.groups)\n self.game = game \n self.image=pg.Surface((TILESIZE,TILESIZE))\n self.image.fill(BLACK)\n self.current_frame=0\n self.last_update=0\n self.can_climb=False\n self.rect = self.image.get_rect()\n self.rect.center=(x,y)\n self.vel=vec(0,0)\n self.pos=vec(x,y)\n \n self.acc = vec(0, 0)\n\n def get_keys(self):\n keys = pg.key.get_pressed()\n def collide_with_platforms(self): \n hits = pg.sprite.spritecollide(self, self.game.platforms, False)\n if hits: \n if hits[0].is_slippery: \n if self.vel.x>0:\n self.vel.x+=0.5\n elif self.vel.x<0:\n self.vel.x-=0.5 \n if self.vel.y > 0 and self.pos.y 0:\n self.pos.x = hits[0].rect.left - self.rect.width\n if self.vel.x < 0:\n self.pos.x = hits[0].rect.right\n self.vel.x = 0\n self.rect.x = self.pos.x\n\n if dir == 'y':\n \n hits = pg.sprite.spritecollide(self, self.game.walls, False)\n if hits:\n if self.vel.y > 0:\n self.pos.y = hits[0].rect.top - self.rect.height\n if hits[0].is_slippery:\n \n if self.vel.x>0:\n self.vel.x+=0.5\n elif self.vel.x<0:\n self.vel.x-=0.5\n \n\n if self.vel.y < 0:\n self.pos.y = hits[0].rect.bottom\n \n self.vel.y = 0\n self.rect.y = self.pos.y\n \n \n \n \n def jump(self):\n \n self.rect.y+=1\n hits = pg.sprite.spritecollide(self, self.game.walls, False)\n if hits:\n \n self.vel.y-=16 \n self.rect.y-=1\n\n self.rect.y+=1\n hits = pg.sprite.spritecollide(self, self.game.platforms, False)\n if hits:\n \n self.vel.y-=16 \n self.rect.y-=1\n\n \n def update(self):\n self.get_keys()\n self.acc = vec(0, GRAVITY)\n keys = pg.key.get_pressed()\n \n if keys[pg.K_LEFT] or keys[pg.K_a]:\n self.acc.x = -PLAYER_ACC\n if keys[pg.K_RIGHT] or keys[pg.K_d]:\n self.acc.x = PLAYER_ACC \n\n \n\n self.acc.x += self.vel.x * PLAYER_FRICTION \n self.vel += self.acc\n self.pos += self.vel + 0.5 * self.acc \n self.rect.x = self.pos.x\n self.collide('x')\n self.rect.y = self.pos.y\n self.collide('y')\n \n\n \n\n\n\n \n\nclass Obstacle(pg.sprite.Sprite):\n def __init__(self, game, x, y,w,h,is_slippery=False):\n self.groups = game.walls\n pg.sprite.Sprite.__init__(self, self.groups)\n self.game = game\n self.rect=pg.Rect(x,y,w,h)\n self.x=x\n self.y=y\n self.is_slippery=is_slippery\n self.rect.x=x\n self.rect.y=y\n \n\n\nclass Enemy(pg.sprite.Sprite):\n def __init__(self,game,x,y,type,level):\n \n\n #базовое\n self.groups=game.enemies,game.all_sprites\n pg.sprite.Sprite.__init__(self,self.groups)\n self.rot='right'\n self.image=pg.Surface((TILESIZE,TILESIZE))\n self.image.fill(LIGHTGREY)\n self.game=game\n \n self.type=type\n \n if self.type=='primitive':\n self.id=0\n elif self.type=='passive':\n self.id=1\n elif self.type=='ninja':\n self.id=2\n \n elif self.type=='jumper':\n self.id=3\n elif self.type=='canon':\n self.id=4\n self.image=pg.image.load(canon_image)\n elif self.type=='star':\n self.id=5\n self.image.set_colorkey(WHITE)\n self.left_image=pg.transform.flip(self.image,True,False)\n self.right_image=self.image\n \n self.rect = self.image.get_rect()\n self.rect.center=(x,y)\n self.vel=vec(0,0)\n self.pos=vec(x,y)\n self.acc = vec(0, 0)\n self.state='right'\n self.rot=vec(1,0)\n with open(enemies_file) as file:\n self.data=json.load(file)\n self.basic=self.data[self.id]\n #характеристика моба\n \n\n self.level=level\n self.range=self.basic['range']\n self.agro_radius=self.basic['agro_radius']\n self.type=self.basic['type']\n self.speed=self.basic['speed']\n self.exp=self.basic['exp']\n #прирост\n self.inc_p_armor=self.basic['inc_p_armor']\n self.inc_m_armor=self.basic['inc_m_armor']\n self.inc_health=self.basic['inc_health']\n #Здоровье\n self.max_health=self.basic['Basic health']+self.level*self.inc_health\n self.health=self.max_health\n #Броня\n self.p_armor=self.basic[\"Basic p_armor\"]+self.level*self.inc_p_armor\n self.m_armor=self.basic[\"Basic m_armor\"]+self.level*self.inc_m_armor\n #атака\n self.damage=int(self.basic['damage']+self.level*self.basic[\"mod\"])\n self.type_of_damage=self.basic['type_of_damage']\n self.last_attack=pg.time.get_ticks()\n self.attack_speed=self.basic[\"attack speed\"]*1000\n self.exp=self.exp*self.level\n\n #логи\n self.creation_time=pg.time.get_ticks()\n self.list_of_attacks=[]\n \n\n\n def jump(self):\n self.rect.y+=1\n hits = pg.sprite.spritecollide(self, self.game.walls, False)\n if hits:\n self.vel.y-=16\n self.rect.y-=1\n def collide(self, dir):\n if dir == 'x':\n hits = pg.sprite.spritecollide(self, self.game.walls, False)\n if hits:\n if self.vel.x > 0:\n self.pos.x = hits[0].rect.left - self.rect.width\n if self.vel.x < 0:\n self.pos.x = hits[0].rect.right\n self.vel.x = 0\n self.rect.x = self.pos.x\n if dir == 'y':\n hits = pg.sprite.spritecollide(self, self.game.walls, False)\n if hits:\n if self.vel.y > 0:\n self.pos.y = hits[0].rect.top - self.rect.height\n if self.vel.y < 0:\n self.pos.y = hits[0].rect.bottom\n self.vel.y = 0\n self.rect.y = self.pos.y\n def draw_health_bar(self):\n\n if self.health > 0.6*self.max_health:\n\n col = GREEN\n\n elif self.health > 0.3*self.max_health :\n\n col = YELLOW\n\n else:\n\n col = RED\n\n width = int(self.rect.width * (self.health / self.max_health))\n\n self.health_bar = pg.Rect(0, 0, self.rect.width, 7)\n\n if self.health < self.max_health:\n\n pg.draw.rect(self.image, col, self.health_bar)\n\n def detect_enemy(self):\n self.detected=[]\n for hero in self.game.heroes:\n if math.fabs(hero.pos.x-self.pos.x)= self.attack_speed:\n self.last_attack = now \n if self.state=='right':\n self.list_of_attacks.append(Attack(self.game,vec(self.pos.x,self.pos.y),vec(1,0),self.damage,self.type_of_damage,'punch','heroes',w=self.rect.width,h=self.rect.height))\n \n elif self.state=='left':\n self.list_of_attacks.append( Attack(self.game,self.pos,vec(self.pos.x,self.pos.y),self.damage,self.type_of_damage,'punch','heroes',w=self.rect.width,h=self.rect.height))\n \n \n def can_attack_range(self):\n self.detected=[]\n for hero in self.game.heroes:\n if math.fabs(hero.pos.x-self.pos.x)=self.rect.top:\n \n self.jump()\n def dodge_melee(self,chance): #шанс увернутся в процентах\n for bullet in self.game.attacks:\n if bullet.type_of_attack=='punch':\n if bullet.danger=='enemies' or bullet.danger=='all':\n i=random.randint(1,100)\n image=self.image\n if i=self.rect.top: \n if self.rot=='right':\n self.vel.x+=100\n else:\n self.vel.x-=100\n \n \n \n\n \n def move(self,dir):\n if dir=='right':\n self.acc.x = -PLAYER_ACC*self.speed\n self.rot='right'\n \n elif dir=='left':\n \n self.acc.x = PLAYER_ACC*self.speed\n self.rot='left'\n def move_to_enemy(self):\n for enemy in self.detected:\n if enemy.pos.x-self.pos.x>0: #cлева\n self.move('left')\n self.state='left'\n \n else:\n self.move(\"right\")\n self.state='right'\n def following_jump(self):\n if self.vel.y==0 and self.vel.x==0:\n \n self.jump()\n for enemy in self.detected:\n if enemy.jumping==True:\n self.jump()\n def random_jumping(self):\n self.jump()\n def canon_shoot(self):\n for enemy in self.detected:\n if enemy.pos.x-self.pos.x>0: #cлева\n \n self.state='right'\n else:\n self.state='left'\n now = pg.time.get_ticks()\n if now - self.last_attack >= self.attack_speed:\n self.last_attack = now\n for detected in self.detected:\n self.list_of_attacks.append(Attack(self.game,vec(self.rect.centerx,self.rect.centery),vec(self.rect.centerx-detected.rect.centerx,self.rect.centery-detected.rect.centery).normalize(),self.damage,self.type_of_damage,'canon_ball','heroes'))\n \n \n \n def star_shoot(self):\n speed=10\n now = pg.time.get_ticks()\n if now - self.last_attack >= self.attack_speed:\n self.last_attack = now\n \n Attack(self.game,vec(self.pos.x,self.pos.y),vec(-1,0),self.damage,self.type_of_damage,'mini_missle','heroes')\n Attack(self.game,vec(self.pos.x,self.pos.y),vec(1,0),self.damage,self.type_of_damage,'mini_missle','heroes')\n Attack(self.game,vec(self.pos.x,self.pos.y),vec(0,-1),self.damage,self.type_of_damage,'mini_missle','heroes')\n Attack(self.game,vec(self.pos.x,self.pos.y),vec(0,1),self.damage,self.type_of_damage,'mini_missle','heroes')\n def ninja_AI(self):\n if self.detect_enemy():\n if self.can_attack():\n self.attack_enemy()\n \n self.dodge_melee(20)\n if self.can_attack()!=True:\n self.move_to_enemy()\n \n self.following_jump()\n else:\n self.dodge_range()\n def canon_AI(self):\n if self.detect_enemy():\n if self.can_attack_range():\n self.canon_shoot()\n def star_AI(self):\n if self.detect_enemy():\n self.star_shoot()\n \n def primitive_AI(self):\n if self.detect_enemy():\n if self.can_attack():\n self.attack_enemy()\n if self.can_attack()!=True:\n self.move_to_enemy() \n else:\n pass\n def passive_AI(self): \n if self.detect_enemy():\n if self.can_attack():\n self.attack_enemy()\n if self.can_attack()!=True:\n self.move_to_enemy() \n else:\n self.dodge_range()\n def jumper_AI(self):\n if self.detect_enemy():\n if self.can_attack():\n self.attack_enemy()\n if self.can_attack()!=True:\n self.move_to_enemy() \n self.random_jumping()\n else:\n pass\n def AI(self):\n if self.type=='primitive':\n self.primitive_AI()\n elif self.type=='passive':\n self.passive_AI()\n elif self.type=='ninja':\n self.ninja_AI()\n elif self.type=='jumper':\n self.jumper_AI()\n elif self.type=='canon':\n self.canon_AI()\n elif self.type=='star':\n self.star_AI()\n \n def necrologue(self):\n if self.health>0:\n live=True\n else:\n live=False\n dealed_damage=0\n accuracy=0\n hits=0\n i=0\n lasthit=False \n for attack in self.list_of_attacks:\n i+=1\n try:\n if attack.attacked:\n dealed_damage+=attack.total_damage \n hits+=1\n except:\n pass\n try:\n lasthit=attack.lasthit\n except:\n pass\n try:\n accuracy=round((hits/i),2)\n except:\n accuracy=0\n \n\n dictionary={\"type\":self.type,\"level\":self.level,\"time survived\":int((pg.time.get_ticks()-self.creation_time)/1000),\n \"dealed damage\":dealed_damage,\"accuracy\":accuracy,\"last hit\":lasthit,\"survived\":live}\n self.game.necrologue_list.append(dictionary)\n \n \n def update(self):\n if self.speed!=0:\n self.acc = vec(0, GRAVITY)\n if self.state==\"right\":\n self.image=self.right_image\n else:\n self.image=self.left_image\n self.AI()\n self.acc.x += self.vel.x * PLAYER_FRICTION \n self.vel += self.acc\n self.pos += self.vel + 0.5 * self.acc \n self.rect.x = self.pos.x\n self.collide('x')\n self.rect.y = self.pos.y\n self.collide('y')\n self.draw_health_bar()\n \n if self.health<=0:\n \n self.necrologue()\n self.kill()\n \n \n for hero in self.game.heroes:\n if self.exp>0:\n\n \n delta=hero.level-self.level\n exp=int(self.exp/len(self.game.heroes))\n hero.exp+=exp+1\n self.exp-=exp+1\n Floating_number(self.game,self.pos.x,self.pos.y,\"+\"+str(exp)+\" exp\",\"expirence\")\n \n \n \nclass Actor(pg.sprite.Sprite):\n def __init__(self,game,x,y,plot_name,sub_stat=0):\n self.game=game\n \n self.groups=game.all_sprites,game.actors\n \n pg.sprite.Sprite.__init__(self,self.groups)\n self.state='right'\n self.start=vec(x,y)\n self.plot=\"plot_\"+plot_name+\".py\"\n self.image=pg.Surface((TILESIZE,TILESIZE))\n self.image.fill(BLACK)\n self.game=game\n self.type=type\n self.active=False\n self.spawn_time=pg.time.get_ticks()\n self.rect = self.image.get_rect()\n self.rect.center=(x,y)\n self.vel=vec(0,0)\n self.pos=vec(x,y)\n self.acc = vec(0, 0)\n self.detect_trigger=1\n self.load_trigger=1\n self.execute_trigger=1\n self.condition=\"staying\"\n self.begin_time=pg.time.get_ticks()\n self.shoot_rot=vec(-1,0) \n \n \n\n \n\n self.load_plot()\n spec = importlib.util.spec_from_file_location(self.plot, PLOT_FOLDER+self.plot)\n plot = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(plot)\n self.activation_radius=plot.radius\n self.living_time=plot.life_time\n self.call_key=plot.call_key\n try:\n self.shots=plot.shots\n except:\n pass\n self.name=plot.name\n self.icon=pg.image.load(plot.icon_path)\n try:\n self.initiator=plot.initiator\n except:\n self.initiator=False\n self.image=self.icon\n self.timer=5000\n self.est_timer=pg.time.get_ticks()\n def load_plot(self):\n\n \n \n spec = importlib.util.spec_from_file_location(self.plot, PLOT_FOLDER+self.plot)\n plot = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(plot)\n \n \n def show_words_on_second(self,string,timer,time_pos,begin_time):\n now=pg.time.get_ticks()\n \n if pg.time.get_ticks()>=begin_time+time_pos*1000 and pg.time.get_ticks()<=begin_time+timer*1000+time_pos*1000:\n Floating_number(self.game,self.game.player_1.pos.x-100,self.game.player_1.pos.y+400,string,\"words\",timer)\n Floating_number(self.game,self.game.player_1.pos.x-420,self.game.player_1.pos.y+470,self.name,\"words\",timer)\n HUD.draw_player_icon(self.game.screen,self.icon,vec(0,0))\n \n \n \n\n def activate(self):\n if self.detect_trigger>0:\n for hero in self.game.heroes:\n if math.fabs(hero.pos.x-self.pos.x)=self.living_time*1000:\n \n \n self.kill()\n \n except:\n pass\n def bug_fix_1(self):\n if pg.time.get_ticks()-self.spawn_time-7000<=self.timer:\n \n self.pos=self.start\n def collide(self, dir):\n if dir == 'x':\n hits = pg.sprite.spritecollide(self, self.game.walls, False)\n if hits:\n if self.vel.x > 0:\n self.pos.x = hits[0].rect.left - self.rect.width\n if self.vel.x < 0:\n self.pos.x = hits[0].rect.right\n self.vel.x = 0\n self.rect.x = self.pos.x\n\n if dir == 'y':\n hits = pg.sprite.spritecollide(self, self.game.walls, False)\n if hits:\n if self.vel.y > 0:\n self.pos.y = hits[0].rect.top - self.rect.height\n if self.vel.y < 0:\n self.pos.y = hits[0].rect.bottom\n self.vel.y = 0\n self.rect.y = self.pos.y\n \n if self.vel.y==0:\n self.state='standing'\n def move(self,dir,speed):\n if dir=='right':\n self.vel.x=speed\n \n \n self.rot='right'\n \n self.shoot_rot=vec(-1,0) \n elif dir=='left':\n self.vel.x=-speed\n self.rot='left'\n self.shoot_rot=vec(1,0) \n elif dir=='up':\n self.vel.y=-speed*self.dir.x\n \n elif dir=='down':\n self.vel.y=-speed*self.dir.x\n \n\n def update(self):\n self.bug_fix_1()\n self.die_after_ending()\n self.activate()\n for hero in self.game.heroes:\n if math.fabs(hero.pos.x-self.pos.x)= self.death_time:\n self.kill()\n def set_image(self):\n \n if self.type_of_attack=='punch':\n self.image = pg.Surface([self.width,self.height], pg.SRCALPHA,32)\n \n\n elif self.type_of_attack=='arrow':\n self.image=pg.Surface([self.width,self.height])\n self.image.fill(GREEN)\n \n elif self.type_of_attack=='magic_missle':\n self.image=pg.Surface([self.width,self.height])\n self.image.fill(GREEN)\n elif self.type_of_attack=='bullet':\n self.image=pg.Surface(self.width,self.height)\n self.image.fill(GREEN)\n \n \n elif self.type_of_attack=='grenade':\n self.image=pg.Surface([self.width,self.height])\n self.image.fill(GREEN)\n \n elif self.type_of_attack=='canon_ball':\n self.image=pg.Surface([self.width,self.height])\n self.image.fill(GREEN)\n elif self.type_of_attack=='mini_missle':\n self.image=pg.Surface([self.width,self.height])\n self.image.fill(GREEN)\n elif self.type_of_attack=='meteor':\n self.image=pg.Surface([self.width,self.height])\n self.image.fill(GREEN)\n \n \n def size(self):\n if self.type_of_attack=='punch':\n \n speed_k=0\n width=1.2*self.start_w\n height=self.start_h\n self.death_time=30\n distance='melee'\n self.penetration=True\n self.dir=self.dir.reflect(vec(1,0))\n \n if self.dir.x>=-1.01 and self.dir.x<=0.99:\n self.pos.x-=self.start_w\n \n\n elif self.type_of_attack=='arrow':\n speed_k=1\n width=50\n height=10\n self.death_time=5000\n distance='ranged'\n \n elif self.type_of_attack=='magic_missle':\n speed_k=0.75\n width=20\n height=15\n self.death_time=4000\n distance='ranged'\n elif self.type_of_attack=='bullet':\n \n speed_k=1.5\n width=10\n height=10\n self.death_time=3000\n distance='ranged'\n elif self.type_of_attack=='grenade':\n \n speed_k=0.125\n width=15\n height=15\n self.death_time=4000\n distance='ranged'\n self.is_falling=True\n elif self.type_of_attack=='canon_ball':\n self.gravity=True\n width=30\n height=30\n self.death_time=6000\n speed_k=0.5\n distance='ranged'\n elif self.type_of_attack=='mini_missle':\n \n width=5\n height=5\n self.death_time=2000\n speed_k=1.2\n distance='ranged'\n elif self.type_of_attack=='meteor':\n width=32\n height=32\n self.death_time=1000\n speed_k=1\n distance='ranged'\n self.penetration=True\n try:\n if self.penetration==True:\n self.penetration=True\n except:\n self.penetration=False\n try:\n if self.is_falling==True:\n self.is_falling=True\n except:\n self.is_falling=False\n self.width=width\n self.height=height\n self.speed=speed_k*self.speed_constant\n self.distance=distance\n\n def start_timer(self):\n if pg.time.get_ticks()-self.creation>=300:\n return True\n else:\n return False\n\n def move(self):\n if self.distance!='melee':\n self.vel.x=-self.speed*self.dir.x\n self.vel.y=-self.speed*self.dir.y\n \n\n def gravity(self):\n self.acc=vec(0,GRAVITY/2)\n def collide_with_wall(self):\n \n if self.penetration==False:\n if self.start_timer():\n hits= pg.sprite.groupcollide(self.game.attacks,self.game.walls,True,False) \n if hits:\n self.collided=True\n \n \n \n def strike(self,group):\n hits=pg.sprite.spritecollide(self,group,False,False)\n if hits:\n for hit in hits:\n \n \n if self.type_of_damage=='physical':\n if self.damage-hit.p_armor<=0:\n damage=1\n else:\n damage=self.damage-hit.p_armor\n elif self.type_of_damage=='magical':\n if self.damage-hit.m_armor<=0:\n damage=1\n else:\n damage=self.damage-hit.m_armor\n elif self.type_of_damage=='clear':\n damage=self.damage\n \n hit.health-=damage\n if self.isStunning:\n hit.isStunned=True\n Floating_number(self.game,hit.pos.x,hit.pos.y,\"-\"+str(damage),self.type_of_damage)\n self.attacked=True\n self.total_damage=damage\n if hit.health<=0:\n self.lasthit=True\n self.kill()\n \n def update(self):\n\n \n \n if self.is_falling:\n self.gravity()\n if self.danger=='heroes' or self.danger=='all':\n self.strike(self.game.heroes)\n \n if self.danger=='enemies' or self.danger=='all':\n self.strike(self.game.enemies)\n \n self.move()\n self.death_timer()\n \n \n self.vel += self.acc\n self.pos += self.vel + 0.5 * self.acc\n self.rect.x=self.pos.x\n self.rect.y=self.pos.y\n self.collide_with_wall()\n\nclass Trap(pg.sprite.Sprite):\n def __init__(self,game,x,y,w,h,type):\n self.groups=game.all_sprites\n pg.sprite.Sprite.__init__(self,self.groups)\n self.image= pg.Surface([w,h], pg.SRCALPHA,32)\n self.game=game\n self.rot=0\n self.rot_speed=60\n self.last_attack=pg.time.get_ticks()\n self.type=type\n self.frame=0\n \n self.last_animation=pg.time.get_ticks()\n if type=='usual':\n self.damage=20\n self.reload=1\n self.type_of_damage=\"physical\"\n if type==\"saw\":\n self.damage=15\n self.image=pg.image.load(saw_image)\n self.image.set_colorkey(BLACK)\n self.orig=self.image\n self.reload=2\n self.type_of_damage=\"clear\"\n\n self.x=x\n self.y=y\n self.rect=self.image.get_rect()\n self.rect.x=x\n self.rect.y=y\n \n def attack_trap(self,group):\n hits=pg.sprite.spritecollide(self,group,False,False)\n \n if hits:\n for hit in hits:\n if self.damage-hit.p_armor<=0:\n damage=1\n else:\n damage=self.damage-hit.p_armor\n #self.game.DJ.play_effect('slash')\n hit.health-=damage\n Floating_number(self.game,hit.pos.x,hit.pos.y,\"-\"+str(damage)+\"hp\",self.type_of_damage)\n\n \n self.last_attack=pg.time.get_ticks()\n def attack_saw(self,group):\n hits=pg.sprite.spritecollide(self,group,False,False)\n \n if hits:\n for hit in hits:\n if pg.sprite.collide_mask(self,hit): \n damage=self.damage\n # self.game.DJ.play_effect('slash')\n hit.health-=damage\n Floating_number(self.game,hit.pos.x,hit.pos.y,\"-\"+str(damage)+\"hp\",self.type_of_damage)\n self.last_attack=pg.time.get_ticks()\n \n\n \n \n \n \n \n def update(self):\n \n if self.type=='saw':\n if pg.time.get_ticks()-self.last_attack>=self.reload*1000:\n \n self.attack_saw(self.game.enemies)\n self.attack_saw(self.game.heroes)\n self.rect.centerx=self.x\n self.rect.centery=self.y\n self.rot = (self.rot + self.rot_speed * self.game.dt) % 360\n self.image = pg.transform.rotate(self.orig,self.rot)\n\n else:\n \n if pg.time.get_ticks()-self.last_attack>=self.reload*1000:\n self.attack_trap(self.game.heroes)\n self.attack_trap(self.game.enemies)\n \n \n\n\n\n\nclass Ladder(pg.sprite.Sprite):\n def __init__(self, game, x, y,w,h):\n self.groups = game.ladders\n pg.sprite.Sprite.__init__(self, self.groups)\n self.game = game\n self.rect=pg.Rect(x,y,w,h)\n self.x=x\n self.y=y\n self.rect.x=x\n self.rect.y=y\nclass Chest(pg.sprite.Sprite):\n def __init__(self, game, x, y,w,h,rarity):\n \n self.groups = game.chests,game.all_sprites\n pg.sprite.Sprite.__init__(self, self.groups)\n self.game = game\n self.rect=pg.Rect(x,y,w,h)\n self.pos=vec(x,y)\n self.rect.x=self.pos.x\n self.rect.y=self.pos.y\n self.rarity=rarity\n self.num_of_items=6\n self.image = pg.Surface([w,h], pg.SRCALPHA,32)\n self.image = self.image.convert_alpha()\n self.items=[]\n self.fill_with_items()\n \n def rand_item(self,type):\n while True:\n with open(items_file) as file:\n data=json.load(file)\n i=random.randint(0,len(data)-1)\n item=Item(self.game,self.rect.x,self.rect.y,i)\n item.kill()\n if item.rarity==type:\n break\n return item\n \n def rand_selected(self,rarity,part):\n while True:\n with open(items_file) as file:\n data=json.load(file)\n i=random.randint(0,len(data)-1)\n item=Item(self.game,self.rect.x,self.rect.y,i)\n item.kill()\n if item.rarity==rarity and item.type==part:\n break\n \n return item\n \n\n def use(self):\n print(\"This is \"+self.rarity.upper()+\" chest!\")\n if len(self.items)>0:\n safe=[]\n print(\"It contains:\")\n i=1\n \n for item in self.items:\n \n print(str(i)+\") \"+item.name)\n \n i+=1\n safe.append(item)\n a=input(\"What you want to do? 1)take one item 2)take all 3)close \")\n try:\n if a.strip()=='1':\n if len(self.game.player_1.inventory)= self.death_timer:\n self.kill()\n # for hero in self.game.heroes:\n # hero.cutscene_up.clear()\n # hero.cutscene_down.clear()\n def get_text(self,name):\n with open(languages_folder+language_manager.get_language()+\"\\\\words_\"+name+\".txt\") as file:\n self.string=file.read()\n def update(self):\n \n self.float_up()\n self.die()\n self.rect.x=self.pos.x\n self.rect.y=self.pos.y\n\n\nclass SpriteList:\n\n \n\n def __init__(self, filename):\n\n self.spritelist = pg.image.load(filename).convert()\n\n\n\n def get_image(self, x, y, width, height):\n\n \n\n image = pg.Surface((width, height))\n\n image.blit(self.spritelist, (0, 0), (x, y, width, height))\n\n \n\n return image\n\n\n\n\nclass Spawn(pg.sprite.Sprite):\n def __init__(self, game, x, y):\n self.groups = game.all_sprites,game.spawns,\n pg.sprite.Sprite.__init__(self, self.groups)\n self.game = game\n self.rect=pg.Rect(x,y,1,1)\n self.pos=vec(x,y)\n self.rect.x=self.pos.x\n self.rect.y=self.pos.y\n self.it=0\n self.image = pg.Surface([1,1], pg.SRCALPHA,32)\n self.image = self.image.convert_alpha()\n self.last_spawn=pg.time.get_ticks()\n self.to_load=[]\n \n def load_global_pack(self,pack):\n \n self.global_pack=pack\n def load_local_pack(self):\n self.to_load=[]\n for enemy in self.global_pack:\n \n self.to_load.append({\"type\":enemy[\"type\"],\"level\":enemy[\"level\"],\"amount\":(enemy[\"amount\"]/len(self.game.spawns))})\n\n\n def spawn(self):\n for enemy in self.to_load:\n while enemy[\"amount\"]>0:\n enemy[\"amount\"]-=1\n spread=random.randint(-20,20)\n pos=vec(self.pos.x+spread,self.pos.y)\n type=enemy[\"type\"]\n level=enemy[\"level\"]\n archive=[pos,type,level]\n self.game.player_1.spawn_enemy(archive)\n \n def spawn_after(self,seconds):\n if pg.time.get_ticks()-self.last_spawn>=seconds*1000:\n self.spawn()\n self.last_spawn=pg.time.get_ticks()\n \n def update(self):\n self.rect.x=self.pos.x\n self.rect.y=self.pos.y\n if self.it==0:\n self.spawn()\n \n self.it-=1\n self.spawn_after(5)\n \n\nclass Platform(pg.sprite.Sprite):\n def __init__(self, game, x, y,w,h,is_slippery=False):\n self.groups = game.platforms\n pg.sprite.Sprite.__init__(self, self.groups)\n self.game = game\n self.rect=pg.Rect(x,y,w,h)\n self.is_slippery=is_slippery\n self.rect.x=x\n self.rect.y=y\n\n \n\n \n \n","sub_path":"Project/Project/sprites.py","file_name":"sprites.py","file_ext":"py","file_size_in_byte":52027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"70133758","text":"#!/usr/bin/python3\n\nfrom __future__ import division\nfrom __future__ import print_function, unicode_literals\nfrom random import randint\nfrom os import urandom\nimport math as m\nimport string\nimport sys\n\n# \n# Generate binnary randons.\n#\n\ndef genbyte(length):\n return urandom(length)\n\n#\n# Generate rangdom numbers.\n#\n\ndef genran(length):\n num_list = []\n for i in range(length):\n num_list.append(randint(0,300))\n return num_list\n\n#\n# Expand number by continuous fractions.\n#\n\ndef genkey(N):\n while True:\n yield N//1\n f = N - (N//1)\n if f < 0.0001:\n break\n N = 1/f\n\n#\n# Special function to xor two strings.\n#\n\ndef xor_strings(s, t):\n \"\"\"xor two strings together\"\"\"\n if isinstance(s, str):\n # Text strings contain single characters\n return b\"\".join(chr(ord(a) ^ ord(b)) for a, b in zip(s, t))\n else:\n # Python 3 bytes objects contain integer values in the range 0-255\n return bytes([a ^ b for a, b in zip(s, t)])\n\ndef main():\n\n # Define a key.\n\n key_seed = 23.1\n garb_length = 100\n jump = 2\n\n # Create the key.\n\n clear_message = \"This is a cool message which cannot be seen !!\"\n\n # Generate the key of \n\n key = list(genkey(m.sqrt(key_seed)))\n\n # Check the size of the key in relation to the message.\n\n if (len(clear_message) > jump**len(key)):\n sys.exit(\"ERROR: You need a better seed\")\n\n # Select the key due to jump.\n\n zkey = []\n\n for i in range(0,len(key),jump):\n zkey.append(key[i])\n\n # Separate the size of the key == message.\n\n zkey_ms = zkey[0:len(clear_message)]\n\n # Convert byte arrays.\n\n clear_message_byte = clear_message.encode('utf8')\n crypt_message_byte = ' '.join(map(str,zkey_ms)).encode('utf8')\n\n print (\"+ Clear message: \", clear_message_byte, \"\\n\")\n print (\"+ The Key: \", crypt_message_byte,\"\\n\")\n\n crypt_message_safe = xor_strings(clear_message_byte, crypt_message_byte)\n\n print (\"+ Crypt message (core): \", crypt_message_safe,\"\\n\")\n\n crypt_message_safe = crypt_message_safe + genbyte(garb_length)\n\n print (\"+ Crypt message (core + backward trash): \", crypt_message_safe,\"\\n\")\n\n crypt_message_safe = genbyte(garb_length) + crypt_message_safe \n\n print (\"+ Crypt message (backward trash + trashed message): \", crypt_message_safe,\"\\n\")\n\n file_out = open(\"test.dat\",\"w\")\n for i in range(len(crypt_message_safe)):\n file_out.write(str(crypt_message_safe[i])) # dieharder -a -f test.dat\n file_out.close()\n\n # Append trash to message.\n\n crypt_message_safe = xor_strings(crypt_message_safe[garb_length:garb_length + len(clear_message)], crypt_message_byte)\n\n print (\"+ Decrypted message: \", crypt_message_safe.decode('utf8'),\"\\n\")\n\nif __name__== \"__main__\":\n main()\n\n","sub_path":"crypy.py","file_name":"crypy.py","file_ext":"py","file_size_in_byte":2799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"553221885","text":"#!/usr/bin/env python3\n\n# -*- coding: UTF-8 -*-\n\nimport sys, codecs\n\nsys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach())\n\n# use this and then prefix all function names with corpus.\n#import corpus\n# or use this\nfrom corpus import loadTextFromFile, tokenize, getTokenCounts, prettyPrintFrequencyProfile, relativizeTokenCounts\n\nfrom math import log\n\n\nmytext = loadTextFromFile(\"pg873.txt\")\n\n# tokenize mytext and return list of tokens\ntokens = tokenize(mytext)\n\n# count tokens\nmydict = getTokenCounts(tokens)\nrelativizeTokenCounts(mydict)\n\n# pretty-print tokens and frequencies\n#prettyPrintFrequencyProfile(mydict, sortbyfrq=True, myreverse=True)\n\nmytext = loadTextFromFile(\"sports-bbc.txt\")\nmysportsdict = getTokenCounts(tokenize(mytext))\nrelativizeTokenCounts(mysportsdict)\n\nunknowntext = \"\"\"Yesterday we scored ten goals in the last 45 minutest of the game.\"\"\"\n\n\n\"\"\"\nWimbledon 2013: Andy Murray's victory could boost British tennis\nComments (149)\nAll too often sporting moments and achievements are given a misplaced historical significance. Not on Sunday.\nAndy Murray made genuine history on Wimbledon's Centre Court by winning the men's singles in straight sets against Serb Novak Djokovic to become the first British male champion since Fred Perry in 1936.\n Murray got to the top not because of the Lawn Tennis Association and this country's development programmes but in spite of them\nComparisons of this nature are always pretty futile, but as achievements go it ranks alongside England's World Cup triumph in 1966, England's Rugby World Cup victory in 2003 and Sir Bradley Wiggins ending Britain's long wait for a winner of the Tour de France.\nBut in some ways, Murray's achievement surpasses all those. For Wimbledon to host the greatest tennis tournament in the world for so many years without a winner or even a serious challenger has been a serious embarrassment. \n\"\"\"\n\n\n\"\"\"\nThe young fisherman likes pomegranates.\n\"\"\"\n\n\nukntokens = tokenize(unknowntext)\nhpgprob = 0.0\nbbcprob = 0.0\nfor token in ukntokens:\n hpgprob += log(mydict.get(token, 0.000000000001))\n bbcprob += log(mysportsdict.get(token, 0.000000000001))\nif hpgprob > bbcprob:\n print(\"This is probably related to the House of Pomeg.\")\nelse:\n print(\"This is probably related to BBC Sports articles\")\nprint(\"hpgprob:\", hpgprob)\nprint(\"bbcprob:\", bbcprob)\n","sub_path":"src/Week3/complete-fp.py","file_name":"complete-fp.py","file_ext":"py","file_size_in_byte":2346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"77227774","text":"\"\"\"\n@version: python3.7\n@author: ‘mengyuantan‘\n@contact: tanmy1016@126.com\n@desc: Consider the SNR of genetic algorithm\n\"\"\"\nimport sys, getopt\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.animation as animation\nimport tkinter.messagebox\nimport time\n\nis_debugging = False\nis_saving = False\nshow_detail = True\n\nROOM_SIZE = np.array([10, 10])\nDNA_SIZE = ROOM_SIZE[0] * ROOM_SIZE[1] # DNA length\nMIN_EFF_AREA = 0.88\nif is_debugging:\n N_GENERATIONS = 50\n POP_SIZE = 5 # population size\nelse:\n POP_SIZE = 100 # population size\n N_GENERATIONS = 3000\nCROSS_RATE = 0.8 # mating probability (DNA crossover)\nplt.figure(figsize=(12, 6)) # set the figure size\n\n# set parameters\ntethaHalf = 60\nm = np.int(- np.log(2) / np.log(np.cos(np.deg2rad(tethaHalf))))\nI0 = 0.73\nnLed = 60\nPt = 0.02 # W\nPt *= nLed * nLed\ngamma = 0.53 # A/W\ndimX, dimY, dimZ, REC_HEIGHT = 5, 5, 3, 0.85\nngx, ngy = dimX * 10, dimY * 10\nht, hr = dimZ, REC_HEIGHT\nhtr = ht - hr\nx = np.linspace(0 + 0.05, dimX - 0.05, ngx)\ny = np.linspace(0 + 0.05, dimY - 0.05, ngy)\nxr, yr = np.meshgrid(x, y)\n\n# load data\nnoise_value_data, Hn_value_data = np.array([]), np.array([])\n\nfor i in range(ROOM_SIZE[0]):\n for j in range(ROOM_SIZE[1]):\n noise_value_data = np.append(noise_value_data,\n np.load(r'noise_value_data/noise_value_%s.npy' % (str(i) + str(j))))\n Hn_value_data = np.append(Hn_value_data,\n np.load(r'Hn_value_data/Hn_value_%s.npy' % (str(i) + str(j))))\nnoise_value_data = noise_value_data.reshape(ROOM_SIZE[0], ROOM_SIZE[1], 50, 50)\nHn_value_data = Hn_value_data.reshape(ROOM_SIZE[0], ROOM_SIZE[1], 50, 50)\n\nid_num = np.load('log.npy')\n# id_num = 0\nroom_id = str(id_num).zfill(3)\nroom = np.load('room_data/%s.npy' % room_id)\n# room = np.ones((10, 10))\n#\n# room[:1, :3] = 0\n# room[-3:, :3] = 0\n\nroom_area = len(np.where(room == 1)[0])\nled_num = np.int((room_area / 25) - 1e-3) + 1\nrepeat_arr = np.ones(10, dtype=np.int) * 5\nroom_mut = np.repeat(room, repeat_arr, axis=0)\nroom_mut = np.repeat(room_mut, repeat_arr, axis=1)\nroom_xx, room_yy = np.where(room == 0)[0] / 2 + 0.25, np.where(room == 0)[1] / 2 + 0.25\n\n\ndef plotting(DNA, gen, saving_pic, is_ending):\n plt.cla()\n DNA = DNA.reshape(-1, ROOM_SIZE[0], ROOM_SIZE[1])[0]\n xt, yt = [], []\n x, y = np.array([]), np.array([])\n S, N = np.zeros((ngx, ngy)) + 1e-9, np.zeros((ngx, ngy)) + 1e-9\n indexes = np.where(DNA == 1)\n led = len(indexes[0])\n for j in range(led):\n xt.append(indexes[0][j])\n yt.append(indexes[1][j])\n x = np.append(x, indexes[0][j] / 2 + 0.25)\n y = np.append(y, indexes[1][j] / 2 + 0.25)\n\n for k in range(len(xt)):\n S += (gamma ** 2) * ((Pt * Hn_value_data[xt[k]][yt[k]]) ** 2)\n N += noise_value_data[xt[k]][yt[k]]\n SNR = 10 * np.log10(S / N) * room_mut\n effect_zone = cal_effect_zone(SNR)\n\n # ax1 = plt.subplot(212)\n # ax1.cla()\n # max_value_idx = np.argmax(value_container)\n # show_max = 'value = %s' % str(round(value_container[max_value_idx][0], 3))\n # ax1.plot(max_value_idx, value_container[max_value_idx], 'rs')\n # ax1.annotate(show_max,\n # xytext=(max_value_idx * 0.8, value_container[max_value_idx]),\n # xy=(max_value_idx, value_container[max_value_idx]))\n # if is_ending:\n # ax1.plot(range(len(value_container[:max_value_idx + 1])), value_container[:max_value_idx + 1], 'k')\n # else:\n # ax1.plot(range(len(value_container)), value_container, 'k')\n # ax1.set_xlabel('Generations')\n # ax1.set_ylabel('Effect Area (%)')\n\n # plt.subplot(221)\n # fig = plt.gcf()\n # ax = fig.add_subplot(2, 2, 1, projection='3d')\n # ax.plot_surface(xr, yr, SNR.T, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))\n # ax.set_xlabel('X (m)')\n # ax.set_ylabel('Y (m)')\n # ax.set_zlabel('SNR (dB)')\n # ax.set_title('Generations : %d ' % gen)\n\n plt.subplot(121)\n plt.cla()\n levels = np.hstack((np.linspace(np.min(SNR[SNR != 0]), 13.6 - (np.max(SNR) - 13.6) / 4, 4),\n np.linspace(13.6, np.max(SNR), 5))) if np.max(SNR) > 13.6 else np.linspace(0, np.max(SNR), 9)\n plt.contourf(xr, yr, SNR.T, levels=levels, alpha=.75)\n C = plt.contour(xr, yr, SNR.T, levels=levels, colors='black', linewidths=1)\n plt.clabel(C, fmt='%.1f', inline=True, fontsize=8)\n plt.xlabel('X (m)')\n plt.ylabel('Y (m)')\n plt.title('SNR (dB) Effect Area: {0} %'.format(round(round(effect_zone, 4) * 100, 2)))\n\n plt.subplot(122)\n plt.scatter(x, y)\n plt.scatter(room_xx, room_yy, s=[1200], marker='s', c='gray')\n plt.xlim(0, 5)\n plt.ylim(0, 5)\n plt.xlabel('X (m)')\n plt.ylabel('Y (m)')\n # plt.title('Generations : %d ' % gen)\n plt.title('room model')\n\n # if saving_pic:\n # plt.savefig('room_result_SNR_contourline/%s_fig.jpg' % room_id)\n plt.grid()\n plt.pause(0.1)\n\n\ndef cal_effect_zone(arr): return len(arr[arr >= 13.6]) / (room_area * 25)\n\n\ndef LED_fun(cur, tar): return np.abs(cur - tar)\n\n\ndef get_common(loc): return np.argsort(np.bincount(loc))[::-1][:led_num]\n\n\ndef F(source): # source shape [-1, 100]\n source = source.reshape(-1, ROOM_SIZE[0], ROOM_SIZE[1])\n value, value_orig, led_gap = np.array([]), np.array([]), np.array([])\n for i in range(source.shape[0]):\n indexes = np.where(source[i] == 1)\n xt, yt = [], []\n led = len(indexes[0])\n for j in range(led):\n xt.append(indexes[0][j])\n yt.append(indexes[1][j])\n S, N = np.zeros((ngx, ngy)) + 1e-9, np.zeros((ngx, ngy)) + 1e-9\n\n for k in range(len(xt)):\n S += (gamma ** 2) * ((Pt * Hn_value_data[xt[k]][yt[k]]) ** 2)\n N += noise_value_data[xt[k]][yt[k]]\n\n SNR = 10 * np.log10(S / N) * room_mut\n try:\n SNR_min, SNR_max, SNR_avg = np.min(SNR[SNR != 0]), np.max(SNR[SNR != 0]), np.mean(SNR[SNR != 0])\n except:\n SNR_min, SNR_max, SNR_avg = 1e-9, 1e-9, 1e-9\n\n led_gap = np.append(led_gap, LED_fun(cur=led, tar=led_num))\n value_orig = np.append(value_orig, cal_effect_zone(SNR))\n value = value_orig\n value[led_gap != 0] = 0\n\n return value, (SNR_min, SNR_max, SNR_avg) # to find the maximum of this function\n\n\n# find non-zero fitness for selection\ndef get_fitness(pred): return pred + 1e-9 # + 1e-3 - np.min(pred)\n\n\n# def get_fitness(pred): return ((pred - np.min(pred)) + 1e-3) / ((np.max(pred) - np.min(pred)) + 1e-3)\n\ndef select(pop, fitness): # nature selection wrt pop's fitness\n idx = np.random.choice(np.arange(POP_SIZE), size=POP_SIZE, replace=True,\n p=fitness / fitness.sum())\n return pop[idx]\n\n\ndef crossover(parent, pop): # mating process (genes crossover)\n if np.random.rand() < CROSS_RATE:\n i_ = np.random.randint(0, POP_SIZE, size=1) # select another individual from pop\n cross_points = np.random.randint(0, 2, size=DNA_SIZE).astype(np.bool) # choose crossover points\n parent[cross_points] = pop[i_, cross_points] # mating and produce one child\n return parent\n\n\ndef mutate(child, rate):\n for point in range(DNA_SIZE):\n if np.random.rand() < rate:\n child[point] = 1 if child[point] == 0 else 0\n return child\n\n\ndef run(pre_pop):\n start_time = time.time()\n global value_container\n value_container = [0]\n DNA_saver = None\n MUTATION_RATE = 0.02 # mutation probability\n Flag = False\n\n # Start initialization\n if pre_pop is None:\n pop = np.array([])\n for _ in range(POP_SIZE):\n each = np.zeros((1, DNA_SIZE))\n each[0][np.random.choice(DNA_SIZE, led_num, replace=False)] = 1\n pop = np.append(pop, each)\n pop = pop.reshape(POP_SIZE, DNA_SIZE)\n else:\n pop = pre_pop\n\n pop_and = np.tile(room.reshape((1, DNA_SIZE)), (POP_SIZE, 1))\n\n plt.ion()\n\n for count in range(N_GENERATIONS):\n pop = pop * pop_and\n F_values, _ = F(pop)\n\n # GA part (evolution)\n fitness = get_fitness(F_values)\n if count % 50 == 0:\n most_fitted_DNA = pop[np.argmax(fitness), :].reshape(1, DNA_SIZE)\n value, detail = F(most_fitted_DNA)\n if show_detail:\n if value > np.max(value_container):\n DNA_saver = [most_fitted_DNA, count]\n # print('Generations: %d value = %f position: %s' %\n # (count, value, np.where(most_fitted_DNA.reshape(1, DNA_SIZE) == 1)[1]))\n value_container.append(value)\n # plotting(most_fitted_DNA, count, saving_pic=False, is_ending=False)\n elif count % 500 == 0:\n print('Generation: %d' % count)\n if np.max(value_container) > MIN_EFF_AREA:\n # np.save('log.npy', np.int(id_num + 1))\n break\n\n if count == N_GENERATIONS - 1:\n # np.save('log.npy', np.int(id_num + 1))\n if DNA_saver and np.max(value_container) > MIN_EFF_AREA:\n # np.save('room_result_SNR_contourline/%s_out.npy' % room_id, DNA_saver[0])\n # plotting(DNA_saver[0], DNA_saver[1], saving_pic=True, is_ending=True)\n print('{0} Finish.'.format(room_id))\n else:\n # np.save('room_result_SNR_contourline/%s_out_error.npy' % room_id, np.zeros((1, DNA_SIZE)))\n print('********************************************Failed.********************************************')\n # plotting(most_fitted_DNA, N_GENERATIONS, saving_pic=True, is_ending=False)\n break\n\n # crossover and mutate\n pop = select(pop, fitness) # select the parent\n pop_copy = pop.copy()\n for parent in pop:\n child = crossover(parent, pop_copy)\n child = mutate(child, MUTATION_RATE)\n parent[:] = child # parent is replaced by its child\n\n end_time = time.time()\n use_time = round(end_time - start_time, 3)\n print(\"Program running time: {}s\".format(use_time))\n time_saver = np.load(\"time_saver.npy\")\n time_saver = np.append(time_saver, use_time)\n np.save(\"time_saver.npy\", time_saver)\n # plt.ioff()\n # plt.show()\n\n\nif __name__ == '__main__':\n run(pre_pop=None)\n","sub_path":"GA_each_shape_SNR.py","file_name":"GA_each_shape_SNR.py","file_ext":"py","file_size_in_byte":10340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"46266200","text":"from . import household as household\nfrom django.contrib.auth.decorators import login_required\nfrom ..models.household_models import Household\nfrom ..forms.household_forms import HouseholdForm\n\n\ndef save_form_old(request, form):\n form_saved = False\n if form.is_valid() and form.has_changed():\n form_saved = False\n fas_object = form.save(commit=False)\n fas_object.household = household.get(request.session['household'])\n fas_object.save()\n form_saved = True\n return form_saved\n\n\ndef save_form_with_no_has_change(request, form):\n form_saved = False\n if form.is_valid():\n form_saved = False\n fas_object = form.save(commit=False)\n fas_object.household = household.get(request.session['household'])\n fas_object.save()\n form_saved = True\n return form_saved\n\n\ndef save_forms(request, forms):\n form_saved = False\n for form in forms:\n if form.is_valid() and form.has_changed():\n form_saved = False\n fas_object = form.save(commit=False)\n fas_object.household = household.get(request.session['household'])\n fas_object.save()\n form_saved = True # TODO: add proper check to verify if all forms are saved\n return form_saved\n\n\ndef save_formset(forms, model, household_id, **kwargs): #Pass key-word args for filter\n \"\"\"add, update and delete models using formset\"\"\"\n if forms.is_valid():\n active_ids = []\n for form in forms:\n try:\n form_id = form.data[form.prefix+'-id']\n except KeyError:\n form_id = None\n if form.is_valid() and form.has_changed():\n record = form.save(commit=False)\n if form_id:\n record.id = int(form_id)\n record.household = get_object_or_none(Household, household_id)\n record.save()\n active_ids.append(record.id)\n else:\n if form_id:\n active_ids.append(int(form_id))\n all_ids = list(model.objects.filter(household=household_id, **kwargs).values_list('id',flat=True))\n model.objects.filter(id__in=[ x for x in all_ids if x not in active_ids]).delete()\n return True\n return False\n\n\ndef save_form(form, household_id):\n \"\"\"add or update model using modelForm\"\"\"\n if form.is_valid():\n if form.has_changed():\n record = form.save(commit=False)\n try:\n if not form.prefix == None:\n form_id = form.data[form.prefix+'-id']\n else:\n form_id = None\n except KeyError:\n form_id = None\n if form_id:\n record.id = int(form_id)\n record.household = get_object_or_none(Household, household_id)\n record.save()\n return True\n return True\n return False\n\n\ndef get_object_or_none(model, household_id, **kwargs):\n \"\"\"get model object or return None\"\"\"\n try:\n if model == Household:\n model_object = model.objects.get(pk=household_id, **kwargs)\n else:\n model_object = model.objects.get(household=household_id, **kwargs)\n except model.DoesNotExist:\n model_object = None\n return model_object\n\n\ndef is_empty(field):\n if field is None or field == '':\n return True\n else:\n return False\n\ndef get_search_form():\n return HouseholdForm()","sub_path":"fas_questionnaire_site/fas_questionnaire/views/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":3480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"175976383","text":"import torch\nimport math\nfrom torch.optim import Optimizer\nfrom torch.optim.lr_scheduler import _LRScheduler\nimport numpy as np\nfrom torch.optim.optimizer import Optimizer\n\n\n# decoder_optim = torch.optim.Adam(model.decoder.parameters(), amsgrad=True)\n# decoder_optim = torch.optim.Adam(model.decoder.parameters())\n# decoder_optim = torch.optim.SGD(model.encoder.parameters(), lr=args.lr)\n\n\ndef get_optimizer(params, optimizer, lr):\n if optimizer == 'amsgrad': return torch.optim.Adam(params, lr=lr, amsgrad=True)\n elif optimizer == 'adam': return torch.optim.Adam(params, lr=lr)\n elif optimizer == 'adamw': return AdamW(params, lr=lr, weight_decay=1e-5)\n elif optimizer == 'sgd' or optimizer is None: return torch.optim.SGD(params, lr=lr)\n\n\ndef get_scheduler(args, optim, train_data=None):\n # if None, do the original annealing from lr = 20.\n if args.scheduler == 'cosine_anneal':\n scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optim, T_max=20000, eta_min=0, last_epoch=-1)\n elif args.scheduler == 'cosine_restart':\n scheduler = CosineLRWithRestarts(optim, args.batch_size, args.epochs, restart_period=5, t_mult=1.2)\n elif args.scheduler == 'lro':\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optim, mode='min')\n elif args.scheduler == 'multi_step':\n max_epochs = args.epochs * train_data.size(0) / args.bptt\n mstones = list(range(0, max_epochs, max_epochs / 10))\n scheduler = torch.optim.lr_scheduler.MultiStepLR(optim, milestones=mstones, gamma=0.1)\n return scheduler\n\n\n\"\"\"\ndef get_scheduler(optim, args, train_size = None):\n if args.scheduler == 'cosine_anneal':\n scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optim, T_max=20000, eta_min=0, last_epoch=-1)\n elif args.scheduler == 'lro':\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optim, mode='min')\n elif args.scheduler == 'multi_step':\n if train_size is None:\n ValueError(\"Need to provide train data as argument\")\n max_epochs = args.epochs * train_size / args.bptt\n mstones = list(range(0, max_epochs, max_epochs / 10))\n scheduler = torch.optim.lr_scheduler.MultiStepLR(optim, milestones=mstones, gamma=0.1)\n return scheduler\n\"\"\"\n\ndef sgd_update(pretrained, params, lr):\n if pretrained is not None:\n for name, p in params:\n if name is not 'encoder.weight':\n p.data.add_(-lr, p.grad.data)\n else:\n for p in params:\n p.data.add_(-lr, p.grad.data)\n\n\n\"\"\"Optimizer for Actor Critic Training\"\"\"\nclass Optim(object):\n def __init__(self, params, lr, is_pre,\n grad_clip, new_lr=0.0, weight_decay=0.):\n self.optimizer = torch.optim.Adam(params, lr=lr, betas=(\n 0.9, 0.98), eps=1e-09, weight_decay=weight_decay)\n self.grad_clip = grad_clip\n self.params = params\n if is_pre:\n self.step = self.pre_step\n else:\n assert new_lr != 0.0\n\n self.n_current_steps = 0\n self.new_lr = new_lr\n self.step = self.train_step\n\n def train_step(self):\n self.optimizer.step()\n\n self.n_current_steps += 1\n if self.n_current_steps == 1e6:\n self.update_learning_rate()\n\n def pre_step(self):\n self.optimizer.step()\n\n def zero_grad(self):\n self.optimizer.zero_grad()\n\n def clip_grad_norm(self):\n torch.nn.utils.clip_grad_norm(self.params, self.grad_clip)\n\n def update_learning_rate(self):\n for param_group in self.optimizer.param_groups:\n param_group['lr'] = self.new_lr\n\n\nclass Policy_optim(Optim):\n def __init__(self, params, lr, grad_clip, new_lr):\n super().__init__(params, lr, False, grad_clip, new_lr)\n\n def train_step(self, reward):\n for group in self.optimizer.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n\n p.grad = p.grad.mul(reward)\n\n self.optimizer.step()\n\n self.n_current_steps += 1\n if self.n_current_steps == 1e6:\n self.update_learning_rate()\n\n\n# Non-centered RMSprop update with shared statistics (without momentum)\nclass SharedRMSprop(torch.optim.RMSprop):\n def __init__(self, params, lr=1e-2, alpha=0.99, eps=1e-8, weight_decay=0):\n super(SharedRMSprop, self).__init__(params, lr=lr, alpha=alpha, eps=eps, weight_decay=weight_decay, momentum=0, centered=False)\n\n # State initialisation (must be done before step, else will not be shared between threads)\n for group in self.param_groups:\n for p in group['params']:\n state = self.state[p]\n state['step'] = p.data.new().resize_(1).zero_()\n state['square_avg'] = p.data.new().resize_as_(p.data).zero_()\n\n def share_memory(self):\n for group in self.param_groups:\n for p in group['params']:\n state = self.state[p]\n state['step'].share_memory_()\n state['square_avg'].share_memory_()\n\n def step(self, closure=None):\n loss = None\n if closure is not None:\n loss = closure()\n\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n grad = p.grad.data\n state = self.state[p]\n\n square_avg = state['square_avg']\n alpha = group['alpha']\n\n state['step'] += 1\n\n if group['weight_decay'] != 0:\n grad = grad.add(group['weight_decay'], p.data)\n\n # g = αg + (1 - α)Δθ^2\n square_avg.mul_(alpha).addcmul_(1 - alpha, grad, grad)\n # θ ← θ - ηΔθ/√(g + ε)\n avg = square_avg.sqrt().add_(group['eps'])\n p.data.addcdiv_(-group['lr'], grad, avg)\n\n return loss\n\n \nclass SharedAdam(torch.optim.Adam):\n \"\"\"Implements Adam algorithm with shared states.\n \"\"\"\n\n def __init__(self,\n params,\n lr=1e-3,\n betas=(0.9, 0.999),\n eps=1e-8,\n weight_decay=0):\n super(SharedAdam, self).__init__(params, lr, betas, eps, weight_decay)\n\n for group in self.param_groups:\n for p in group['params']:\n state = self.state[p]\n state['step'] = torch.zeros(1)\n state['exp_avg'] = p.data.new().resize_as_(p.data).zero_()\n state['exp_avg_sq'] = p.data.new().resize_as_(p.data).zero_()\n\n def share_memory(self):\n for group in self.param_groups:\n for p in group['params']:\n state = self.state[p]\n state['step'].share_memory_()\n state['exp_avg'].share_memory_()\n state['exp_avg_sq'].share_memory_()\n\n def step(self, closure=None):\n \"\"\"Performs a single optimization step.\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n \"\"\"\n loss = None\n if closure is not None:\n loss = closure()\n\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n grad = p.grad.data\n state = self.state[p]\n\n exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n beta1, beta2 = group['betas']\n\n state['step'] += 1\n\n if group['weight_decay'] != 0:\n grad = grad.add(group['weight_decay'], p.data)\n\n # Decay the first and second moment running average coefficient\n exp_avg.mul_(beta1).add_(1 - beta1, grad)\n exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n\n denom = exp_avg_sq.sqrt().add_(group['eps'])\n\n bias_correction1 = 1 - beta1 ** state['step'].item()\n bias_correction2 = 1 - beta2 ** state['step'].item()\n step_size = group['lr'] * math.sqrt(\n bias_correction2) / bias_correction1\n\n p.data.addcdiv_(-step_size, exp_avg, denom)\n\n return loss\n\n\n\n\n\n\n\n# ------------------ Adam With Warm Restarts ----------------------- #\nclass AdamW(Optimizer):\n \"\"\"Implements Adam algorithm.\n\n Arguments:\n params (iterable): iterable of parameters to optimize or dicts defining\n parameter groups\n lr (float, optional): learning rate (default: 1e-3)\n betas (Tuple[float, float], optional): coefficients used for computing\n running averages of gradient and its square (default: (0.9, 0.999))\n eps (float, optional): term added to the denominator to improve\n numerical stability (default: 1e-8)\n weight_decay (float, optional): weight decay (L2 penalty) (default: 0)\n amsgrad (boolean, optional): whether to use the AMSGrad variant of this\n algorithm from the paper `On the Convergence of Adam and Beyond`_\n\n \"\"\"\n\n def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8,\n weight_decay=0, amsgrad=False):\n if not 0.0 <= betas[0] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 0: {}\".format(betas[0]))\n if not 0.0 <= betas[1] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 1: {}\".format(betas[1]))\n defaults = dict(lr=lr, betas=betas, eps=eps,\n weight_decay=weight_decay, amsgrad=amsgrad)\n # super(AdamW, self).__init__(params, defaults)\n super().__init__(params, defaults)\n\n def step(self, closure=None):\n \"\"\"Performs a single optimization step.\n\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n \"\"\"\n loss = None\n if closure is not None:\n loss = closure()\n\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n grad = p.grad.data\n if grad.is_sparse:\n raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead')\n amsgrad = group['amsgrad']\n\n state = self.state[p]\n\n # State initialization\n if len(state) == 0:\n state['step'] = 0\n # Exponential moving average of gradient values\n state['exp_avg'] = torch.zeros_like(p.data)\n # Exponential moving average of squared gradient values\n state['exp_avg_sq'] = torch.zeros_like(p.data)\n if amsgrad:\n # Maintains max of all exp. moving avg. of sq. grad. values\n state['max_exp_avg_sq'] = torch.zeros_like(p.data)\n\n exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n if amsgrad:\n max_exp_avg_sq = state['max_exp_avg_sq']\n beta1, beta2 = group['betas']\n\n state['step'] += 1\n\n # Decay the first and second moment running average coefficient\n exp_avg.mul_(beta1).add_(1 - beta1, grad)\n exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n if amsgrad:\n # Maintains the maximum of all 2nd moment running avg. till now\n torch.max(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq)\n # Use the max. for normalizing running avg. of gradient\n denom = max_exp_avg_sq.sqrt().add_(group['eps'])\n else:\n denom = exp_avg_sq.sqrt().add_(group['eps'])\n\n bias_correction1 = 1 - beta1 ** state['step']\n bias_correction2 = 1 - beta2 ** state['step']\n step_size = group['lr'] * math.sqrt(bias_correction2) / bias_correction1\n\n if group['weight_decay'] != 0:\n decayed_weights = torch.mul(p.data, group['weight_decay'])\n p.data.addcdiv_(-step_size, exp_avg, denom)\n p.data.sub_(decayed_weights)\n else:\n p.data.addcdiv_(-step_size, exp_avg, denom)\n\n return loss\n\n\nclass CosineLRWithRestarts(_LRScheduler):\n \"\"\"Decays learning rate with cosine annealing, normalizes weight decay\n hyperparameter value, implements restarts.\n https://arxiv.org/abs/1711.05101\n\n Args:\n optimizer (Optimizer): Wrapped optimizer.\n batch_size: minibatch size\n epoch_size: training samples per epoch\n restart_period: epoch count in the first restart period\n t_mult: multiplication factor by which the next restart period will extend/shrink\n\n\n Example:\n >>> scheduler = CosineLRWithRestarts(optimizer, 32, 1024, restart_period=5, t_mult=1.2)\n >>> for epoch in range(100):\n >>> scheduler.step()\n >>> train(...)\n >>> ...\n >>> optimizer.zero_grad()\n >>> loss.backward()\n >>> optimizer.step()\n >>> scheduler.batch_step()\n >>> validate(...)\n \"\"\"\n\n def __init__(self, optimizer, batch_size, epoch_size, restart_period=100,\n t_mult=2, last_epoch=-1, eta_threshold=1000, verbose=False):\n if not isinstance(optimizer, Optimizer):\n raise TypeError('{} is not an Optimizer'.format(\n type(optimizer).__name__))\n self.optimizer = optimizer\n if last_epoch == -1:\n for group in optimizer.param_groups:\n group.setdefault('initial_lr', group['lr'])\n else:\n for i, group in enumerate(optimizer.param_groups):\n if 'initial_lr' not in group:\n raise KeyError(\"param 'initial_lr' is not specified \"\n \"in param_groups[{}] when resuming an\"\n \" optimizer\".format(i))\n self.base_lrs = list(map(lambda group: group['initial_lr'],\n optimizer.param_groups))\n\n self.last_epoch = last_epoch\n self.batch_size = batch_size\n self.iteration = 0\n self.epoch_size = epoch_size\n self.eta_threshold = eta_threshold\n self.t_mult = t_mult\n self.verbose = verbose\n self.base_weight_decays = list(map(lambda group: group['weight_decay'],\n optimizer.param_groups))\n self.restart_period = restart_period\n self.restarts = 0\n self.t_epoch = -1\n self.batch_increments = []\n self._set_batch_increment()\n\n def _schedule_eta(self):\n \"\"\"\n Threshold value could be adjusted to shrink eta_min and eta_max values.\n \"\"\"\n eta_min = 0\n eta_max = 1\n if self.restarts <= self.eta_threshold:\n return eta_min, eta_max\n else:\n d = self.restarts - self.eta_threshold\n k = d * 0.09\n return (eta_min + k, eta_max - k)\n\n def get_lr(self, t_cur):\n eta_min, eta_max = self._schedule_eta()\n\n eta_t = (eta_min + 0.5 * (eta_max - eta_min)\n * (1. + math.cos(math.pi *\n (t_cur / self.restart_period))))\n\n weight_decay_norm_multi = math.sqrt(self.batch_size /\n (self.epoch_size *\n self.restart_period))\n lrs = [base_lr * eta_t for base_lr in self.base_lrs]\n weight_decays = [base_weight_decay * eta_t * weight_decay_norm_multi\n for base_weight_decay in self.base_weight_decays]\n\n if self.t_epoch % self.restart_period < self.t_epoch:\n if self.verbose:\n print(\"Restart at epoch {}\".format(self.last_epoch))\n self.restart_period *= self.t_mult\n self.restarts += 1\n self.t_epoch = 0\n\n return zip(lrs, weight_decays)\n\n def _set_batch_increment(self):\n d, r = divmod(self.epoch_size, self.batch_size)\n batches_in_epoch = d + 2 if r > 0 else d + 1\n self.iteration = 0\n self.batch_increments = list(np.linspace(0, 1, batches_in_epoch))\n\n def step(self):\n self.last_epoch += 1\n self.t_epoch += 1\n self._set_batch_increment()\n self.batch_step()\n\n def batch_step(self):\n try:\n t_cur = self.t_epoch + self.batch_increments[self.iteration]\n self.iteration += 1\n except (IndexError):\n raise RuntimeError(\"Epoch size and batch size used in the \"\n \"training loop and while initializing \"\n \"scheduler should be the same.\")\n\n for param_group, (lr, weight_decay) in zip(self.optimizer.param_groups,\n self.get_lr(t_cur)):\n param_group['lr'] = lr\n param_group['weight_decay'] = weight_decay\n\n\n'''A wrapper class for optimizer '''\n\n\nclass ScheduledOptim():\n '''A simple wrapper class for learning rate scheduling'''\n\n def __init__(self, optimizer, d_model, n_warmup_steps):\n self._optimizer = optimizer\n self.n_warmup_steps = n_warmup_steps\n self.n_current_steps = 0\n self.init_lr = np.power(d_model, -0.5)\n\n def step_and_update_lr(self):\n \"Step with the inner optimizer\"\n self._update_learning_rate()\n self._optimizer.step()\n\n def zero_grad(self):\n \"Zero out the gradients by the inner optimizer\"\n self._optimizer.zero_grad()\n\n def _get_lr_scale(self):\n return np.min([\n np.power(self.n_current_steps, -0.5),\n np.power(self.n_warmup_steps, -1.5) * self.n_current_steps])\n\n def _update_learning_rate(self):\n ''' Learning rate scheduling per step '''\n\n self.n_current_steps += 1\n lr = self.init_lr * self._get_lr_scale()\n\n for param_group in self._optimizer.param_groups:\n param_group['lr'] = lr","sub_path":"models/optimizer.py","file_name":"optimizer.py","file_ext":"py","file_size_in_byte":18118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"561417631","text":"from django.shortcuts import get_object_or_404, render, redirect\r\nfrom django.http import HttpResponse, JsonResponse\r\nimport os\r\nimport datetime\r\nimport json\r\nfrom rest_framework import status\r\n\r\nfrom tools._models.MasterContacts import *\r\nfrom tools._models.Vendors import (VendorContact, )\r\nfrom tools._models.Contact_Customer import *\r\nfrom userprofile.models import (Profile, Broker, )\r\nfrom tools._forms.MasterContactForms import *\r\nfrom tools.serializers import *\r\n\r\ndef get_New_Contact_Number():\r\n last_object = MasterContact.objects.all().order_by('id').last()\r\n if not last_object:\r\n return 10001\r\n return last_object.Contact_Number + 1\r\n\r\ndef get_New_Vendor_Contact_Number():\r\n last_object = VendorContact.objects.all().order_by('id').last()\r\n if not last_object:\r\n return 10001\r\n return last_object.Vendor_Contact_Number + 1\r\n\r\ndef index(request):\r\n if request.user.is_superuser != True:\r\n try:\r\n profile = Profile.objects.get(user_id=request.user.id)\r\n items = MasterContact.objects.exclude(Status=Status.Inactive.value).filter(Broker_id=profile.Broker_id)\r\n except Exception:\r\n return render(request, 'base_not_found_partial.html')\r\n else:\r\n items = MasterContact.objects.exclude(Status=Status.Inactive.value)\r\n\r\n return render(request, \"tools/contact/index_partial.html\", \r\n {\r\n 'items': items,\r\n })\r\n\r\ndef add_contact(request):\r\n if request.user.is_superuser == True:\r\n return redirect('/tools/contact/')\r\n\r\n try:\r\n profile = Profile.objects.get(user_id=request.user.id)\r\n except Exception:\r\n return render(request, 'base_not_found_partial.html')\r\n\r\n if request.method == \"POST\": \r\n mform = MasterContactForm(request.POST)\r\n if mform.is_valid():\r\n new_model = mform.save(commit=False) \r\n new_model.Contact_Number = get_New_Contact_Number()\r\n new_model.Status = Status.Active.value\r\n new_model.User_id = request.user.id\r\n new_model.Broker_id = profile.Broker_id\r\n new_model.save()\r\n company = request.POST.getlist('Company')\r\n #company_data = json.loads(company)\r\n list_contact_models = []\r\n for item in company:\r\n new_contact = Contact_Customer()\r\n new_contact.Customer_id = int(item)\r\n new_contact.MasterContact_id = new_model.id\r\n list_contact_models.append(new_contact)\r\n if len(list_contact_models) > 0:\r\n # Call bulk_create to create records in a single call\r\n Contact_Customer.objects.bulk_create(list_contact_models)\r\n return redirect('/tools/contact/')\r\n else:\r\n print(mform.errors)\r\n else:\r\n mform = MasterContactForm(Broker_id=profile.Broker_id,instance=MasterContact()) \r\n\r\n return render(request, 'tools/contact/change_contact_partial.html', {\r\n 'form': mform,\r\n 'form_name': mform.__class__.__name__,\r\n 'is_change': False,\r\n })\r\n\r\ndef edit_contact(request, id): \r\n if request.user.is_superuser == True:\r\n return redirect('/tools/contact/')\r\n try:\r\n profile = Profile.objects.get(user_id=request.user.id)\r\n except Exception:\r\n return render(request, 'base_not_found_partial.html')\r\n try:\r\n if request.method == \"POST\": \r\n obj_model = MasterContact.objects.get(id=id)\r\n fac_ID = obj_model.Contact_Number\r\n status = obj_model.Status\r\n user_id = obj_model.User_id\r\n broker_id = obj_model.Broker_id\r\n mform = MasterContactForm(request.POST or None, instance=obj_model)\r\n if mform.is_valid():\r\n obj_model.Contact_Number = fac_ID\r\n obj_model.Status = status\r\n obj_model.User_id = user_id\r\n obj_model.Broker_id = broker_id\r\n obj_model.save()\r\n recommendations = Contact_Customer.objects.filter(MasterContact_id=obj_model.id)\r\n if recommendations.exists():\r\n recommendations.delete()\r\n company = request.POST.getlist('Company')\r\n #company_data = json.loads(company)\r\n list_contact_models = []\r\n for item in company:\r\n new_contact = Contact_Customer()\r\n new_contact.Customer_id = int(item)\r\n new_contact.MasterContact_id = obj_model.id\r\n list_contact_models.append(new_contact)\r\n if len(list_contact_models) > 0:\r\n # Call bulk_create to create records in a single call\r\n Contact_Customer.objects.bulk_create(list_contact_models)\r\n return redirect('/tools/contact/')\r\n else:\r\n print(mform.errors)\r\n else:\r\n obj_model = MasterContact.objects.get(id=id)\r\n mform = MasterContactForm(Broker_id=profile.Broker_id,instance=obj_model)\r\n mylist = []\r\n contact_cust_list = Contact_Customer.objects.filter(MasterContact_id = obj_model.id)\r\n for item in contact_cust_list:\r\n mylist.append(item.Customer.id)\r\n mform.fields['Company'].initial = mylist\r\n print(mylist)\r\n except Exception:\r\n return render(request, 'base_not_found_partial.html')\r\n\r\n return render(request, 'tools/contact/change_contact_partial.html', {\r\n 'form': mform,\r\n 'form_name': mform.__class__.__name__,\r\n 'is_change': True,\r\n })\r\n\r\ndef delete_contact(request):\r\n if request.user.is_superuser == True:\r\n return redirect('/tools/contact/')\r\n\r\n try:\r\n id = int(request.GET['id'])\r\n item = MasterContact.objects.get(id=id)\r\n item.Status = Status.Inactive.value\r\n item.save()\r\n except Exception:\r\n return render(request, 'base_not_found_partial.html')\r\n\r\n json = \"{\\\"success\\\": true, \\\"id\\\":\\\"\"+ str(id) +\"\\\"}\"\r\n return HttpResponse(json)\r\n\r\ndef add_contact_with_json(request):\r\n if request.method == \"POST\": \r\n try:\r\n profile = Profile.objects.get(user_id=request.user.id)\r\n \r\n mform = MasterContactForm(request.POST)\r\n if mform.is_valid():\r\n new_model = mform.save(commit=False) \r\n new_model.Contact_Number = get_New_Contact_Number()\r\n new_model.Status = Status.Active.value\r\n new_model.User_id = request.user.id\r\n new_model.Broker_id = profile.Broker_id\r\n new_model.save()\r\n company = request.POST.getlist('Company')\r\n print(company)\r\n list_contact_models = []\r\n for item in company:\r\n new_contact = Contact_Customer()\r\n new_contact.Customer_id = int(item)\r\n new_contact.MasterContact_id = new_model.id\r\n list_contact_models.append(new_contact)\r\n if len(list_contact_models) > 0:\r\n # Call bulk_create to create records in a single call\r\n Contact_Customer.objects.bulk_create(list_contact_models)\r\n # Return json result\r\n vendor_number = get_New_Vendor_Contact_Number()\r\n json_item = MasterContactSerializer(new_model)\r\n obj_json = {\r\n \"success\": True,\r\n \"Vendor_Number\": vendor_number,\r\n \"Master_Contact\": json_item.data\r\n }\r\n return JsonResponse(obj_json, status=status.HTTP_201_CREATED)\r\n except Exception as error:\r\n print('Caught this error: ' + repr(error))\r\n pass \r\n\r\n obj_json = {\r\n \"success\": False,\r\n \"Vendor_Number\": \"\",\r\n \"Master_Contact\": None\r\n }\r\n return JsonResponse(obj_json, status=status.HTTP_201_CREATED)\r\n\r\ndef get_model_using_current_contact(request):\r\n obj_id=request.GET.get('id')\r\n item = MasterContact.objects.get(id=obj_id)\r\n\r\n facilitycontact_set = item.facilitycontact_set.all()\r\n vendorcontact_set = item.vendorcontact_set.all() \r\n gen_mastercontact = item.gen_mastercontact.all()\r\n certification_set = item.certification_set.all()\r\n Order_Order_Contact = item.Order_Order_Contact.all()\r\n Order_Billing_Contact = item.Order_Billing_Contact.all()\r\n\r\n\r\n return render(request, 'tools/contact/list_of_item_using_contact.html', \r\n {\r\n 'item': item,\r\n 'facilitycontact_set': facilitycontact_set,\r\n 'vendorcontact_set': vendorcontact_set,\r\n 'gen_mastercontact': gen_mastercontact,\r\n 'certification_set': certification_set,\r\n 'Order_Order_Contact': Order_Order_Contact,\r\n 'Order_Billing_Contact': Order_Billing_Contact,\r\n })\r\n","sub_path":"tools/_views/contact_views.py","file_name":"contact_views.py","file_ext":"py","file_size_in_byte":9194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"622543277","text":"import spacy\nfrom spacy.matcher import PhraseMatcher\nfrom TweetBase import TweetBase\nimport HardQuery\nfrom spacy.symbols import *\nimport re\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom random import randint\n\nspacyNLP = spacy.load(\"en_core_web_sm\")\nsynonyms = {\"television\":[\"tv\"],\"picture\":[\"motion picture\",\"movie\",\"film\",\"feature film\"],\"film\":[\"movie\",\"feature film\"],\"movie\":[\"motion picture\",\"film\"]}\n\nclass AwardParser(object):\n def __init__(self,year,filepath = None):\n if filepath == None:\n self.datab = TweetBase(\"gg\" + str(year) + \".json\",year)\n else:\n self.datab = TweetBase(filepath,year)\n print(\"Starting cull\",year)\n self.datab.cullTwitterPunctuation()\n #self.awardFilter = self.datab.anyStringList([\"award for Best \"])\n self.actualAwards = []\n self.year = year\n self.movienames = []\n self.winners = {}\n self.HardQueries = {}\n\n def PopulateHardQueries(self):\n if len(self.HardQueries) == 0:\n self.HardQueries = self.datab.PopulateHardQueries() \n \n def HostFinder(self):\n firstcull = self.datab.anyStringList([\" is hosting\"])\n secondcull = self.datab.anyStringList([\" are hosting\"])\n \n multihost = len(secondcull) > len(firstcull)\n\n if multihost: firstcull = secondcull\n\n docs = []\n hostVote = {}\n\n for tweet in firstcull:\n docs.append(spacyNLP(tweet))\n\n for doc in docs:\n for ent in doc.ents:\n if ent.label_ == \"PERSON\":\n if len(ent.text.split(\" \")) == 1:\n continue\n if ent.lower_ in hostVote:\n hostVote[ent.lower_] += 1\n else:\n hostVote[ent.lower_] = 1\n \n if multihost:\n hVs = sorted(hostVote,key = hostVote.get)\n return [hVs[-1],hVs[-2]]\n\n return max(hostVote,key=hostVote.get)\n\n def WinnerFinder(self, award, nomType):\n self.PopulateHardQueries()\n\n firstcull = list(filter(lambda tweet: any(kw in tweet for kw in [\"wins\",\"goes to\",award + \"-\"]),self.HardQueries[award]))\n docs = []\n winVote = {}\n if nomType == \"PERSON\":\n for tweet in firstcull:\n docs.append(spacyNLP(tweet))\n \n for doc in docs:\n for ent in doc.ents:\n if ent.label_ == \"PERSON\":\n if ent.lower_ in winVote:\n winVote[ent.lower_] += 1\n else:\n winVote[ent.lower_] = 1\n else:\n for tweet in firstcull:\n titlefind = list(re.finditer(r\"([\\\"])(?:(?=(\\\\?))\\2.)*?\\1\", tweet))\n if len(titlefind) > 0:\n if titlefind[0][0] in winVote:\n winVote[titlefind[0][0]] += 1\n else:\n winVote[titlefind[0][0]] = 1 \n\n\n \n if len(winVote) == 0:\n return \"\"\n return max(winVote, key=winVote.get)\n\n def acceptActualAwards(self, actualList):\n self.actualAwards = actualList\n\n def FindAllWinners(self):\n print(\"finding winners\",self.year)\n allWinners = {}\n self.PopulateHardQueries()\n \n for aA in self.actualAwards:\n nomType = \"MEDIA\"\n if \"act\" in aA or \"direct\" in aA or \"screenp\" in aA or \"award\" in aA:\n nomType = \"PERSON\"\n \n if nomType == \"PERSON\":\n win1 = self.TheyWonAwardParser(aA,nomType)\n if not win1 or win1 == \"who\":\n win1 = self.WinnerFinder(aA,nomType)\n if win1 == '':\n win1 = self.CongratulationsParser(aA,nomType)\n if win1 == None or win1 == False:\n win1 = ''\n allWinners[aA] = win1\n else:\n win1 = self.WinnerFinder(aA,nomType)\n if win1 == '':\n win1 = self.TheyWonAwardParser(aA,nomType)\n if win1 == False:\n win1 = self.CongratulationsParser(aA,nomType)\n if win1 == None:\n win1 = ''\n win1 = win1.replace(\"\\\"\",\"\").lower()\n allWinners[aA] = win1\n\n self.winners = allWinners\n return allWinners\n\n def FindAllNominees(self):\n print(\"finding nominees\",self.year)\n allNominees = {}\n for aA in self.actualAwards:\n nomType = \"MEDIA\"\n \n if \"act\" in aA or \"direct\" in aA or \"screenp\" in aA or \"cec\" in aA:\n nomType = \"PERSON\"\n \n nN = self.newNominees(aA)\n if nN != []:\n allNominees[aA] = nN\n continue\n\n mergedNominees = self.NominatedForParser(aA,nomType)\n if aA in self.winners and self.winners[aA] not in [False,None,'']:\n mergedNominees.update(self.BeatParser([self.winners[aA]],nomType))\n\n \n if len(mergedNominees) > 9:\n allNominees[aA] = sorted(mergedNominees,key=mergedNominees.get)[-9:]\n else:\n allNominees[aA] = list(mergedNominees)\n \n return allNominees\n \n\n \"\"\"def NomineeFinder(self, award, nomType):\n firstcull = self.datab.filterStringList([award, \"\\\"\"])\n docs = []\n nomVote = {}\n\n for tweet in firstcull:\n if nomType == \"PERSON\":\n doc = spacyNLP(tweet)\n for ent in doc.ents:\n if ent.label_ == \"PERSON\":\n print(ent)\n if ent.lower_ in nomVote:\n nomVote[ent.lower_] += 1\n else:\n nomVote[ent.lower_] = 1\n elif nomType == \"TITLE\":\n titlefind = re.finditer(r\"([\\\"])(?:(?=(\\\\?))\\2.)*?\\1\", tweet)\n\n for match in titlefind:\n print(match[0])\n tfind = match[0].replace(\"\\\"\",\"\").replace(\"\\'\",\"\").lower()\n if tfind in nomVote:\n nomVote[tfind] += 1\n else:\n nomVote[tfind] = 1\"\"\"\n\n \"\"\"def PresenterFinder(self, award, winner):\n winTime = self.datab.earliestMention([award,winner,\"won\"])\n if winTime == None:\n return []\n if self.year == 2020:\n winnerTime = datetime.strptime(winTime,\"%Y-%m-%dT%H:%M:%S\")\n End = winnerTime + timedelta(minutes=5)\n Start = winnerTime - timedelta(minutes=5)\n tenMinuteList = self.datab.timeFrameFilter(str(Start).replace(\" \",\"T\"),str(End).replace(\" \",\"T\"))\n else:\n End = winTime + 300000\n Start = winTime - 300000\n tenMinuteList = self.datab.timeFrameFilter(Start,End)\n \n\n kwlist = [\" announc\",\" present\",\" on stage\",\" read\"]\n PresenterFilter = filter(lambda tweet: any(kw in tweet for kw in kwlist), tenMinuteList)\n pVote = {}\n\n for presentertweet in list(PresenterFilter):\n doc = spacyNLP(presentertweet)\n for ent in doc.ents:\n if ent.label_ == \"PERSON\" and \"olden\" not in ent.text and ent.lower_ not in winner:\n if ent.lower_ in pVote:\n pVote[ent.lower_]+=1\n else:\n pVote[ent.lower_]=1\n \n a = sorted(pVote,key=pVote.get)\n\n if len(pVote) == 0:\n return []\n elif len(pVote) == 1 or pVote[a[-2]] < pVote[a[-1]]/2:\n return [a[-1]]\n else:\n return [a[-1],a[-2]]\"\"\"\n\n \"\"\"\"def NameVariantFinder(self,person):\n variants = [person]\n personarray = person.split(\" \")\n variants.append(personarray[0])\n variants.append(personarray[1])\n variants.append(personarray[0] + personarray[1])\n\n return variants\"\"\"\n\n def TheyWonAwardParser(self,filters, nomType):\n filterb = [\"wins\",\"won\"]\n if nomType == \"MEDIA\":\n filterb.append(\"\\\"\")\n firstcull = list(filter(lambda tweet: all(kw in tweet for kw in filterb),self.HardQueries[filters]))\n winVote = {}\n docs = []\n\n for tweet in firstcull:\n mentionedMovies = list(re.finditer(r\"([\\\"'])(?:(?=(\\\\?))\\2.)*?\\1\", tweet))\n for mMovie in mentionedMovies:\n if len(mMovie[0]) > 30:\n mentionedMovies.remove(mMovie)\n \n if len(mentionedMovies) == 0:\n continue\n\n subj = \"\"\n pred = \"\"\n ignore = False\n doc = spacyNLP(tweet)\n\n for word in doc:\n if word.text == \".\":\n break\n if nomType == \"MEDIA\" and word.text == \"\\\"\":\n subj = mentionedMovies[0][0]\n if word.dep_ in [\"nsubj\",\"nsubjpass\"] and word.head.text in [\"wins\",\"won\"] and nomType == \"PERSON\":\n if word.ent_iob_ == \"I\":\n subj = next(x for x in doc.ents if word.text in x.text).lower_\n else:\n subj = word.text.lower()\n elif word.dep_ == \"dobj\" and word.head.text in [\"wins\",\"won\"]:\n pred = word.text\n\n \n if not ignore and subj != \"\" and pred != \"\":\n if subj in winVote:\n winVote[subj]+=1\n else:\n winVote[subj]=1\n \n if len(winVote) == 0:\n return False\n\n return max(winVote,key=winVote.get)\n\n def CongratulationsParser(self, filters, nomType):\n filterb = [[\"congratulations\",\"congrats\"],[\"for winning best\",\"for winning the award\",\"for best\"]]\n if nomType == \"MEDIA\":\n filterb.append(\"\\\"\")\n firstcull = list(filter(lambda tweet: all(kw in tweet for kw in filterb[0]) and all(kw in tweet for kw in filterb[1]),self.HardQueries[filters]))\n winVote = {}\n \n\n for tweet in firstcull:\n mentionedMovies = list(re.finditer(r\"([\\\"'])(?:(?=(\\\\?))\\2.)*?\\1\", tweet))\n if mentionedMovies == [] and nomType == \"MEDIA\":\n continue\n obj = \"\"\n doc = spacyNLP(tweet)\n\n for word in doc:\n if word.text == \".\":\n break\n if nomType==\"MEDIA\" and word.text==\"\\\"\":\n obj = mentionedMovies[0][0]\n break\n if word.text in [\"congratulations\", \"congrats\", \"Congratulations\", \"Congrats\"] and nomType==\"PERSON\":\n idx = word.i\n obj = next((ent for ent in doc.ents if ent.start > idx and ent.label_ == \"PERSON\"),False)\n if obj:\n obj = obj.text\n break\n \n \"\"\"if obj:\n print(tweet)\n print(obj)\"\"\"\n if obj != \"\" and obj in winVote:\n winVote[obj]+=1\n else:\n winVote[obj]=1\n\n if len(winVote) == 0:\n return None\n \n return max(winVote, key=winVote.get)\n\n \"\"\"def AwardGroupParse(self,award):\n award1 = award.lower()\n for filtere in [\".\",\", i\",\",\",\" a \",\" an \", \" or \",\"!\",\":\",\";\",\"\\'\",\"\\\"\",\"\\n\"]:\n award1 = award1.replace(filtere,\" \")\n for filterd in [\" in \", \" by \", \" - \"]:\n award1 = award1.replace(filterd,\"|\")\n\n award1.replace(\"tv\",\"television\")\n\n split1 = award1.split(\"|\")\n split2 = []\n for segment in split1:\n split2.append(segment.split(\" \"))\n \n return split2\"\"\"\n\n def NominatedForParser(self,award,nomType):\n self.PopulateHardQueries()\n\n firstcull = self.HardQueries[award]\n if nomType == \"MEDIA\":\n firstcull = list(filter(lambda tweet: all(kw in tweet for kw in [\"\\\"\",\" nomin\"]),firstcull))\n else:\n firstcull = list(filter(lambda tweet: all(kw in tweet for kw in [\" nomin\"]),firstcull))\n nominees = {}\n if nomType == \"MEDIA\":\n for tweet in firstcull:\n mentionedMovies = list(re.finditer(r\"([\\\"'])(?:(?=(\\\\?))\\2.)*?\\1\", tweet))\n for mMovie in mentionedMovies:\n if len(mMovie[0]) > 30:\n continue\n if mMovie[0] not in self.movienames:\n self.movienames.append(mMovie[0])\n a = mMovie[0].lower().replace(\"\\\"\",\"\").replace(\"\\'\",\"\")\n if a in nominees:\n nominees[a]+=1\n else:\n nominees[a]=1\n\n else:\n for tweet in firstcull:\n doc = spacyNLP(tweet)\n for ent in doc.ents:\n if ent.label_ == \"PERSON\" and \"olden\" not in ent.lower_:\n if ent.lower_ in nominees:\n nominees[ent.lower_]+=1\n else:\n nominees[ent.lower_] = 1\n\n return nominees\n \n def BeatParser(self,winner,nomtype):\n filters = [winner,[\" beat\",\" rob\",\" stole\",\" steal\"],(\" de \",\" en \",\" y \",\" lo \", \" la \", \" el \", \" los \")]\n firstcull = self.datab.ANDorFILTER(filters,True)\n \n nominees = {}\n for tweet in firstcull:\n doc = spacyNLP(tweet)\n if nomtype == \"PERSON\":\n for ent in doc.ents:\n if ent.label_ == \"PERSON\" and ent.lower_ not in winner and \"olden\" not in ent.lower_:\n if ent.lower_ in nominees:\n nominees[ent.lower_]+=1\n else:\n nominees[ent.lower_]=1\n else:\n for word in doc:\n if word.dep_ == \"dobj\" and word.head.text in [\"beat\",\"beats\",\"rob\",\"robbed\",\"stole\",\"steal\",\"steals\"] and word.text[0].isupper():\n a = self.MovieNameFinder(word.text).replace(\"\\\"\",\"\").replace(\"\\'\",\"\").lower()\n if a in nominees:\n nominees[a]+=1\n else:\n nominees[a]=1\n \n return nominees\n\n def MovieNameFinder(self, word):\n for mName in self.movienames:\n if word in mName:\n return mName\n \n filters = [[\"\\\"\"],word]\n firstcull = self.datab.ANDorFILTER(filters)\n\n vote = {}\n for tweet in firstcull:\n mentionedMovies = list(re.finditer(r\"([\\\"'])(?:(?=(\\\\?))\\2.)*?\\1\", tweet))\n for mMovie in mentionedMovies:\n if word in mMovie[0] and len(mMovie[0]) < 30:\n self.movienames.append(mMovie[0])\n if mMovie[0] in vote:\n vote[mMovie[0]]+=1\n else:\n vote[mMovie[0]] = 1\n\n if vote != {}:\n return max(vote,key=vote.get)\n return word\n \n def firstNameFinder(self, lastName):\n filters = [lastName]\n firstcull = self.datab.ANDorFILTER(filters,True)\n\n for tweet in firstcull:\n doc = spacyNLP(tweet)\n for ent in doc.ents:\n if ent.label_ == \"PERSON\" and lastName in ent.text and lastName!=ent.text:\n return ent.text\n\n def AllPresentersFinder(self):\n print(\"finding presenters\",self.year)\n presenters = {}\n for award in self.actualAwards:\n presenters[award] = self.PresenterFinder2(award)\n \n return presenters\n \n\n def getAllPresenters(self):\n stopWords = ('hate', 'love','hope','good','bad',' en ',' los ',' de ',' la ', ' un ', 'drink', 'should', 'could', 'would', ' i ', \n ' im ', ' i\\'m ', '?', '!!')\n filters = [['present', 'announc'],stopWords]\n \n firstcull = self.datab.ANDorFILTER(filters,True)\n\n presenters = {}\n fullName = re.compile(r\"^([A-Z][a-z]+ (?:[A-Z][a-z]+)*)$\")\n\n for tweet in firstcull:\n doc = spacyNLP(tweet)\n\n for ent in doc.ents:\n if ent.label_ == \"PERSON\" and fullName.match(ent.text) and ent.text in presenters:\n presenters[ent.text]+=1\n elif ent.label_ == \"PERSON\" and fullName.match(ent.text) and not ent.text in presenters and not \"olden\" in ent.text and not \"present\" in ent.lower_ and not \"win\" in ent.lower_:\n presenters[ent.text]=1\n\n '''\n finalPresenters = {}\n self.PopulateHardQueries()\n \n for name in presenters:\n for award, awardTweets in self.HardQueries.items():\n for tweet in awardTweets:\n if \"present\" in tweet and \"win\" not in tweet:\n if any(name in tweet.lower() for name in name.split()) and award in finalPresenters:\n if any(name in finalPresenters[award] for name in name.split()):\n continue\n else:\n finalPresenters[award].append(name)\n break\n elif any(name in tweet.lower() for name in name.split()) and not award in finalPresenters:\n finalPresenters[award] = [name]\n '''\n finalPresenters = {}\n self.PopulateHardQueries()\n presenters = set(presenters)\n culledPresenters = set()\n\n for presenter in presenters:\n if not 'win' in presenter.lower() and not 'olden' in presenter.lower() and not 'best' in presenter.lower() and not presenter.lower() in self.winners.values():\n culledPresenters.add(presenter)\n\n for award, awardTweets in self.HardQueries.items():\n for tweet in awardTweets:\n for name in culledPresenters:\n if name in tweet and 'present' in tweet.lower() and not 'win' in tweet.lower() and award in finalPresenters:\n if not name.lower() in finalPresenters[award]:\n finalPresenters[award].append(name.lower())\n elif name in tweet and 'present' in tweet.lower() and not 'win' in tweet.lower() and not award in finalPresenters:\n finalPresenters[award] = [name.lower()]\n\n for award in self.HardQueries:\n if not award in finalPresenters:\n finalPresenters[award] = self.PresenterFinder2(award)\n\n return finalPresenters\n\n def PresenterFinder2(self, award):\n self.PopulateHardQueries()\n firstcull = self.HardQueries[award]\n\n firstcull = list(filter(lambda tweet: any(kw in tweet for kw in [\"present\",\"announc\"]),firstcull))\n \n docs = []\n hostVote = {}\n\n for tweet in firstcull:\n docs.append(spacyNLP(tweet))\n\n for doc in docs:\n for ent in doc.ents:\n if ent.label_ == \"PERSON\" and \"olden\" not in ent.text:\n if ent.lower_ in hostVote:\n hostVote[ent.lower_] += 1\n else:\n hostVote[ent.lower_] = 1\n\n hVs = sorted(hostVote,key = hostVote.get)\n\n if len(hVs) < 5:\n return hVs\n if len(hVs) == 0:\n return []\n return hVs[-5:]\n\n def DrinkingGames(self):\n firstcull = self.datab.ANDorFILTER([[\"drinking game\", \"drink!\", \"take a drink\", \"drink every\", \"drink when\"]])\n firstcull = list(set(firstcull))\n\n games = []\n\n for tweet in firstcull:\n ltweet = tweet.lower().replace(\"\\n\",\" | \")\n if any(kw in tweet for kw in [\"|\",\"rules\",\" \"]):\n continue\n if \"drinking game:\" in ltweet:\n games.append(tweet[ltweet.index(\"game:\")+5:])\n continue\n for st in [\"when \",\" if \",\" every \"]:\n if st in ltweet:\n games.append(tweet[ltweet.index(st):])\n continue\n rns = []\n i = 0\n while i < 10:\n rand = randint(0,len(games)-1)\n if games[rand] not in rns:\n rns.append(games[rand])\n i+=1\n\n return rns\n\n \"\"\"def awardparseOpen(self):\n awards = []\n\n firstcull = self.datab.ANDorFILTER([re.compile(\"^Best [A-Z]\"),re.compile(\" \\n$\"),\"\\n\\n\"])\n if \"-\" in firstcull[0]:\n return firstcull\n for string in firstcull:\n awards.append(string[0:string.index(\"\\n\\n\")])\n \n firstcull = self.datab.ANDorFILTER([re.compile(\"^Best [A-Z]\"),re.compile(\"[a-z] $\"),[\" : \"]])\n for string in firstcull:\n awards.append(string[0:string.index(\": \")])\n secondcull = self.datab.ANDorFILTER([re.compile(\"[a-z] - Best [A-Z]\"),re.compile(\"[a-z][a-z]$\")])\n for string in secondcull:\n awards.append(string[string.index(\" - \"):]) \n\n return awards\n\n def awardParseRegex2(self):\n #regexParse = self.datab.getRegexFullMatchOnly(re.compile(\"Best(([\\s][A-Z][a-z,\\-]{2,})| in a| in an| by an| or| \\-| for)+([\\s][A-Z][a-z]{2,})\"))\n regexParse = self.datab.getRegexFullMatchOnly(re.compile(\"^BEST [A-Z\\-, ]+\"))\n awardDict = {}\n\n stopwords = [\"joke\",\"carpet\",\"dress\",\"olden\",\"look\",\"moment\",\"award\",\"the\",\"--\",\"hosts\",\"ever\",\"speech\"]\n for item in regexParse:\n add = True\n if any(kw in item.lower() for kw in stopwords) or len(item.split(\" \")) < 4:\n add = False\n\n dash = item.split(\" - \")\n if len(dash) > 2:\n item = \" - \".join([dash[0],dash[1]])\n if len(dash) == 2 and len(dash[1].split(\" \")) > 3:\n add = False\n \n if any(kw in item[-5:] for kw in [\",\",\"-\"]):\n add = False\n\n if add:\n if item in awardDict:\n awardDict[item]+=1\n else:\n awardDict[item]=1\n\n print(list(awardDict))\n\n def awardParseRegex3(self):\n #regexParse = self.datab.getRegexFullMatchOnly(re.compile(\"\\n\\nBest .*(\\n\\n|\\nW)\"))\n regexParse = self.datab.getRegexFullMatchOnly(re.compile(\"(^|\\n)Best( [A-Z][a-z]+| -| [a-z][a-z]?)+ [A-Z][a-z]+\"))\n\n awardDict = {}\n\n stopwords = [\"joke\",\"carpet\",\"dress\",\"olden\",\"look\",\"moment\",\"award\",\"the\",\"--\",\"hosts\",\"ever\",\"speech\",\"win\", \"is\",\"should\"]\n for item in regexParse:\n add = True\n if any(kw in item.lower() for kw in stopwords) or len(item.split(\" \")) < 4:\n add = False\n\n dash = item.split(\" - \")\n if len(dash) > 2:\n item = \" - \".join([dash[0],dash[1]])\n if len(dash) == 2 and len(dash[1].split(\" \")) > 3:\n add = False\n \n \n if any(kw in item[-5:] for kw in [\",\",\"-\"]):\n add = False\n\n if add:\n if item in awardDict:\n awardDict[item]+=1\n else:\n awardDict[item]=1\n\n print(list(awardDict))\"\"\"\n\n def awardParseRegexFinal(self):\n regexParse = self.datab.getRegexFullMatchOnly(re.compile(\"(- |^|:|: |,|, |'|\\n)(BEST|best|Best) [A-Za-z, \\-]+(: | : |\\n|$|[\\s]*\\n|[\\s]*$|')\"))\n awardDict = {}\n \n stopwords = HardQuery.stopwords\n for item in regexParse:\n add = True\n if any(kw in item.lower() for kw in stopwords):\n add = False\n\n dash = item.split(\" - \")\n if len(dash) > 2:\n item = \" - \".join([dash[0],dash[1]])\n if len(dash) == 2 and len(dash[1].split(\" \")) > 3:\n add = False\n \n \n if any(kw in item[-5:] for kw in [\",\",\"-\",\"or\"]):\n add = False\n item = item.lower().replace(\"tv\",\"television\").replace(\":\",\"\").replace(\"\\n\",\"\").replace(\"'\",\"\").replace(\",\",\"\")\n item = item[item.index(\"best\"):]\n\n while item[-1] == ' ':\n item = item[:-1]\n\n if len(item.split(\" \")) < 4:\n add = False\n \n if add:\n if item in awardDict:\n awardDict[item]+=1\n else:\n awardDict[item]=1\n \n #print(sorted(awardDict))\n return [x for x in awardDict if awardDict[x] > 1] \n\n\n \"\"\"def awardParseRegex(self):\n print(\"parsing awards\",self.year)\n regexParse = self.datab.getRegexFullMatchOnly(re.compile(\"Best(([\\s][A-Z\\-][a-z,]{2,})| in a| in an| by an| or| \\-| for)+\"))\n tangent = [\"on Picture\",\"Series\"]\n antiTangent = [\"Should\", \"t Ac\", \"t Su\",\" a F\",\"t Fi\",\"olden\"]\n duoTangent = [(\",\",\", L\"),(\"for\",\"for Te\")]\n if(int(self.year) <= 2015):\n tangent.append(\"Film\")\n \n r2 = list(filter(lambda match: any([kw in match for kw in tangent]),regexParse))\n r3 = list(filter(lambda cull: \n len(cull.split(\" \")) > 3 and len(cull.split(\"\\n\")) == 1 and len(cull.split(\"-\")) < 3 and not any([kw in cull for kw in antiTangent]) and\n cull[-1] not in [\"r\",\"-\",\"n\"] and not any([kw[0] in cull and not kw[1] in cull for kw in duoTangent]),r2))\n\n vote = {}\n for string in r3:\n if string.replace(\"- \",\"\") in vote:\n vote[string] = vote[string.replace(\"- \",\"\")] + 1\n del vote[string.replace(\"- \",\"\")]\n elif string in vote:\n vote[string] += 1\n else:\n vote[string] = 1\n\n return [x for x in vote if vote[x] > 1]\"\"\"\n\n\n def WeinsteinMachine(self):\n firstcull = self.datab.ANDorFILTER([[\"Weinstein\",\"Harvey Weinstein\",\"Harvey\",\"Weinzstein\",\"Wienstien\",\"Weinstien\"]])\n context = {}\n mentionTimes = len(firstcull)\n for tweet in firstcull:\n doc = spacyNLP(tweet)\n idx = 0\n for word in doc:\n if word.text in [\"Weinstein\",\"Harvey\"]:\n idx = word.i\n break\n start = max(idx - 3,0)\n end = min(idx + 3, len(list(doc)))\n for word in doc[start:end+1]: \n if word.tag_ in [\"NNP\",\"NNP\",\"NNPS\",\"NNS\",\"NN\",\"VBD\",\"VBG\",\"VBP\",\"VBZ\"] and word.text not in [\"Weinstein\",\"Harvey\",\"Golden\",\"Globes\"] and len(word.text) > 3:\n if word.text in context:\n context[word.text]+=1\n else:\n context[word.text]=1\n \n \n chunky = sorted(context,key=context.get)\n dictma = {'unique-mentions':mentionTimes,'most-associated-terms':chunky[-7:]}\n return dictma\n\n def newNominees(self,award):\n self.PopulateHardQueries()\n\n query = self.HardQueries[award]\n filledQ = list(filter(lambda tweet: \"nominees:\" in tweet and not any(kw in tweet for kw in [\"present\",\"won\",\"win\",\"not\",\"n't\",\"goes\",\"?\"]),query))\n\n for string in filledQ:\n spd = string[string.index(\"nominees:\")+9:]\n a = spd.replace(\"and\", \"\").split(\",\")\n if len(a) > 1:\n return a\n \n return []\n\n def Top5BestDressed(self):\n firstcull = self.datab.ANDorFILTER([[\"beautiful\",\"gorgeous\",\"ravishing\",\"best dressed\"]],False)\n\n docs = []\n hostVote = {}\n if len(firstcull) > 500:\n firstcull = firstcull[0:500]\n\n for tweet in firstcull:\n docs.append(spacyNLP(tweet))\n\n for doc in docs:\n for ent in doc.ents:\n if ent.label_ == \"PERSON\" and \"olden\" not in ent.text:\n if ent.lower_ in hostVote:\n hostVote[ent.lower_] += 1\n else:\n hostVote[ent.lower_] = 1\n\n hVs = sorted(hostVote,key = hostVote.get)\n return hVs[-5:]\n","sub_path":"AwardParse.py","file_name":"AwardParse.py","file_ext":"py","file_size_in_byte":28391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"145681951","text":"# %% this idea is from https://www.kaggle.com/c/porto-seguro-safe-driver-prediction/discussion/44629\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = '1'\nbase_path = '/home/tom/mywork/some_test/porto_seguro/input/'\n\nmodel_name = 'porto_seguro_dae004'\ndata_path = '/home/tom/data/porto_seguro_dae'\nmodel_path = os.path.join(data_path, model_name)\nif not os.path.exists(model_path):\n os.makedirs(model_path)\n\n# %% The last cell preprocess data. In this cell, let data go into one model\n# in dae003, try hyperopt\nimport os\nimport pandas as pd\nimport numpy as np\nimport hyperopt as hp\nfrom hyperopt import fmin, rand, tpe, hp, pyll, base, space_eval, Trials\nfrom hyperopt.pyll import Apply, as_apply, dfs, scope\nfrom hyperopt.mongoexp import MongoTrials\nfrom PPMoney.core.utils import proc_run\nfrom PPMoney.core.model.space import space_lgb_binary, space_update, sample_int\nfrom PPMoney.core.data import HDFDataSet\n\nsuggest = rand.suggest\n\ndata_root = model_path\nmodel_root = os.path.join(data_root, \"test_model\")#\"/tmp/test_model\"\n\n\nextra_param = {\n \"train_file\": os.path.join(data_path, 'mjahrer_1st_train.dataset'),\n \"model_root\": model_root,\n \"n_fold\": 5,\n \"summary_step\": 10,\n \"lgb_param\": {\n # 'objective' use default PPMoney/core/model/space.py\n # 'boosting_type' use default PPMoney/core/model/space.py\n # 'learning_rate' use default PPMoney/core/model/space.py\n 'max_bin': 2 ** sample_int(\"i_max_bins\", 5, 9) - 1,\n 'num_leaves': 2 ** sample_int(\"v_num_leaves\", 4, 8) - 1,\n 'min_data_in_leaf': 2 ** sample_int(\"idx_min_data_in_leaf\", 5, 11),\n # 'feature_fraction' use default PPMoney/core/model/space.py\n 'bagging_freq': sample_int(\"bagging_frq\", 1, 10),\n # 'bagging_fraction' use default PPMoney/core/model/space.py\n\n \"num_threads\": 80,\n \"verbose\": -1,\n \"lambda_l1\": 2 ** sample_int(\"v_lambda_l1\", 0, 4) - 1,\n \"lambda_l2\": 2 ** sample_int(\"v_lambda_l2\", 0, 4) - 1,\n }\n}\n\n# from sklearn.model_selection import StratifiedKFold\n# skf = StratifiedKFold(n_splits=extra_param['n_fold'], random_state=0)\n# train_index, valid_index = next(skf.split(X_0, y_0))\n\n@proc_run\ndef lgb_run(param):\n import pprint\n import numpy as np\n pprint.pprint(param)\n from sklearn.datasets import load_svmlight_file as load_svm\n from PPMoney.core.model import BinaryLGB\n from PPMoney.core.model.metrics import ModelMetric\n\n file_tr = param[\"train_file\"]\n model_root = param[\"model_root\"]\n n_fold = param[\"n_fold\"]\n\n from PPMoney.core.data import HDFDataSet\n dataset_load = HDFDataSet(file_tr, chunk_size=2048)\n\n X, y = dataset_load['feature'], dataset_load['label']\n label = y == 1\n print(f\"X.shape, label.shape: {X.shape, label.shape}\")\n\n from sklearn.model_selection import StratifiedKFold\n skf = StratifiedKFold(n_splits=n_fold, random_state=0)\n train_index, valid_index = next(skf.split(X, label))\n\n X_tr, X_v = X[train_index], X[valid_index]\n label_tr, label_v = label[train_index], label[valid_index]\n\n # X_tr = X[:-n_val]\n # label_tr = label[:-n_val]\n # X_v = X[-n_val:]\n # label_v = label[-n_val:]\n\n import os\n if not os.path.isdir(model_root):\n os.mkdir(model_root)\n\n v_metric = ModelMetric(feature_t=X_v, label_t=label_v, name=\"VA\", metrics=[\"AUC\"], minimize=False)\n tr_metric = ModelMetric(feature_t=X_tr, label_t=label_tr, name=\"TR\", metrics=[\"auc\"], minimize=False)\n\n model = BinaryLGB(\n model_root=model_root,\n model_metric=[v_metric, tr_metric], #可以定义多个metric,其中第一个的作为模型选择的基准\n model_name=None # for random model name\n )\n return model.fit(param, X_tr, label_tr)\n\n# 先试试单线程\n# fmin(lgb_run, space_lgb, algo=suggest, max_evals=5)\n\n\n# %%\n\nspace_lgb = space_update(space_lgb_binary, extra_param, model_key=\"lgb_bin\", n_round=2000)\n\n# mongo trials可以进行并行训练,可以同时跑多组参数\n# from hyperopt.mongoexp import MongoTrials\n# trials_lgb = MongoTrials('mongo://$addr/lgb_worker/jobs', exp_key=f'test_model')\ntrials_lgb = Trials()\n\nfrom multiprocessing.pool import ThreadPool\n\nwith ThreadPool(4) as pool:\n #提交给线程池运行,这样可以同时运行多个fmin\n res = pool.apply_async(fmin, args=(lgb_run, space_lgb), kwds={\"trials\": trials_lgb, \"algo\": suggest, \"max_evals\": 20})\n res.get()\n\n# %%\n\nfrom hyperopt.plotting import main_plot_vars, main_plot_history, main_plot_histogram\nimport matplotlib.pylab as plt\n\nfor sp, trls in zip([space_lgb], [trials_lgb]):\n domain = base.Domain(lgb_run, sp)\n # plt.figure(figsize=(20, 40))\n # main_plot_vars(trls, bandit=domain, colorize_best=30, columns=1)\n plt.figure(figsize=(20, 5))\n # plt.ylim((-0.003, 0.003))\n main_plot_history(trls, bandit=domain)\n\n# NOTE: 对trials_lgb的性能的评判应该是VA的第一个metric指标的负数,至少在这个例子里是这样\n\ntrials_lgb.trials # 所有模型的参数和结果的字典组成的一个list\ntrials_lgb.results # 返回所有实验的结果\ntrials_lgb.miscs # 返回所有实验的参数\ntrials_lgb.vals # 返回所有实验的跟space更新有关的参数\n\ntrials_lgb.trials[0]['misc']['vals']\ntmp1 = space_lgb['lgb_param']['bagging_fraction']\ntmp2 = 2 ** sample_int(\"v_lambda_l1\", 0, 2) - 1\n5**-1.6 # 0.07614615754863513\n\ntype(tmp2), dir(tmp2)\n\n# NOTE: 试验space到实际数值的映射, 可能和Apply没关系\nhp_assignment = {k:v[0] for k,v in trials_lgb.trials[0]['misc']['vals'].items()}\nhp_assignment = {k:v[0] for k,v in trials_lgb.vals.items()} # 这句和上面那句等价,这句更简洁\nspace_eval(space_lgb, hp_assignment)\n\n\ntrials_lgb.trials[0]['result'] # {'loss': -0.8737864077669903, 'status': 'ok'}\n# 返回k个最好的模型的参数dict组成的一个list\ntrials_lgb.topk_trials(k=2)\n# return_score=True就返回2个list组成的tuple\ntrials_lgb.topk_trials(2, return_score=True, ordered=True)\ntype(trials_lgb.topk_trials(2, return_score=True, ordered=True)[0][0]) # 这个类型就是个dict\n# Trials().trial_attachments的作用是,根据trial的参数字典解析出相应的model路径\ntrials_lgb.trial_attachments(trials_lgb.topk_trials(2, return_score=True, ordered=True)[0][0])[\"model\"].decode()\n# %%\n\n#返回topk的模型\nselect_models = lambda trials, k: [(trials.trial_attachments(t)[\"model\"].decode(), c) for t, c in zip(*trials.topk_trials(k, return_score=True, ordered=True))]\nfor sub_model_path, sub_model_score in select_models(trials_lgb, 3):\n print(-sub_model_score, sub_model_path)\n\nbest_auc = -trials_lgb.topk_trials(1, return_score=True, ordered=True)[1][0]\nbest_space = trials_lgb.topk_trials(1, return_score=True, ordered=True)[0][0]['misc']['vals']\nbest_hyperparam = space_eval(space_lgb, hp_assignment = {k:v[0] for k,v in best_space.items()})\nbest_model_path = select_models(trials_lgb, 1)[0][0]\n\nimport json\nwith open(os.path.join(model_path, 'best_model.json'), 'w') as f:\n json.dump({'best_auc': best_auc, 'best_hyperparam': best_hyperparam, 'best_model_path': best_model_path},\n f, ensure_ascii=False, indent=2, separators=(',', ': '))\n\n# %% reload data and the best model to predict testset\nfrom PPMoney.core.data import HDFDataSet\ndataset_load = HDFDataSet(os.path.join(data_path, 'mjahrer_1st_test.dataset'), chunk_size=2048)\n\nX_test = dataset_load['feature']\nprint(f'Shape of X_test: {X_test.shape}')\n\nbest_model_path = os.path.join(model_root, 'e1422032-dcff-11e7-966f-0cc47a64aaf0/model/00890.model')\n\nimport lightgbm as lgb\nmodel = lgb.Booster(model_file=best_model_path)\ny_test = model.predict(X_test)\n\nX_test_raw = pd.read_csv(base_path+'test.csv')\nsub = X_test_raw['id'].to_frame()\nsub['target'] = 0\nsub['target'] = y_test\nsub.to_csv(os.path.join(model_path, 'test_'+model_name+'.csv.gz'), index=False, float_format='%.5f', compression='gzip')\n# test_porto_seguro_dae004.csv.gz, eval: 0.286, PublicLB: 0.28090, PrivateLB: 0.28720\n","sub_path":"code/script_reproduce_kaggle_1st_dae004.py","file_name":"script_reproduce_kaggle_1st_dae004.py","file_ext":"py","file_size_in_byte":7949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"301110636","text":"# Create a faster factorial lookup dictionary\r\nfactorials = {'0':1,'1':1,'2':2,'3':6,'4':24,'5':120,'6':720,'7':5040,'8':40320,'9':362880}\r\n\r\ndigit_factorials = []\r\n\r\n# Check up to 3 million as 9! = 362880 which means that after 3 million or so\r\n# the number gets bigger than the maximum possible sum of the factorial of its\r\n# digits. (ie: 9!*7 which would correpond to almost 10 million is only\r\n# ~ 2.5 million)\r\nfor num in range(3,30000000):\r\n total = 0\r\n for digit in str(num):\r\n total += factorials[digit]\r\n if total == num:\r\n digit_factorials.append(num)\r\n \r\nprint(digit_factorials)","sub_path":"#34.py","file_name":"#34.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"108458605","text":"from django import template\nfrom django.db.models.query import EmptyQuerySet\nfrom django.shortcuts import render\nfrom django.http import HttpResponse # This takes http requests\nfrom . import forms\nfrom django.shortcuts import redirect\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm\nfrom django.contrib.sessions.models import Session\nfrom django.contrib.auth.models import User, Group\nfrom django.contrib.auth.decorators import login_required\nfrom django.urls import reverse_lazy\nfrom django.contrib.auth import update_session_auth_hash\nfrom django.contrib import messages\nfrom django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.views.generic import ListView, DetailView, View, CreateView, UpdateView, DeleteView\nfrom django.utils import timezone\nfrom .models import Categoria, Producto, Carrito, ProductoAgregado\nfrom store.forms import NuevoProductoForm\nfrom django.db.models import Q, F\nimport pprint\nimport json\nimport random\n\n\n# Create your views here.\ndef index(request):\n productos = Producto.objects.all()\n productos_ordenados = productos.order_by('-fecha_creacion')\n\n index = 0\n tres_productos = []\n while index < 3:\n un_producto = productos_ordenados[index]\n tres_productos.append(un_producto)\n index +=1\n\n index = 3\n siete_productos = []\n while index < 10:\n un_producto = productos_ordenados[index]\n siete_productos.append(un_producto)\n index +=1\n\n print(productos)\n dictionary = {\n 'tres_productos': tres_productos,\n 'siete_productos': siete_productos,\n }\n return render(request, 'index.html', context=dictionary)\n\ndef acerca_de(request):\n dictionary={}\n return render(request, 'acerca_de.html', context=dictionary)\n\ndef sign_up_form(request):\n form = forms.SignUpForm() # class defined in forms.py\n dictionary = {\"form\": form}\n \n if request.method == \"POST\":\n form = forms.SignUpForm(request.POST) # creating a variable that receives the POST\n if form.is_valid(): \n password = form.clean_password2()\n user = form.save(commit=False)\n user.save()\n grupo_estandar = Group.objects.get(name='Estandar')\n user.groups.add(grupo_estandar)\n \n form.save()\n\n return redirect('resultado_registro/')\n else:\n print(\"Invalid form request\")\n error = form.errors\n print(error)\n dictionary = {\n 'error': error\n } \n else:\n form = forms.SignUpForm()\n \n dictionary = {\n 'form': form\n } \n return render(request, \"registro.html\", context=dictionary)\n\ndef resultado_registro(request):\n dictionary = {}\n return render(request, \"resultado_registro.html\", context=dictionary)\n\ndef login_form(request):\n username = 'not logged in'\n user = request.user\n form = AuthenticationForm()\n dictionary = {\n 'form': form\n }\n if request.method == 'POST':\n form = AuthenticationForm(data=request.POST)\n if form.is_valid():\n username = form.cleaned_data['username']\n password = form.cleaned_data['password']\n if username and password:\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n request.session['username'] = username\n login(request, user)\n print('form and session started')\n return redirect('resultado_login/')\n else:\n error = form.errors\n print(error)\n dictionary = {\n 'error': error\n }\n else:\n form = AuthenticationForm()\n\n dictionary = {\n 'object_list': user,\n 'form': form,\n }\n \n return render(request, \"login.html\", context=dictionary)\n\ndef resultado_login(request):\n dictionary = {}\n return render(request, \"resultado_login.html\", context=dictionary)\n\n@login_required(login_url='/login/')\ndef sign_out(request): # my logout view\n request.session.clear()\n logout(request)\n print(\"All sessions closed\")\n return render(request, \"logout.html\")\n\nclass VistaProducto(DetailView):\n model = Producto\n template_name = \"producto.html\"\n\nclass VistaResumenCompra(LoginRequiredMixin, View):\n login_url = '/login/'\n redirect_field_name = 'redirect_to'\n def get(self, *args, **kwargs):\n try:\n compra = Carrito.objects.get(usuario=self.request.user, ya_pedido=False)\n contexto= {\n 'objeto': compra\n }\n return render(self.request, 'resumen_compra.html', context=contexto)\n except ObjectDoesNotExist:\n messages.error(self.request, 'No tiene un carrito todavía')\n return redirect('/')\n\n@login_required(login_url= '/login/')\ndef agregar_al_carrito(request, pk):\n producto = get_object_or_404(Producto, pk=pk)\n producto_agregado, creado = ProductoAgregado.objects.get_or_create(\n producto = producto,\n usuario = request.user,\n ya_agregado = False\n )\n\n producto_existente_carrito = Carrito.objects.filter(usuario=request.user, ya_pedido=False)\n\n if producto_existente_carrito.exists():\n agrega_producto = producto_existente_carrito[0]\n\n if agrega_producto.productos.filter(producto__pk=producto.pk).exists():\n producto_agregado.cantidad += 1\n producto_agregado.save()\n messages.info(request, \"Agregada/s unidad/es\")\n return redirect(\"store:resumen_compra\")\n else:\n agrega_producto.productos.add(producto_agregado)\n messages.info(request, 'Producto agregado al carrito')\n return redirect(\"store:resumen_compra\")\n else:\n fecha_pedido = timezone.now()\n agregado_al_pedido = Carrito.objects.create(usuario=request.user, fecha=fecha_pedido)\n agregado_al_pedido.productos.add(producto_agregado)\n messages.info(request, \"Producto agregado al carrito\")\n return redirect('store:resumen_compra')\n\n\n@login_required\ndef quitar_del_carrito(request, pk):\n producto = get_object_or_404(Producto, pk=pk )\n producto_existente = Carrito.objects.filter(usuario=request.user, ya_pedido=False)\n\n if producto_existente.exists():\n quita_producto = producto_existente[0]\n if quita_producto.productos.filter(producto__pk=producto.pk).exists():\n producto_en_lista = ProductoAgregado.objects.filter( producto=producto,\n usuario=request.user,\n ya_agregado=False\n )[0]\n producto_en_lista.delete()\n messages.info(request, \"Item \\\"\"+producto_en_lista.producto.titulo+\"\\\" retirado del carrito\")\n return redirect(\"store:resumen_compra\")\n else:\n messages.info(request, \"Este producto no está en su carrito\")\n return redirect(\"store:producto\", pk=pk)\n else:\n #add message doesnt have order\n messages.info(request, \"No tiene un carrito\")\n return redirect(\"store:producto\", pk = pk)\n\n@login_required\ndef eliminar_carrito(request):\n productos_del_usuario = Carrito.objects.filter(usuario=request.user, ya_pedido=False)\n\n if productos_del_usuario.exists():\n Carrito.objects.filter(usuario=request.user, ya_pedido=False).delete()\n ProductoAgregado.objects.filter(usuario=request.user, ya_agregado=False).delete()\n Carrito.objects.create(usuario=request.user)\n\n return redirect(\"store:carrito_eliminado\")\n else:\n #add message doesnt have order\n messages.info(request, \"No tiene un carrito\")\n return redirect(\"/\")\n\ndef carrito_eliminado(request):\n dictionary = {}\n return render(request, \"carrito_eliminado.html\", context=dictionary)\n\n@login_required\ndef reducir_cantidad_producto(request, pk):\n producto = get_object_or_404(Producto, pk=pk )\n producto_existente = Carrito.objects.filter(\n usuario = request.user, \n ya_pedido = False\n )\n if producto_existente.exists():\n quita_producto = producto_existente[0]\n if quita_producto.productos.filter(producto__pk=producto.pk).exists() :\n item = ProductoAgregado.objects.filter(\n producto = producto,\n usuario = request.user,\n ya_agregado = False\n )[0]\n if item.cantidad > 1:\n item.cantidad -= 1\n item.save()\n else:\n item.delete()\n messages.info(request, \"La cantidad fue modificada\")\n return redirect(\"store:resumen_compra\")\n else:\n messages.info(request, \"Este item no esta en su lista\")\n return redirect(\"store:resumen_compra\")\n else:\n #add message doesnt have order\n messages.info(request, \"No tiene un carrito\")\n return redirect(\"store:resumen_compra\")\n\nclass NuevoProductoView(LoginRequiredMixin, PermissionRequiredMixin, CreateView):\n login_url = '/login/'\n redirect_field_name = 'redirect_to'\n permission_required = 'store.can_add_productos'\n \n form_class = NuevoProductoForm\n template_name = 'nuevo_producto.html'\n success_url = 'nuevo_producto_resultado'\n\ndef nuevo_producto_resultado(request):\n dictionary = {}\n return render(request, \"nuevo_producto_resultado.html\", context=dictionary)\n\nclass ResultadoBusqueda(ListView):\n model = Producto\n template_name = 'resultado_busqueda.html'\n\n def get_queryset(self):\n query = self.request.GET.get('q')\n if query:\n queryset = Producto.objects.filter(\n Q(titulo__icontains=query) | Q(categoria_base__descripcion__icontains=query) | Q(detalle__icontains=query)\n )\n print(queryset)\n else:\n queryset = Producto.objects.all()\n\n return queryset\n\n\nclass ResultadoBusquedaCategoria(ListView):\n model = Producto\n template_name = 'resultado_busqueda_categoria.html'\n\n def get_queryset(self):\n query = self.request.GET.get('q')\n print(query)\n if query:\n queryset = Producto.objects.filter(Q(categoria_base__descripcion__icontains=query))\n print(queryset)\n else:\n queryset = Producto.objects.all()\n\n return queryset\n\nclass EditarProductoView(LoginRequiredMixin, PermissionRequiredMixin, UpdateView):\n login_url = '/login/'\n redirect_field_name = 'redirect_to'\n permission_required = 'store.can_add_productos'\n \n model = Producto\n template_name = 'actualizar_producto.html'\n success_url = 'producto_actualizado'\n fields=[\n 'titulo','categoria_base','detalle','precio','imagen'\n ]\n\ndef producto_actualizado(request):\n dictionary = {}\n return render(request, \"producto_actualizado.html\", context=dictionary)\n\n\nclass EliminarProductoView(LoginRequiredMixin, PermissionRequiredMixin, DeleteView):\n login_url = '/login/'\n redirect_field_name = 'redirect_to'\n permission_required = 'store.can_add_productos'\n \n model = Producto\n template_name = 'eliminar_producto.html'\n success_url = 'producto_eliminado'\n fields=[\n 'titulo','categoria_base','detalle','precio','imagen'\n ]\n\ndef producto_eliminado(request):\n dictionary = {}\n return render(request, \"producto_eliminado.html\", context=dictionary)","sub_path":"src/store/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"212132936","text":"# Compute the probability that ten randomly selected 15-mers from the ten 600-nucleotide \n# long strings in the Subtle Motif Problem capture at least one implanted 15-mer. (Allowable error: 0.000001)\n\nimport math\n\ndna_length = 600\nkmer_length = 15\nstrands_dna = 10\n\ndef probability_implanted_kmer_in_dna(dna_length, kmer_length, strands_dna):\n # First you compute p1 - probability of not capturing the implanted k-mer (15-mer) in one string.\n # Then you notice for the entire problem we have to deal with ten similar cases, i.e. you have to\n # multiply p1 * p2... *p10, where p1 = p2 = ... = p10. So you just compute p1 to the 10th power:\n # Then you just compute the 'opposite' probability, i.e. the probability that from ten 600-length \n # nucleotide string, we capture at least one implanted 15-mer! \n p = (dna_length - kmer_length) / ((dna_length - kmer_length) + 1)\n return 1 - math.pow(p, 10)\nprint(probability_implanted_kmer_in_dna(dna_length, kmer_length, strands_dna))\n","sub_path":"Python/Bioinformatics/FindingHIddenMessagesInDNA/probability_implanted_kmer_in_dna.py","file_name":"probability_implanted_kmer_in_dna.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"46473188","text":"from django.contrib import admin\nfrom django.urls import path\nfrom onlineapp.views import *\n\nurlpatterns = [\n path('test/', testview.test, name=\"test\"),\n path('login/', LoginController.as_view(), name=\"login\"),\n path('signup/', SignUpController.as_view(), name=\"signup\"),\n path('logout/', logout_user, name=\"logout\"),\n\n path('api/v1/colleges/', college_list, name=\"rest_colleges\"),\n path('api/v1/colleges//', college_list, name=\"rest_colleges\"),\n path('api/v1/colleges//students/', student_details.as_view(), name=\"rest_students\"),\n path('api/v1/colleges//students//', student_details.as_view(), name=\"rest_students\"),\n path('api-token-auth/', CustomAuthToken.as_view()),\n\n path('colleges/', CollegeView.as_view(), name=\"colleges_html\"),\n path('colleges//', CollegeView.as_view(), name=\"college_details\"),\n path('colleges/add', AddCollegeView.as_view(), name=\"add_college\"),\n path('colleges//edit', AddCollegeView.as_view(), name=\"edit_college\"),\n path('colleges//delete', DeleteCollegeView.as_view(), name=\"delete_college\"),\n path('colleges//addstudent', AddStudentView.as_view(), name=\"add_student\"),\n path('colleges//editstudent/', AddStudentView.as_view(), name=\"edit_student\"),\n path('colleges//deletestudent/', DeleteStudentView.as_view(), name=\"delete_student\"),\n\n]\n","sub_path":"classproject/onlineapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"454872460","text":"numOfList = int(input(\"Enter the number of lists you want to make: \"))\n\nmyList = []\n\ni = 1\ncount = 0\n\nfor list in range(numOfList):\n count = count + 3\n subList = []\n while(count >= i):\n subList.append(i)\n i = i + 1\n\n myList.append(subList)\n\nprint(myList)","sub_path":"adelphi_prob.py","file_name":"adelphi_prob.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"260289073","text":"import sys\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.mlab as mlab\r\nimport numpy as np\r\nimport random\r\nimport timeit\r\n\r\nelectionFile = sys.argv[1]\r\nnomineeList = sys.argv[2].split(\",\")\r\nnomineeColumnIndex = [0 for i in range(len(nomineeList))]\r\noutputFile = \"retrievedData.txt\"\r\nanswerFile = \"myAnswer.txt\"\r\n\r\nstateList = []\r\nnomineesVotes = [[] for i in range(len(nomineeList))]\r\ncolorList = ['r','b','y','c','m']\r\n\r\nmeanArray = [0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1]\r\nnumUSAGreater = 0\r\npercUSAGreater = 0\r\npLevel = 0\r\nelectionDataSize = 0\r\nrandMSESize = 10000\r\n\r\ndef retrieveData(filename,nominees):\r\n\tglobal electionDataSize\r\n\tnumLines = 0\r\n\twith open(filename) as f:\r\n\t\tfirstline = 1\r\n\t\tfor line in f:\r\n\t\t\tif 1 == firstline:\r\n\t\t\t\tlineArr = line.rstrip().split(\",\")\r\n\t\t\t\tfor i in range(len(nominees)):\r\n\t\t\t\t\tnomineeColumnIndex[i] = lineArr.index(nominees[i])\r\n\t\t\telse:\r\n\t\t\t\tlineArr = line.split(\",\")\r\n\t\t\t\tstateList.append(lineArr[0])\r\n\t\t\t\tfor i in range(len(nominees)):\r\n\t\t\t\t\tnomineesVotes[i].append(int(lineArr[nomineeColumnIndex[i]]))\r\n\t\t\t\tnumLines = numLines + 1\r\n\t\t\tfirstline = 0\r\n\telectionDataSize = numLines * len(nominees)\r\n\toutputList = []\r\n\tfor i in range(len(nominees)):\r\n\t\tfor vote in nomineesVotes[i]:\r\n\t\t\toutputList.append(vote)\r\n\treturn outputList\r\n\r\nvoteList = retrieveData(electionFile,nomineeList)\r\n\r\nwith open(outputFile,\"w\") as output:\r\n\toutput.write(str(voteList))\r\n\r\noutput.close()\r\n\r\ndef DispBarPlot():\r\n\tfirstNom = 0\r\n\tsecondNom = 0\r\n\tfor i in range(len(nomineeList)):\r\n\t\tif sum(nomineesVotes[i]) > sum(nomineesVotes[firstNom]):\r\n\t\t\tfirstNom = i\r\n\t\t\tsecondNom = firstNom\r\n\t\telif sum(nomineesVotes[i]) > sum(nomineesVotes[secondNom]):\r\n\t\t\tsecondNom = i\r\n\t\telif secondNom == firstNom:\r\n\t\t\tsecondNom = i\r\n\r\n\tn_groups = len(stateList)\r\n\r\n\tfirstVotes = nomineesVotes[firstNom]\r\n\r\n\tsecondVotes = nomineesVotes[secondNom]\r\n\r\n\tfig, ax = plt.subplots(figsize=(20,10))\r\n\tindex = np.arange(n_groups)\r\n\r\n\tbar_width = 0.3\r\n\topacity = 1\r\n\terror_config = {'ecolor': '0.3'}\r\n\r\n\trects2 = plt.bar(index + 1, secondVotes, bar_width,\r\n\t\t\t\t\t alpha=opacity,\r\n\t\t\t\t\t color='r',\r\n\t\t\t\t\t yerr=None,\r\n\t\t\t\t\t error_kw=error_config,\r\n\t\t\t\t\t label=nomineeList[secondNom])\r\n\r\n\trects1 = plt.bar(index+1+bar_width, firstVotes, bar_width,\r\n\t\t\t\t\t alpha=opacity,\r\n\t\t\t\t\t color='b',\r\n\t\t\t\t\t yerr=None,\r\n\t\t\t\t\t error_kw=error_config,\r\n\t\t\t\t\t label=nomineeList[firstNom])\r\n\r\n\tplt.xlabel('State')\r\n\tplt.ylabel('Votes')\r\n\tplt.title('Votes per State')\r\n\tplt.xticks(index + bar_width + 1, stateList,rotation =90)\r\n\tplt.legend()\r\n\tplt.tight_layout()\r\n\tplt.savefig(\"ComparativeVotes.pdf\")\r\n\r\ndef calculatepersantages():\r\n\tpersantageList=[0 for i in range(len(nomineeList))]\r\n\ttotalVotes = [0 for i in range(len(nomineeList))]\r\n\tallTotal=0\r\n\tfor i in range(len(nomineeList)):\r\n\t\tfor vote in nomineesVotes[i]:\r\n\t\t\ttotalVotes[i] = totalVotes[i] + vote\r\n\t\tallTotal = allTotal + totalVotes[i]\r\n\r\n\tfor i in range(len(nomineeList)):\r\n\t\tpersantageList[i] = (totalVotes[i] / allTotal) * 100\r\n\treturn persantageList\r\n\r\ndef compareVoteonBar():\r\n\tpercentages =calculatepersantages()\r\n\tn_groups = len(percentages)\r\n\r\n\tfig, ax = plt.subplots()\r\n\r\n\tindex = np.arange(n_groups)\r\n\tbar_width = 0.7\r\n\r\n\topacity = 1\r\n\terror_config = {'ecolor': '0.3'}\r\n\r\n\trects = plt.bar(index,percentages, bar_width,\r\n\t\t\t\t\t color = colorList[0],\r\n\t\t\t\t\t alpha=opacity,\r\n\t\t\t\t\t yerr=None,\r\n\t\t\t\t\t error_kw=error_config,\r\n\t\t\t\t\t label=nomineeList[0]\r\n\t\t\t\t\t )\r\n\r\n\tfor i in range(1,len(nomineeList)):\r\n\t\tplt.bar(0,0, bar_width,\r\n\t\tcolor = colorList[i%5],\r\n\t\talpha=opacity,\r\n\t\tyerr=None,\r\n\t\terror_kw=error_config,\r\n\t\tlabel=nomineeList[i])\r\n\r\n\t\trects[i].set_color(colorList[i])\r\n\r\n\tpercentagesFormatted = []\r\n\tfor percent in percentages:\r\n\t\tpercentagesFormatted.append(\"{0:.3f}\".format(percent))\r\n\r\n\tplt.xlabel('Nominees')\r\n\tplt.ylabel('vote percentages')\r\n\tplt.xticks(index + bar_width/2, percentagesFormatted)\r\n\tplt.legend()\r\n\tplt.tight_layout()\r\n\tplt.savefig(\"CompVotePercs.pdf\")\r\n\r\ndef obtainHistogram(numbers):\r\n\tdataLen = len(numbers)\r\n\thistogramNums = []\r\n\thistogramPerc = []\r\n\ttotalDigits = 0\r\n\tfor i in range(0,10):\r\n\t\thistogramNums.append(0)\r\n\t\thistogramPerc.append(0)\r\n\tfor num in numbers:\r\n\t\tdigitOnes = int(num % 10)\r\n\t\thistogramNums[digitOnes] = histogramNums[digitOnes] + 1\r\n\t\tdigitTens = int((num/10) % 10)\r\n\t\thistogramNums[digitTens] = histogramNums[digitTens] + 1\r\n\t\ttotalDigits = totalDigits + 2\r\n\tfor i in range(0,10):\r\n\t\thistogramPerc[i] = histogramNums[i] / totalDigits\r\n\treturn histogramPerc\r\n\r\ndef plotHistogram(histData, plotColor, outputPdfFile):\r\n\tplt.clf()\r\n\tdashedLine = plt.plot(meanArray)\r\n\tplt.setp(dashedLine, color = 'g',label='Mean',linestyle=\"dashed\")\r\n\tdigitLine = plt.plot(histData)\r\n\tplt.setp(digitLine, color=plotColor,label='Digit Dist.')\r\n\tplt.title('Histogram of least sign. digits')\r\n\tplt.ylabel('Distribution')\r\n\tplt.xlabel('Digits')\r\n\tplt.legend()\r\n\tplt.savefig(outputPdfFile)\r\n\r\ndef plotHistogramWithSample():\r\n\trand_10 = [];rand_50 = []; rand_100 = []; rand_1000 = []; rand_10000 = []\r\n\tfor i in range(0,10):\r\n\t\trand_10.append(random.choice(range(0,100)))\r\n\tfor i in range(0,50):\r\n\t\trand_50.append(random.choice(range(0,100)))\r\n\tfor i in range(0,100):\r\n\t\trand_100.append(random.choice(range(0,100)))\r\n\tfor i in range(0,1000):\r\n\t\trand_1000.append(random.choice(range(0,100)))\r\n\tfor i in range(0,10000):\r\n\t\trand_10000.append(random.choice(range(0,100)))\r\n\r\n\thist_1 = obtainHistogram(rand_10)\r\n\tplotHistogram(hist_1,'r',\"HistogramofSample1.pdf\")\r\n\r\n\thist_2 = obtainHistogram(rand_50)\r\n\tplotHistogram(hist_2,'b',\"HistogramofSample2.pdf\")\r\n\r\n\thist_3 = obtainHistogram(rand_100)\r\n\tplotHistogram(hist_3,'y',\"HistogramofSample3.pdf\")\r\n\r\n\thist_4 = obtainHistogram(rand_1000)\r\n\tplotHistogram(hist_4,'c',\"HistogramofSample4.pdf\")\r\n\r\n\thist_5 = obtainHistogram(rand_10000)\r\n\tplotHistogram(hist_5,'m',\"HistogramofSample5.pdf\")\r\n\r\ndef calculateMSE(list1,list2) :\r\n\tcalcualatedVal = 0\r\n\tfor i in range(0,len(list1)):\r\n\t\tcalcualatedVal = calcualatedVal + (list2[i] - list1[i])**2\r\n\treturn calcualatedVal\r\n\r\ndef compareMSEs(usaElectionMSE):\r\n\tglobal numUSAGreater\r\n\tglobal percUSAGreater\r\n\tglobal pLevel\r\n\tfor i in range(randMSESize):\r\n\t\trand_Election = []\r\n\t\tfor i in range(0,electionDataSize):\r\n\t\t\trand_Election.append(random.choice(range(0,100)))\r\n\t\thistPercentRand = obtainHistogram(rand_Election)\r\n\t\tmseRand = calculateMSE(histPercentRand, meanArray)\r\n\t\tif usaElectionMSE > mseRand:\r\n\t\t\tnumUSAGreater = numUSAGreater + 1\r\n\tpercUSAGreater = (numUSAGreater / randMSESize) * 100\r\n\tpLevel = numUSAGreater / randMSESize\r\n\r\nDispBarPlot()\r\ncompareVoteonBar()\r\n\r\nhistPercent = obtainHistogram(voteList)\r\nplotHistogram(histPercent, 'r', \"Histogram.pdf\")\r\nplotHistogramWithSample()\r\n\r\nusaMSE = calculateMSE(histPercent, meanArray)\r\ncompareMSEs(usaMSE)\r\n\r\nprint(\"MSE value of 2012 USA election is : \" + str(usaMSE))\r\nprint(\"The number of MSE of random samples which are larger than or equal to USA election MSE is : \" + str(randMSESize-numUSAGreater))\r\nprint(\"The number of MSE of random samples which are smaller than USA election MSE is : \" + str(numUSAGreater))\r\nprint(\"2012 USA election rejection level p is : \" + str(pLevel))\r\nif percUSAGreater <= 95:\r\n\tprint(\"Finding: We reject the null hypothesis at the p = \" + str(pLevel) + \" level\")\r\nelse:\r\n\tprint(\"Finding: There is no statistical evidence to reject null\")\r\n\r\nwith open(answerFile,\"w\") as answer:\r\n\tanswer.writelines(\"MSE value of 2012 USA election is : \" + str(usaMSE) + \"\\n\")\r\n\tanswer.writelines(\"The number of MSE of random samples which are larger than or equal to USA election MSE is : \" + str(randMSESize-numUSAGreater)+ \"\\n\")\r\n\tanswer.writelines(\"The number of MSE of random samples which are smaller than USA election MSE is : \" + str(numUSAGreater)+ \"\\n\")\r\n\tanswer.writelines(\"2012 USA election rejection level p is : \" + str(pLevel) + \"\\n\")\r\n\tif percUSAGreater <= 95:\r\n\t\tanswer.writelines(\"Finding: We reject the null hypothesis at the p = \" + str(pLevel) + \" level\" + \"\\n\")\r\n\telse:\r\n\t\tanswer.writelines(\"Finding: There is no statistical evidence to reject null\")\r\nanswer.close()\r\n","sub_path":"DataVisulation.py","file_name":"DataVisulation.py","file_ext":"py","file_size_in_byte":8021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"450234901","text":"import cv2\nimport numpy as np\nimport time\n\ndef getLines(image_name):\n ## Convert from RGB to gray\n img = cv2.imread(image_name)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n \n ## Convert to binary image\n th, threshed = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)\n \n \n ## Calculate rotated image\n pts = cv2.findNonZero(threshed)\n ret = cv2.minAreaRect(pts)\n \n (cx,cy), (w,h), ang = ret\n if w>h:\n w,h = h,w\n ang += 90\n \n M = cv2.getRotationMatrix2D((cx,cy), 0, 1.0)\n rotated = threshed\n rotated = cv2.warpAffine(threshed, M, (img.shape[1], img.shape[0]))\n #cv2.imshow(\"\", rotated)\n #cv2.waitKey()\n \n ## Draw upper and lower lines for each text line\n hist = cv2.reduce(rotated,1, cv2.REDUCE_AVG).reshape(-1)\n \n th = 10\n H,W = img.shape[:2]\n uppers = [y-5 for y in range(H-1) if hist[y]<=th and hist[y+1]>th]\n lowers = [y+5 for y in range(H-1) if hist[y]>th and hist[y+1]<=th]\n print(len(uppers))\n print(len(lowers))\n \n rotated = cv2.cvtColor(rotated, cv2.COLOR_GRAY2BGR)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n \n minDistance = 5\n count = 0\n croppedImages = []\n for i in range(len(uppers)):\n print(uppers[i])\n print(lowers[i])\n tooClose = False\n if abs(uppers[i] - lowers[i]) < minDistance:\n tooClose = True\n print(\"too close\")\n if not tooClose:\n croppedImages.append(rotated[uppers[i]:lowers[i],:])\n #cv2.line(rotated, (0,uppers[i]), (W, uppers[i]), (255,0,0), 1)\n #cv2.line(rotated, (0,lowers[i]), (W, lowers[i]), (0,255,0), 1)\n \n return np.array(croppedImages)\n #cv2.imwrite(\"result.png\", croppedImages[0])\n\ngetLines(\"index.jpg\")","sub_path":"backend/line_detect3.py","file_name":"line_detect3.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"297571947","text":"import numpy as np\r\n\r\ndef ppp(p_value):\r\n \"\"\" Use atsterisks to denote p-values. \"\"\"\r\n if p_value <= 0.01:\r\n return '^{***}'\r\n elif p_value <= 0.05:\r\n return '^{**}'\r\n elif p_value <= 0.1:\r\n return '^{*}'\r\n else:\r\n return ''\r\n\r\n\r\ndef ppf(slope, intercept, p_slope, p_intercept):\r\n \"\"\" Pretty format for regression equations. \"\"\"\r\n\r\n if (np.abs(slope) < 1e-1) | (np.abs(slope) > 10):\r\n fslope = '{:.2e}'.format(slope)\r\n else:\r\n fslope = '%.2f' % slope\r\n fslope += ppp(p_slope)\r\n\r\n if (np.abs(intercept) < 1e-1) | (np.abs(intercept) > 10):\r\n fintercept = '{:.2e}'.format(np.abs(intercept))\r\n else:\r\n fintercept = '%.2f' % (np.abs(intercept))\r\n if intercept > 0:\r\n fintercept = ' + ' + fintercept\r\n else:\r\n fintercept = ' - ' + fintercept\r\n fintercept += ppp(p_intercept)\r\n\r\n return r'$y = ' + fslope + r' \\times x' + fintercept + r'$'\r\n","sub_path":"tools/format_text.py","file_name":"format_text.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"629235114","text":"import tkinter\n\nroot = tkinter.Tk()\nlabel1 = tkinter.Label(root,text=\"label1\")\nlabel2 = tkinter.Label(root, text=\"label2\")\n\ntombol1 = tkinter.Button(root,text=\"tombol1\")\ntombol2 = tkinter.Button(root, text=\"tombol2\")\n#method positioning\nlabel1.pack()\nlabel2.pack()\ntombol1.pack()\ntombol2.pack()\n\n#method menampilkan GUI\nroot.mainloop()\n","sub_path":"oop/tkinter/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"76876145","text":"import pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\n\n# 使用RandomForestRegressor填补缺失的年龄属性\ndef set_miss_ages(df):\n # 把已有的数值型特征取出来丢进RandomForestRegressor中\n age_df = df[['age','pclass','embarked','sex']]\n\n # 乘客分成已知年龄和未知年龄两部分\n known_age = age_df[age_df.age.notnull()].values\n unknown_age = age_df[age_df.age.isnull()].values\n\n # y即目标年龄\n y = known_age[:, 0]\n\n # X即特征属性值\n X = known_age[:, 1:]\n\n # 建立训练模型并训练\n rfr = RandomForestRegressor(random_state=0, n_estimators=2000, n_jobs=-1)\n rfr.fit(X, y)\n\n # 用得到的模型进行未知年龄结果预测\n predictedAges = rfr.predict(unknown_age[:, 1::])\n\n # 用得到的预测结果填补原缺失数据\n df.loc[(df.age.isnull()), 'age'] = predictedAges\n\n return df\n\ntitanic = pd.read_csv(\"Titanic\\DataSet\\\\train\\\\titanicOut3.csv\")\n\ntitanic = set_miss_ages(titanic)\n\n# 将Embarked,Sex,Pclass转换成为one-hot编码\ndummies_embarked = pd.get_dummies(titanic['embarked'], prefix='embarked')\ndummies_sex = pd.get_dummies(titanic['sex'], prefix='sex')\ndummies_pclass = pd.get_dummies(titanic['pclass'], prefix= 'pclass')\n\ndf = pd.concat([titanic, dummies_embarked, dummies_sex, dummies_pclass], axis=1)\ndf.drop(['pclass','sex','embarked'], axis=1, inplace=True)\n\nprint(df)\ndf.to_csv(\"Titanic\\DataSet\\\\train\\\\titanicOut4.csv\", index=False)\n\n# 导入测试集\ntitanic_test = pd.read_csv(\"Titanic\\DataSet\\\\test\\\\testOut.csv\")\n\n# 填补缺失的年龄\ntitanic_test = set_miss_ages(titanic_test)\n\n# 将Embarked,Sex,Pclass转换成为one-hot编码\ndummies_embarked = pd.get_dummies(titanic_test['embarked'], prefix='embarked')\ndummies_sex = pd.get_dummies(titanic_test['sex'], prefix='sex')\ndummies_pclass = pd.get_dummies(titanic_test['pclass'], prefix= 'pclass')\n\ndf2 = pd.concat([titanic_test, dummies_embarked, dummies_sex, dummies_pclass], axis=1)\ndf2.drop(['pclass','sex','embarked'], axis=1, inplace=True)\n\nprint(df2)\ndf2.to_csv(\"Titanic\\DataSet\\\\test\\\\testOut2.csv\", index=False)","sub_path":"Titanic/DataProcessing/FittingMissingAgeData.py","file_name":"FittingMissingAgeData.py","file_ext":"py","file_size_in_byte":2111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"393949613","text":"#!/usr/bin/env python\n\n\"\"\"\n cifar10.py\n\"\"\"\n\nfrom __future__ import division, print_function\n\nimport sys\nimport json\nimport argparse\nimport numpy as np\nfrom time import time\nfrom PIL import Image\nfrom datetime import datetime\nfrom collections import OrderedDict\n\nfrom basenet import BaseNet\nfrom basenet.hp_schedule import HPSchedule\nfrom basenet.helpers import to_numpy, set_seeds\nfrom basenet.vision import transforms as btransforms\n\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom torch.autograd import Variable\ntorch.backends.cudnn.benchmark = True\n\nfrom torchvision import transforms, datasets\n\nimport dlib\n\n# --\n# Helpers\n\ndef dlib_find_max_global(f, bounds, **kwargs):\n varnames = f.__code__.co_varnames[:f.__code__.co_argcount]\n bound1_, bound2_ = [], []\n for varname in varnames:\n bound1_.append(bounds[varname][0])\n bound2_.append(bounds[varname][1])\n \n return dlib.find_max_global(f, bound1_, bound2_, **kwargs)\n\n\n# --\n# CLI\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--epochs', type=int, default=10)\n parser.add_argument('--weight-decay', type=float, default=5e-4)\n parser.add_argument('--momentum', type=float, default=0.9)\n parser.add_argument('--batch-size', type=int, default=128)\n parser.add_argument('--seed', type=int, default=789)\n parser.add_argument('--download', action=\"store_true\")\n return parser.parse_args()\n\n# --\n# Model definition\n# Derived from models in `https://github.com/kuangliu/pytorch-cifar`\n\nclass PreActBlock(nn.Module):\n \n def __init__(self, in_channels, out_channels, stride=1):\n super(PreActBlock, self).__init__()\n \n self.bn1 = nn.BatchNorm2d(in_channels)\n self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(out_channels)\n self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False)\n \n if stride != 1 or in_channels != out_channels:\n self.shortcut = nn.Sequential(\n nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False)\n )\n \n def forward(self, x):\n out = F.relu(self.bn1(x))\n shortcut = self.shortcut(out) if hasattr(self, 'shortcut') else x\n out = self.conv1(out)\n out = self.conv2(F.relu(self.bn2(out)))\n return out + shortcut\n\n\nclass ResNet18(BaseNet):\n def __init__(self, num_blocks=[2, 2, 2, 2], num_classes=10):\n super(ResNet18, self).__init__(loss_fn=F.cross_entropy)\n \n self.in_channels = 64\n \n self.prep = nn.Sequential(\n nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False),\n nn.BatchNorm2d(64),\n nn.ReLU()\n )\n \n self.layers = nn.Sequential(\n self._make_layer(64, 64, num_blocks[0], stride=1),\n self._make_layer(64, 128, num_blocks[1], stride=2),\n self._make_layer(128, 256, num_blocks[2], stride=2),\n self._make_layer(256, 256, num_blocks[3], stride=2),\n )\n \n self.classifier = nn.Linear(512, num_classes)\n \n def _make_layer(self, in_channels, out_channels, num_blocks, stride):\n \n strides = [stride] + [1] * (num_blocks-1)\n layers = []\n for stride in strides:\n layers.append(PreActBlock(in_channels=in_channels, out_channels=out_channels, stride=stride))\n in_channels = out_channels\n \n return nn.Sequential(*layers)\n \n def forward(self, x):\n x = self.prep(x)#.half())\n \n x = self.layers(x)\n \n x_avg = F.adaptive_avg_pool2d(x, (1, 1))\n x_avg = x_avg.view(x_avg.size(0), -1)\n \n x_max = F.adaptive_max_pool2d(x, (1, 1))\n x_max = x_max.view(x_max.size(0), -1)\n \n x = torch.cat([x_avg, x_max], dim=-1)\n \n x = self.classifier(x)\n \n return x\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n \n set_seeds(args.seed)\n \n # --\n # IO\n \n print('cifar_opt.py: making dataloaders...', file=sys.stderr)\n \n transform_train = transforms.Compose([\n btransforms.ReflectionPadding(margin=(4, 4)),\n transforms.RandomCrop(32),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n btransforms.NormalizeDataset(dataset='cifar10'),\n ])\n \n transform_test = transforms.Compose([\n transforms.ToTensor(),\n btransforms.NormalizeDataset(dataset='cifar10'),\n ])\n \n try:\n trainset = datasets.CIFAR10(root='./data', train=True, download=args.download, transform=transform_train)\n testset = datasets.CIFAR10(root='./data', train=False, download=args.download, transform=transform_test)\n except:\n raise Exception('cifar10.py: error loading data -- try rerunning w/ `--download` flag')\n \n trainloader = torch.utils.data.DataLoader(\n trainset,\n batch_size=args.batch_size,\n shuffle=True,\n num_workers=16,\n pin_memory=True,\n )\n \n testloader = torch.utils.data.DataLoader(\n testset,\n batch_size=512,\n shuffle=False,\n num_workers=16,\n pin_memory=True,\n )\n \n dataloaders = {\n \"train\" : trainloader,\n \"test\" : testloader,\n }\n \n def run_one(break1, break2, val1, val2):\n \n # try:\n # set_seeds(args.seed) # Might have bad side effects\n \n if (break1 >= break2):\n return float(-1)\n \n timestamp = datetime.now().strftime('%Y-%m-%dT%H:%M:%S')\n params = OrderedDict([\n (\"timestamp\", timestamp),\n (\"break1\", break1),\n (\"break2\", break2),\n (\"val1\", 10 ** val1),\n (\"val2\", 10 ** val2),\n (\"momentum\", args.momentum),\n (\"weight_decay\", args.weight_decay),\n ])\n \n model = ResNet18().cuda()#.half()\n \n lr_scheduler = HPSchedule.piecewise_linear(\n breaks=[0, break1, break2, args.epochs],\n vals=[0, 10 ** val1, 10 ** val2, 0]\n )\n \n model.init_optimizer(\n opt=torch.optim.SGD,\n params=model.parameters(),\n hp_scheduler={\"lr\" : lr_scheduler},\n momentum=args.momentum,\n weight_decay=args.weight_decay,\n nesterov=True,\n )\n \n t = time()\n for epoch in range(args.epochs):\n train = model.train_epoch(dataloaders, mode='train')\n test = model.eval_epoch(dataloaders, mode='test')\n \n res = OrderedDict([\n (\"params\", params),\n (\"epoch\", int(epoch)),\n (\"lr\", model.hp['lr']),\n (\"test_acc\", float(test['acc'])),\n (\"time\", time() - t),\n ])\n print(json.dumps(res))\n sys.stdout.flush()\n \n return float(test['acc'])\n # except:\n # return float(-1)\n \n print('cifar_opt.py: start', file=sys.stderr)\n best_args, best_score = dlib_find_max_global(run_one, bounds={\n \"break1\" : (0, args.epochs),\n \"break2\" : (0, args.epochs),\n \"val1\" : (-3, 0),\n \"val2\" : (-3, 0),\n }, num_function_calls=100, solver_epsilon=0.001)\n \n print(best_args, file=sys.stderr)\n print(best_score, file=sys.stderr)\n print('cifar_opt.py: done', file=sys.stderr)\n","sub_path":"examples/dev/cifar_opt/cifar_opt.py","file_name":"cifar_opt.py","file_ext":"py","file_size_in_byte":7824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"189006505","text":"import serial\nfrom matplotlib import pyplot as plt\nfrom drawnow import drawnow, figure\n\n\ndef draw_fig():\n plt.imshow(frame, interpolation='nearest', cmap=\"Greys_r\")\n\nw, h = 320, 200\nframe = [[0 for x in range(w)] for y in range(h)]\nfigure(figsize=(4, 3))\n\nwhile True:\n ser = serial.Serial('COM6', 921600, timeout=1)\n try:\n ser.write(chr(2).encode(encoding='UTF-8'))\n print(ser.read(1))\n print(ser.read(1))\n\n ser.write(chr(3).encode(encoding='UTF-8'))\n frame_data = ser.read(2**16);\n ser.close()\n print('line read')\n\n vpix = 0\n hline = 0\n i = 0\n\n while True:\n if hline < 200:\n if vpix < 320:\n #print(i)\n i += 1\n #print(int(frame_data[i]))\n frame[hline][vpix] = int(frame_data[i])\n vpix += 1\n else:\n vpix = 0\n hline += 1\n else:\n break\n\n drawnow(draw_fig)\n\n except:\n ser.close()\n print('Exception')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"71282317","text":"\"\"\"\nDemonstrates robust grasping policies with GQ-CNNS\nAuthor: Jeff Mahler\n\"\"\"\nimport argparse\nimport logging\nimport IPython\nimport numpy as np\nimport os\nimport sys\nimport time\n\nfrom autolab_core import RigidTransform, YamlConfig\nfrom perception import RgbdImage, RgbdSensorFactory\n\nfrom gqcnn import CrossEntropyAntipodalGraspingPolicy, RgbdImageState\nfrom gqcnn import Visualizer as vis\n\nif __name__ == '__main__':\n # set up logger\n logging.getLogger().setLevel(logging.DEBUG)\n\n # parse args\n parser = argparse.ArgumentParser(description='Capture a set of test images from the Kinect2')\n parser.add_argument('--config_filename', type=str, default='cfg/examples/policy.yaml', help='path to configuration file to use')\n args = parser.parse_args()\n config_filename = args.config_filename\n\n # read config\n config = YamlConfig(config_filename)\n sensor_type = config['sensor']['type']\n sensor_frame = config['sensor']['frame']\n inpaint_rescale_factor = config['inpaint_rescale_factor']\n policy_config = config['policy']\n\n # read camera calib\n tf_filename = '%s_to_world.tf' %(sensor_frame)\n T_camera_world = RigidTransform.load(os.path.join(config['calib_dir'], sensor_frame, tf_filename))\n\n # setup sensor\n sensor = RgbdSensorFactory.sensor(sensor_type, config['sensor'])\n sensor.start()\n camera_intr = sensor.ir_intrinsics\n\n # read images\n color_im, depth_im, _ = sensor.frames()\n color_im = color_im.inpaint(rescale_factor=inpaint_rescale_factor)\n depth_im = depth_im.inpaint(rescale_factor=inpaint_rescale_factor)\n rgbd_im = RgbdImage.from_color_and_depth(color_im, depth_im)\n state = RgbdImageState(rgbd_im, camera_intr)\n\n # init policy\n policy = CrossEntropyAntipodalGraspingPolicy(policy_config)\n policy_start = time.time()\n action = policy(state)\n logging.info('Planning took %.3f sec' %(time.time() - policy_start))\n\n # vis final grasp\n if policy_config['vis']['final_grasp']:\n vis.figure(size=(10,10))\n vis.subplot(1,2,1)\n vis.imshow(rgbd_im.color)\n vis.grasp(action.grasp, scale=1.5, show_center=False, show_axis=True)\n vis.title('Planned grasp on color (Q=%.3f)' %(action.q_value))\n vis.subplot(1,2,2)\n vis.imshow(rgbd_im.depth)\n vis.grasp(action.grasp, scale=1.5, show_center=False, show_axis=True)\n vis.title('Planned grasp on depth (Q=%.3f)' %(action.q_value))\n vis.show()\n\n","sub_path":"examples/policy.py","file_name":"policy.py","file_ext":"py","file_size_in_byte":2454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"386446521","text":"\"\"\"Problem: https://www.hackerrank.com/challenges/python-lists/problem\"\"\"\n\nif __name__ == '__main__':\n N = int(input())\n l = []\n \n for i in range(N):\n # Read in command, split by whitespace\n s = input().split()\n # Command is first in list, remainder are args\n command = s[0]\n arguments = [int(arg) for arg in s[1:]]\n \n # Print is not an attribute, call it separately\n if command == 'print':\n print(l)\n # Otherwise add attribute and args to list\n else: \n getattr(l, command)(*arguments)\n ","sub_path":"python/basic_data_types/list_commands.py","file_name":"list_commands.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"72520660","text":"\n# This will be useful to convert letter to ints\nfrom string import ascii_lowercase, ascii_uppercase\n\n# For mean/dev scaling. Important for PCA, and good practice in general\nfrom sklearn.preprocessing import StandardScaler\n\nimport os\n\nfrom collections import OrderedDict\n\nimport pandas as pd\n\nimport json\n\ndebug = False\n\ndef Scale(df, y='TARGET'):\n\n if debug:\n print(\"Doing StandardScaler\")\n\n# print(\"\\nInside Scale(): # of entries missing in data: \\n{0}\".format(df.isnull().sum()))\n scaler = StandardScaler()\n\n skcol = []\n for c in df.filter(regex='SK_ID*').columns:\n skcol.append(c)\n\n # Don't scale target column!!\n keepTarget = False\n if y in df.columns:\n print(\"mean of target column before handling: {0}\".format(df[y].mean()))\n keepTarget = True\n skcol.append(y)\n\n targetdf = df[skcol].copy()\n\n df = df.drop(columns=skcol)\n xcol = df.columns\n\n scaleddf = scaler.fit_transform(df)\n scaleddf = pd.DataFrame(scaleddf, columns = xcol)\n scaleddf['SK_ID_CURR'] = targetdf['SK_ID_CURR'].values \n\n scaleddf = scaleddf.merge( targetdf, on='SK_ID_CURR' )\n if debug:\n print(\"\\nInside Scale(): # rows in targetdf: {0}\".format(targetdf.shape))\n print(\"\\nInside Scale(): # rows in df: {0}\".format(df.shape))\n print(\"\\nInside Scale(): # rows in scaleddf: {0}\".format(scaleddf.shape))\n\n return scaleddf\n\n\ndef makeNameTokens(df, col, name_dict):\n\n numbervalue = name_dict.values()[-1] + 1\n for i,row in df.iterrows():\n name_cidx = df.columns.get_loc(col)\n name_str = str(row[name_cidx])\n\n if name_str not in name_dict.keys():\n if debug:\n print(\"Adding pair {0}:{1} to name dictionary\".format(name_str, numbervalue))\n name_dict[name_str] = numbervalue\n numbervalue += 1\n\n return name_dict\n\n\ndef tokenizeNames(df,col,namedict):\n\n newcol = df[col].replace(namedict, regex=True)\n return newcol\n\n\ndef preprocess(df, buildDictionaries):\n\n # test and xval df's are smaller, will run out of rows for high skipranges\n if df.shape[0] == 0:\n return df\n\n if debug:\n print(\"\\npreprocess (beginning): Number of entries missing in data: \\n{0}\".format(df.isnull().sum()))\n\n # Let's start with an ultrasimple na replace\n newdf = df.fillna(0)\n if debug:\n dtypeCount_x =[newdf.iloc[:,i].apply(type).value_counts() for i in range(newdf.shape[1])]\n print(dtypeCount_x)\n\n stringcols = []\n for c in newdf.columns[newdf.dtypes=='object']:\n stringcols.append(c)\n\n\n dictpath = \"dictionaries\"\n if buildDictionaries:\n for c in stringcols:\n \n # Name of dictionary file\n dictname = dictpath+\"/\"+c+\".txt\"\n \n if os.path.exists(dictname):\n with open(dictname) as f:\n c_dict = json.load(f)\n else:\n c_dict = {}\n c_dict[0] = 0\n \n if debug:\n print(\"Building dictionary for column {0} with example values:\\n{1}\".format(c, newdf[c].head()))\n \n c_dict = makeNameTokens(newdf, c, c_dict) # append dictionaries for each column\n \n # write the dictionary to file\n with open(dictname, 'w') as file:\n file.write(json.dumps(c_dict))\n\n # Now replace string columns with tokens\n for c in stringcols:\n # Name of dictionary file\n dictname = dictpath+\"/\"+c+\".txt\"\n\n if os.path.exists(dictname):\n with open(dictname) as f:\n c_dict = json.load(f)\n\n newdf = newdf.replace({c: c_dict})\n\n if debug:\n print(\"After tokenizing\")\n dtypeCount_x =[newdf.iloc[:,i].apply(type).value_counts() for i in range(newdf.shape[1])]\n print(dtypeCount_x)\n\n # Scale variables after strings have been converted\n newdf = Scale(newdf)\n\n if debug:\n print(\"\\npreprocess (end): Number of entries missing in data: \\n{0}\".format(newdf.isnull().sum()))\n\n return newdf\n","sub_path":"HCDRpreprocessing.py","file_name":"HCDRpreprocessing.py","file_ext":"py","file_size_in_byte":4130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"104832329","text":"#================================================================= \n# AE2220-II: Computational Modelling \n# TriFEMLib: A number of classes to assist in implementing\n# finite-element methods on meshes of triangles\n#================================================================= \nimport math\nimport numpy as np\nimport matplotlib.tri as tri\nimport matplotlib.pyplot as plt\n\n\n#=================================================================\n# TriOMesh class definition.\n# TriOMesh objects create and hold data for meshes of triangles for\n# circular or airfoil-shaped domains with a single hole. \n# Either structured algebraic or Delaunay triangulation can be used.\n# To use, create an empty object, set the parameters below \n# and call \"loadMesh\"\n#=================================================================\nclass TriOMesh(object):\n\n #=========================================================\n # Public data\n #=========================================================\n x1 = 0.0; # Left boundary position\n x2 = 5.0; # Right boundary position\n y1 = 0. ; # lower boundary position\n y2 = 2.0; # Upper boundary position\n dlx = 1.5; # Delamination x position\n dly = 0.5; # Delamination x position\n dlr = 0.4; # Delamination radius\n bnx = 20; # Background elements in x\n bny = 10; # Background elements in y\n permn = 1.0; # Nominal value of permittivity\n permd = 0.001; # Permittivity of delamination\n dx = (x2-x1)/float(bnx-1); # Mesh spacing in x\n dy = (y2-y1)/float(bny-1); # Mesh spacing in y\n minTriArea = (dx+dy)/10000.; # Minimum triangle size\n refine = 1; # Mesh refinement factor\n\n vertices = None; # Mesh Vertices as list\n vertArray = None; # Mesh Vertices as array\n elements = None; # Mesh Elements\n elemArray = None; # Mesh Elements as array\n nVert = None; # Number of vertArray\n nElem = None; # Number of elements\n dtri = None; # Delaunay triangulation\n mask = None; # Triangle mask\n leftVI = None; # Left boundary vertex list\n rightVI = None; # Right boundary vertex list\n lowerVI = None; # Lower boundary vertex list\n upperVI = None; # Upper boundary vertex list\n \n #=========================================================\n # Object constructor\n #=========================================================\n def __init__(self): \n created = 1;\n\n \n #=========================================================\n # Defines triangles removed from Delaunay triangulation\n #=========================================================\n def triMask(self,triangles):\n\n out = []\n self.elements = []\n for points in triangles:\n a,b,c = points\n va = self.vertices[a]\n vb = self.vertices[b]\n vc = self.vertices[c]\n x1 = float(va[0]); y1 = float(va[1]);\n x2 = float(vb[0]); y2 = float(vb[1]);\n x3 = float(vc[0]); y3 = float(vc[1]);\n Ae = 0.5*(x2*y3 + x1*y2 + x3*y1 - x3*y2 - x1*y3 - x2*y1);\n #if (Ae1.4):\n self.addDelam(5*n,10*n);\n \n self.nVert=len(self.vertices);\n self.vertArray = np.asarray(self.vertices);\n# self.smoothVert(2,0.01);\n\n # Use Delaunay triangulation and mask bnd-only elements\n self.dtri = tri.Triangulation(self.vertArray[:,0],self.vertArray[:,1]);\n self.mask = self.triMask(self.dtri.triangles)\n self.dtri.set_mask(self.mask);\n\n \n self.nElem=len(self.elements);\n self.elemArray=np.asarray(self.elements);\n\n\n #=========================================================\n # Adds a set of vertices to increase resolution near \n # the delamination\n #=========================================================\n def addDelam(self,dlnr,dlnt):\n\n rl = self.dlr*0.9\n dvr = rl/float(dlnr-2);\n\n # Add verticies\n for i in range(dlnr):\n vr = dvr*float(i+2);\n dti = 0.; \n if (i%2==0): dti = math.pi/float(dlnt);\n for j in range(dlnt):\n vt = dti + 2*math.pi*float(j)/float(dlnt);\n xv = self.dlx + vr*math.cos(vt);\n yv = self.dly + vr*math.sin(vt);\n self.vertices.append( (xv,yv) );\n\n\n #=========================================================\n # Returns the distribution of voltage across an electrode\n #=========================================================\n def getElectrodeDist(self,x,xe,le):\n return 0.5 + 0.5*math.cos((x-xe)*2.*math.pi/le);\n\n\n #=========================================================\n # Returns the local permittivity\n #=========================================================\n def getPerm(self,x,y):\n\n dx = x-self.dlx;\n dy = y-self.dly;\n dr = math.sqrt(dx*dx+dy*dy)\n if (self.dlx<1.4):\n perm=self.permn;\n elif (dr, Eric Ma, Charlie Harris\n# License: MIT\n# Project Website: https://github.com/a-r-j/graphein\n# Code Repository: https://github.com/a-r-j/graphein\nfrom __future__ import annotations\n\nimport logging\nfrom typing import Callable, List, Optional\n\nimport networkx as nx\nimport numpy as np\nimport pandas as pd\nfrom Bio.PDB.Polypeptide import three_to_one\nfrom biopandas.pdb import PandasPdb\n\nfrom graphein.protein.config import (\n DSSPConfig,\n GetContactsConfig,\n ProteinGraphConfig,\n)\nfrom graphein.protein.edges.distance import compute_distmat\nfrom graphein.protein.resi_atoms import BACKBONE_ATOMS\nfrom graphein.protein.utils import (\n filter_dataframe,\n get_protein_name_from_filename,\n three_to_one_with_mods,\n)\nfrom graphein.utils.utils import (\n annotate_edge_metadata,\n annotate_graph_metadata,\n annotate_node_metadata,\n compute_edges,\n)\n\n# from rdkit.Chem import MolFromPDBFile\n# from graphein.protein.visualisation import protein_graph_plot_3d\n\n\nlogging.basicConfig(level=\"DEBUG\")\nlog = logging.getLogger(__name__)\n\n\ndef read_pdb_to_dataframe(\n pdb_path: Optional[str] = None,\n pdb_code: Optional[str] = None,\n verbose: bool = False,\n granularity: str = \"CA\",\n) -> pd.DataFrame:\n \"\"\"\n Reads PDB file to PandasPDB object.\n\n Returns `atomic_df`, which is a dataframe enumerating all atoms and their cartesian coordinates in 3D space. Also\n contains associated metadata.\n\n :param pdb_path: path to PDB file. Defaults to None.\n :type pdb_path: str, optional\n :param pdb_code: 4-character PDB accession. Defaults to None.\n :type pdb_code: str, optional\n :param verbose: print dataframe?\n :type verbose: bool\n :param granularity: Specifies granularity of dataframe. See graphein.protein.config.ProteinGraphConfig for further\n details.\n :type granularity: str\n :returns: Pd.DataFrame containing protein structure\n :rtype: pd.DataFrame\n \"\"\"\n if pdb_code is None and pdb_path is None:\n raise NameError(\"One of pdb_code or pdb_path must be specified!\")\n\n atomic_df = (\n PandasPdb().read_pdb(pdb_path)\n if pdb_path is not None\n else PandasPdb().fetch_pdb(pdb_code)\n )\n\n # Assign Node IDs to dataframes\n atomic_df.df[\"ATOM\"][\"node_id\"] = (\n atomic_df.df[\"ATOM\"][\"chain_id\"].apply(str)\n + \":\"\n + atomic_df.df[\"ATOM\"][\"residue_name\"]\n + \":\"\n + atomic_df.df[\"ATOM\"][\"residue_number\"].apply(str)\n )\n if granularity == \"atom\":\n atomic_df.df[\"ATOM\"][\"node_id\"] = (\n atomic_df.df[\"ATOM\"][\"node_id\"]\n + \":\"\n + atomic_df.df[\"ATOM\"][\"atom_name\"]\n )\n if verbose:\n print(atomic_df)\n return atomic_df\n\n\ndef deprotonate_structure(df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Remove protons from PDB dataframe.\n\n :param df: Atomic dataframe.\n :type df: pd.DataFrame\n :returns: Atomic dataframe with all atom_name == \"H\" removed.\n :rtype: pd.DataFrame\n \"\"\"\n log.debug(\n \"Deprotonating protein. This removes H atoms from the pdb_df dataframe\"\n )\n # return df.loc[df[\"atom_name\"] != \"H\"].reset_index(drop=True)\n return filter_dataframe(\n df, by_column=\"atom_name\", list_of_values=[\"H\"], boolean=False\n )\n\n\ndef convert_structure_to_centroids(df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Overwrite existing (x, y, z) coordinates with centroids of the amino acids.\n\n :param df: Pandas Dataframe config protein structure to convert into a dataframe of centroid positions\n :type df: pd.DataFrame\n :return: pd.DataFrame with atoms/residues positiions converted into centroid positions\n :rtype: pd.DataFrame\n \"\"\"\n log.debug(\n \"Converting dataframe to centroids. This averages XYZ coords of the atoms in a residue\"\n )\n\n centroids = calculate_centroid_positions(df)\n df = df.loc[df[\"atom_name\"] == \"CA\"].reset_index(drop=True)\n df[\"x_coord\"] = centroids[\"x_coord\"]\n df[\"y_coord\"] = centroids[\"y_coord\"]\n df[\"z_coord\"] = centroids[\"z_coord\"]\n\n return df\n\n\ndef subset_structure_to_atom_type(\n df: pd.DataFrame, granularity: str\n) -> pd.DataFrame:\n \"\"\"\n Return a subset of atomic dataframe that contains only certain atom names.\n\n :param df: Protein Structure dataframe to subset\n :type df: pd.DataFrame\n :returns: Subsetted protein structure dataframe\n :rtype: pd.DataFrame\n \"\"\"\n return filter_dataframe(\n df, by_column=\"atom_name\", list_of_values=[granularity], boolean=True\n )\n # return df.loc[df[\"atom_name\"] == granularity]\n\n\ndef remove_insertions(df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"\n This function removes insertions from PDB dataframes\n\n :param df: Protein Structure dataframe to remove insertions from\n :type df: pd.DataFrame\n :return: Protein structure dataframe with insertions removed\n :rtype: pd.DataFrame\n \"\"\"\n \"\"\"Remove insertions from structure.\"\"\"\n # Remove alt_loc residues\n # Todo log.debug(f\"Detected X insertions\")\n # return df.loc[df[\"alt_loc\"].isin([\"\", \"A\"])]\n return filter_dataframe(\n df, by_column=\"alt_loc\", list_of_values=[\"\", \"A\"], boolean=True\n )\n\n\ndef filter_hetatms(\n df: pd.DataFrame, keep_hets: List[str]\n) -> List[pd.DataFrame]:\n \"\"\"Return hetatms of interest.\n\n :param df: Protein Structure dataframe to filter hetatoms from.\n :type df: pd.DataFrame\n :param keep_hets: List of hetero atom names to keep\n :returns: Protein structure dataframe with heteroatoms removed\n :rtype pd.DataFrame\n \"\"\"\n hetatms_to_keep = []\n for hetatm in keep_hets:\n hetatms_to_keep.append(df.loc[df[\"residue_name\"] == hetatm])\n return hetatms_to_keep\n\n\ndef compute_rgroup_dataframe(pdb_df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Return the atoms that are in R-groups and not the backbone chain.\n\n :param pdb_df: DataFrame to compute R group dataframe from\n :type pdb_df: pd.DataFrame\n :returns: Dataframe containing R-groups only (backbone atoms removed)\n :rtype: pd.DataFrame\n \"\"\"\n rgroup_df = filter_dataframe(pdb_df, \"atom_name\", BACKBONE_ATOMS, False)\n return rgroup_df\n\n\ndef process_dataframe(\n protein_df: pd.DataFrame,\n atom_df_processing_funcs: Optional[List[Callable]] = None,\n hetatom_df_processing_funcs: Optional[List[Callable]] = None,\n granularity: str = \"centroids\",\n chain_selection: str = \"all\",\n insertions: bool = False,\n deprotonate: bool = True,\n keep_hets: List[str] = [],\n verbose: bool = False,\n) -> pd.DataFrame:\n \"\"\"\n Process ATOM and HETATM dataframes to produce singular dataframe used for graph construction\n\n :param protein_df: Dataframe to process.\n Should be the object returned from `read_pdb_to_dataframe`.\n :type protein_df: pd.DataFrame\n :param atom_df_processing_funcs: List of functions to process dataframe. These must take in a dataframe and return a\n dataframe. Defaults to None.\n :type atom_df_processing_funcs: List[Callable], optional\n :param hetatom_df_processing_funcs: List of functions to process dataframe. These must take in a dataframe and return a dataframe\n :type hetatom_df_processing_funcs: List[Callable], optional\n :param granularity: The level of granualrity for the graph.\n This determines the node definition.\n Acceptable values include:\n - \"centroids\"\n - \"atoms\"\n - any of the atom_names in the PDB file (e.g. \"CA\", \"CB\", \"OG\", etc.)\n :type granularity: str\n :param insertions: Whether or not to keep insertions.\n :param insertions: bool\n :param deprotonate: Whether or not to remove hydrogen atoms (i.e. deprotonation).\n :type deprotonate: bool\n :param keep_hets: Hetatoms to keep. Defaults to an empty list.\n To keep a hetatom, pass it inside a list of hetatom names to keep.\n :type keep_hets: List[str]\n :param verbose: Verbosity level.\n :type verbose: bool\n :param chain_selection: Which protein chain to select. Defaults to \"all\". Eg can use \"ACF\"\n to select 3 chains (A, C & F :)\n :type chain_selection: str\n :return: A protein dataframe that can be consumed by\n other graph construction functions.\n :rtype: pd.DataFrame\n \"\"\"\n # TODO: Need to properly define what \"granularity\" is supposed to do.\n atoms = protein_df.df[\"ATOM\"]\n hetatms = protein_df.df[\"HETATM\"]\n\n # This block enables processing via a list of supplied functions operating on the atom and hetatom dataframes\n # If these are provided, the dataframe returned will be computed only from these and the default workflow\n # below this block will not execute.\n if atom_df_processing_funcs is not None:\n for func in atom_df_processing_funcs:\n atoms = func(atoms)\n if hetatom_df_processing_funcs is None:\n return atoms\n\n if hetatom_df_processing_funcs is not None:\n for func in hetatom_df_processing_funcs:\n hetatms = func(hetatms)\n return pd.concat([atoms, hetatms])\n\n # Deprotonate structure by removing H atoms\n if deprotonate:\n atoms = deprotonate_structure(atoms)\n\n # Restrict DF to desired granularity\n if granularity == \"centroids\":\n atoms = convert_structure_to_centroids(atoms)\n # elif granularity == \"atom\":\n # atoms = atoms\n else:\n atoms = subset_structure_to_atom_type(atoms, granularity)\n\n protein_df = atoms\n\n if len(keep_hets) > 0:\n hetatms_to_keep = filter_hetatms(atoms, keep_hets)\n protein_df = pd.concat([atoms, hetatms_to_keep])\n\n # Remove alt_loc residues\n if not insertions:\n protein_df = remove_insertions(protein_df)\n\n # perform chain selection\n protein_df = select_chains(\n protein_df, chain_selection=chain_selection, verbose=verbose\n )\n\n \"\"\"\n # Name nodes\n protein_df[\"node_id\"] = (\n protein_df[\"chain_id\"].apply(str)\n + \":\"\n + protein_df[\"residue_name\"]\n + \":\"\n + protein_df[\"residue_number\"].apply(str)\n )\n if granularity == \"atom\":\n protein_df[\"node_id\"] = (\n protein_df[\"node_id\"] + \":\" + protein_df[\"atom_name\"]\n )\n \"\"\"\n\n log.debug(f\"Detected {len(protein_df)} total nodes\")\n\n return protein_df\n\n\ndef assign_node_id_to_dataframe(\n protein_df: pd.DataFrame, granularity: str\n) -> pd.DataFrame:\n \"\"\"\n Assigns the node ID back to the pdb_df dataframe\n\n :param protein_df: Structure Dataframe\n :type protein_df: pd.DataFrame\n :param granularity: Granularity of graph. Atom-level, resiidue (e.g. CA) or centroids\n :type granularity: str\n :return: Returns dataframe with added node_ids\n :rtype: pd.DataFrame\n \"\"\"\n protein_df[\"node_id\"] = (\n protein_df[\"chain_id\"].apply(str)\n + \":\"\n + protein_df[\"residue_name\"]\n + \":\"\n + protein_df[\"residue_number\"].apply(str)\n )\n if granularity == \"atom\":\n protein_df[\"node_id\"] = (\n protein_df[\"node_id\"] + \":\" + protein_df[\"atom_name\"]\n )\n\n\ndef select_chains(\n protein_df: pd.DataFrame, chain_selection: str, verbose: bool = False\n) -> pd.DataFrame:\n \"\"\"\n Extracts relevant chains from protein_df\n\n :param protein_df: pandas dataframe of PDB subsetted to relevant atoms (CA, CB)\n :type protein_df: pd.DataFrame\n :param chain_selection: Specifies chains that should be extracted from the larger complexed structure\n :type chain_selection: str\n :param verbose: Print dataframe\n :type verbose: bool\n :return Protein structure dataframe containing only entries in the chain selection\n :rtype: pd.DataFrame\n \"\"\"\n if chain_selection != \"all\":\n protein_df = filter_dataframe(\n protein_df,\n by_column=\"chain_id\",\n list_of_values=list(chain_selection),\n boolean=True,\n )\n\n return protein_df\n\n\ndef initialise_graph_with_metadata(\n protein_df: pd.DataFrame,\n raw_pdb_df: pd.DataFrame,\n pdb_id: str,\n granularity: str,\n) -> nx.Graph:\n \"\"\"\n Initialises the nx Graph object with initial metadata\n\n :param protein_df: Processed Dataframe of protein structure\n :type protein_df: pd.DataFrame\n :param raw_pdb_df: Unprocessed dataframe of protein structure for comparison and traceability downstream\n :type raw_pdb_df: pd.DataFrame\n :param pdb_id: PDB Accession code\n :type pdb_id: str\n :param granularity: Granularity of the graph (eg \"atom\", \"CA\", \"CB\" etc or \"centroid\")\n :type granularity: str\n :return: Returns initial protein structure graph with metadata\n :rtype: nx.Graph\n \"\"\"\n G = nx.Graph(\n name=pdb_id,\n pdb_id=pdb_id,\n chain_ids=list(protein_df[\"chain_id\"].unique()),\n pdb_df=protein_df,\n raw_pdb_df=raw_pdb_df,\n rgroup_df=compute_rgroup_dataframe(raw_pdb_df),\n coords=np.asarray(protein_df[[\"x_coord\", \"y_coord\", \"z_coord\"]]),\n )\n\n # Create graph and assign intrinsic graph-level metadata\n G.graph[\"node_type\"] = granularity\n\n # Add Sequences to graph metadata\n for c in G.graph[\"chain_ids\"]:\n G.graph[f\"sequence_{c}\"] = (\n protein_df.loc[protein_df[\"chain_id\"] == c][\"residue_name\"]\n .apply(three_to_one_with_mods)\n .str.cat()\n )\n return G\n\n\ndef add_nodes_to_graph(\n G: nx.Graph,\n protein_df: Optional[pd.DataFrame] = None,\n verbose: bool = False,\n) -> nx.Graph:\n \"\"\"Add nodes into protein graph.\n\n :param G: nx.Graph with metadata to populate with nodes\n :type G: nx.Graph\n :protein_df: DataFrame of protein structure containing nodes & initial node metadata to add to the graph\n :type protein_df: pd.DataFrame, optional\n :param verbose: Controls verbosity of this step\n :type verbose: bool\n :returns: nx.Graph with nodes added\n :rtype: nx.Graph\n \"\"\"\n\n # If no protein dataframe is supplied, use the one stored in the Graph object\n if protein_df is None:\n protein_df = G.graph[\"pdb_df\"]\n # Assign intrinsic node attributes\n chain_id = protein_df[\"chain_id\"].apply(str)\n residue_name = protein_df[\"residue_name\"]\n residue_number = protein_df[\"residue_number\"] # .apply(str)\n coords = np.asarray(protein_df[[\"x_coord\", \"y_coord\", \"z_coord\"]])\n b_factor = protein_df[\"b_factor\"]\n atom_type = protein_df[\"atom_name\"]\n nodes = protein_df[\"node_id\"]\n element_symbol = protein_df[\"element_symbol\"]\n G.add_nodes_from(nodes)\n\n # Set intrinsic node attributes\n nx.set_node_attributes(G, dict(zip(nodes, chain_id)), \"chain_id\")\n nx.set_node_attributes(G, dict(zip(nodes, residue_name)), \"residue_name\")\n nx.set_node_attributes(\n G, dict(zip(nodes, residue_number)), \"residue_number\"\n )\n nx.set_node_attributes(G, dict(zip(nodes, atom_type)), \"atom_type\")\n nx.set_node_attributes(\n G, dict(zip(nodes, element_symbol)), \"element_symbol\"\n )\n nx.set_node_attributes(G, dict(zip(nodes, coords)), \"coords\")\n nx.set_node_attributes(G, dict(zip(nodes, b_factor)), \"b_factor\")\n\n # TODO: include charge, line_idx for traceability?\n if verbose:\n print(nx.info(G))\n print(G.nodes())\n\n return G\n\n\ndef calculate_centroid_positions(\n atoms: pd.DataFrame, verbose: bool = False\n) -> pd.DataFrame:\n \"\"\"\n Calculates position of sidechain centroids\n\n :param atoms: ATOM df of protein structure\n :type atoms: pd.DataFrame\n :param verbose: bool controlling verbosity\n :type verbose: bool\n :return: centroids (df)\n :rtype: pd.DataFrame\n \"\"\"\n centroids = (\n atoms.groupby(\"residue_number\")\n .mean()[[\"x_coord\", \"y_coord\", \"z_coord\"]]\n .reset_index()\n )\n if verbose:\n print(f\"Calculated {len(centroids)} centroid nodes\")\n log.debug(f\"Calculated {len(centroids)} centroid nodes\")\n return centroids\n\n\ndef compute_edges(\n G: nx.Graph,\n funcs: List[Callable],\n get_contacts_config: Optional[GetContactsConfig] = None,\n) -> nx.Graph:\n \"\"\"\n Computes edges for the protein structure graph. Will compute an pairwise distance matrix between nodes which is\n added to the graph metadata to facilitate some edge computations.\n\n :param G: nx.Graph with nodes to add edges to\n :type G: nx.Graph\n :param funcs: List of edge construction functions\n :type funcs: List[Callable]\n :param get_contacts_config: Config object for getcontacts if intramolecular edges are being used\n :type get_contacts_config: graphein.protein.config.GetContactsConfig\n :return: Graph with added edges\n :rtype: nx.Graph\n \"\"\"\n # This control flow prevents unnecessary computation of the distance matrices\n if \"config\" in G.graph:\n if G.graph[\"config\"].granularity == \"atom\":\n G.graph[\"atomic_dist_mat\"] = compute_distmat(G.graph[\"raw_pdb_df\"])\n else:\n G.graph[\"dist_mat\"] = compute_distmat(G.graph[\"pdb_df\"])\n\n for func in funcs:\n func(G)\n\n return G\n\n\ndef construct_graph(\n config: Optional[ProteinGraphConfig] = None,\n pdb_path: Optional[str] = None,\n pdb_code: Optional[str] = None,\n chain_selection: str = \"all\",\n df_processing_funcs: Optional[List[Callable]] = None,\n edge_construction_funcs: Optional[List[Callable]] = None,\n edge_annotation_funcs: Optional[List[Callable]] = None,\n node_annotation_funcs: Optional[List[Callable]] = None,\n graph_annotation_funcs: Optional[List[Callable]] = None,\n) -> nx.Graph:\n \"\"\"\n Constructs protein structure graph from a pdb_code or pdb_path. Users can provide a ProteinGraphConfig object.\n\n However, config parameters can be overridden by passing arguments directly to the function.\n\n :param config: ProteinGraphConfig object. If None, defaults to config in graphein.protein.config\n :type config: graphein.protein.config.ProteinGraphConfig, optional\n :param pdb_path: Path to pdb_file to build graph from\n :type pdb_path: str, optional\n :param pdb_code: 4-character PDB accession pdb_code to build graph from\n :type pdb_code: str, optional\n :param chain_selection: String of polypeptide chains to include in graph. E.g \"ABDF\" or \"all\"\n :type chain_selection: str, optional\n :param df_processing_funcs: List of dataframe processing functions\n :type df_processing_funcs: List[Callable], optional\n :param edge_construction_funcs: List of edge construction functions\n :type edge_construction_funcs: List[Callable], optional\n :param edge_annotation_funcs: List of edge annotation functions\n :type edge_annotation_funcs: List[Callable], optional\n :param node_annotation_funcs: List of node annotation functions\n :type node_annotation_funcs: List[Callable], optional\n :param graph_annotation_funcs: List of graph annotation function\n :type graph_annotation_funcs: List[Callable]\n :return: Protein Structure Graph\n :type: nx.Graph\n \"\"\"\n\n # If no config is provided, use default\n if config is None:\n config = ProteinGraphConfig()\n\n # Get name from pdb_file is no pdb_code is provided\n if pdb_path and (pdb_code is None):\n pdb_code = get_protein_name_from_filename(pdb_path)\n\n # If config params are provided, overwrite them\n config.protein_df_processing_functions = (\n df_processing_funcs\n if config.protein_df_processing_functions is None\n else config.protein_df_processing_functions\n )\n config.edge_construction_functions = (\n edge_construction_funcs\n if config.edge_construction_functions is None\n else config.edge_construction_functions\n )\n config.node_metadata_functions = (\n node_annotation_funcs\n if config.node_metadata_functions is None\n else config.node_metadata_functions\n )\n config.graph_metadata_functions = (\n graph_annotation_funcs\n if config.graph_metadata_functions is None\n else config.graph_metadata_functions\n )\n config.edge_metadata_functions = (\n edge_annotation_funcs\n if config.edge_metadata_functions is None\n else config.edge_metadata_functions\n )\n\n raw_df = read_pdb_to_dataframe(\n pdb_path,\n pdb_code,\n verbose=config.verbose,\n granularity=config.granularity,\n )\n protein_df = process_dataframe(\n raw_df, chain_selection=chain_selection, granularity=config.granularity\n )\n\n # Initialise graph with metadata\n g = initialise_graph_with_metadata(\n protein_df=protein_df,\n raw_pdb_df=raw_df.df[\"ATOM\"],\n pdb_id=pdb_code,\n granularity=config.granularity,\n )\n # Add nodes to graph\n g = add_nodes_to_graph(g)\n\n # Add config to graph\n g.graph[\"config\"] = config\n\n # Annotate additional node metadata\n if config.node_metadata_functions is not None:\n g = annotate_node_metadata(g, config.node_metadata_functions)\n\n # Compute graph edges\n g = compute_edges(\n g,\n funcs=config.edge_construction_functions,\n get_contacts_config=None,\n )\n\n # Annotate additional graph metadata\n if config.graph_metadata_functions is not None:\n g = annotate_graph_metadata(g, config.graph_metadata_functions)\n\n # Annotate additional edge metadata\n if config.edge_metadata_functions is not None:\n g = annotate_edge_metadata(g, config.edge_metadata_functions)\n\n return g\n\n\nif __name__ == \"__main__\":\n from functools import partial\n\n from graphein.protein.edges.distance import add_k_nn_edges\n from graphein.protein.features.sequence.sequence import molecular_weight\n\n configs = {\n \"granularity\": \"CA\",\n \"keep_hets\": False,\n \"insertions\": False,\n \"verbose\": False,\n \"get_contacts_config\": GetContactsConfig(),\n \"dssp_config\": DSSPConfig(),\n \"graph_metadata_functions\": [molecular_weight],\n }\n config = ProteinGraphConfig(**configs)\n config.edge_construction_functions = [\n partial(add_k_nn_edges, k=3, long_interaction_threshold=0)\n ]\n # Test High-level API\n g = construct_graph(\n config=config,\n pdb_path=\"../examples/pdbs/3eiy.pdb\",\n )\n\n \"\"\"\n # Test Low-level API\n raw_df = read_pdb_to_dataframe(\n pdb_path=\"../../examples/pdbs/3eiy.pdb\",\n verbose=config.verbose,\n )\n\n processed_pdb_df = process_dataframe(\n protein_df=raw_df,\n atom_df_processing_funcs=None,\n hetatom_df_processing_funcs=None,\n granularity=\"centroids\",\n chain_selection=\"all\",\n insertions=False,\n deprotonate=True,\n keep_hets=[],\n verbose=False,\n )\n\n g = initialise_graph_with_metadata(\n protein_df=processed_pdb_df,\n raw_pdb_df=raw_df.df[\"ATOM\"],\n pdb_id=\"3eiy\",\n granularity=config.granularity,\n )\n\n g = add_nodes_to_graph(g)\n\n g = annotate_node_metadata(g, [expasy_protein_scale, meiler_embedding])\n g = compute_edges(\n g,\n config.get_contacts_config,\n [\n add_delaunay_triangulation,\n peptide_bonds,\n salt_bridge,\n add_hydrogen_bond_interactions,\n ],\n )\n\n g = annotate_graph_metadata(\n g,\n [\n esm_sequence_embedding,\n biovec_sequence_embedding,\n molecular_weight,\n ],\n )\n\n print(nx.info(g))\n colors = nx.get_edge_attributes(g, \"color\").values()\n \"\"\"\n \"\"\"\n nx.draw(\n g,\n # pos = nx.circular_layout(g),\n edge_color=colors,\n with_labels=True,\n )\n plt.show()\n \"\"\"\n","sub_path":"graphein/protein/graphs.py","file_name":"graphs.py","file_ext":"py","file_size_in_byte":23613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"266963061","text":"from django.conf.urls import include, url\nfrom django.contrib.auth.decorators import login_required, permission_required\n\nfrom .views import *\n\nurlpatterns = [\n url(r'^$', AlbumListView.as_view(), name='album_list_view'),\n url(r'^photos/$', PhotoListView.as_view(), name='photo_list_view'),\n url(r'^(?P[\\-\\d\\w]+)/$', AlbumDetailView.as_view(), name='album_detail_view'),\n # url(r'^photo/(?P[\\-\\d\\w]+)/(?P[\\-\\d\\w]+)$', PhotoDetailView.as_view(), name='photo_detail_view'),\n url(r'''^(?:(?P[^/]+))'''\n r'''(?:\\/(?P[^/]+))?$''',\n PhotoDetailView.as_view(), name='photo_detail_view'),\n url(r'^photo/(?P[\\-\\d\\w]+)$', PhotoDetailView.as_view(), name='photo_detail_view'),\n url(r'^photo/create/$', PhotoCreateView.as_view(), name='photo_create_view'),\n # url(r'^photo/create/$', AjaxPhotoUploadView.as_view(), name='photo_upload_view'),\n url(r'^photo/edit/(?P[\\-\\d\\w]+)$', PhotoUpdateView.as_view(), name='photo_edit_view'),\n url(r'^photo/delete/(?P[\\-\\d\\w]+)$', PhotoDeleteView.as_view(), name='photo_delete_view'),\n url(r'^album/create/$', AlbumCreateView.as_view(), name='album_create_view'),\n url(r'^album/edit/(?P[\\-\\d\\w]+)$', AlbumUpdateView.as_view(), name='album_edit_view'),\n url(r'^album/delete/(?P[\\-\\d\\w]+)$', AlbumDeleteView.as_view(), name='album_delete_view'),\n]\n\n ","sub_path":"gallery/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"41489403","text":"from django.core import mail\nfrom selenium.webdriver.common.keys import Keys\nimport re\n\nfrom functional_tests.base import FunctionalTest\n\nTEST_EMAIL = '1091889012@qq.com'\nSUBJECT = 'Your login link for Superlists'\n\n\nclass LoginTest(FunctionalTest):\n def test_can_get_email_link_to_log_in(self):\n # 伊迪丝访问这个很棒的超级列表网站\n # 第一次注意到导航栏有登录区域\n # 看到要求输入电子邮件地址,她便输入了\n self.browser.get(self.live_server_url)\n self.browser.find_element_by_name('email').send_keys(TEST_EMAIL)\n self.browser.find_element_by_name('email').send_keys(Keys.ENTER)\n\n # 出现一条消息,告诉她邮件已经发出\n self.wait_for(lambda: self.assertIn(\n 'Check your email',\n self.browser.find_element_by_tag_name('body').text\n ))\n\n # 她查看邮件,看到一条消息\n email = mail.outbox[0]\n self.assertIn(TEST_EMAIL, email.to)\n self.assertEqual(email.subject, SUBJECT)\n\n # 邮件中有个URL链接\n self.assertIn('Use this link to log in', email.body)\n url_search = re.search(r'http://.+/.+$', email.body)\n if not url_search:\n self.fail('Could not find url in email body:\\n'+email.body)\n url = url_search.group(0)\n self.assertIn(self.live_server_url, url)\n\n # 她点击了链接\n self.browser.get(url)\n\n # 她登录了\n self.wait_for(\n lambda: self.browser.find_element_by_link_text('Log out')\n )\n navbar=self.browser.find_element_by_css_selector('.navbar')\n self.assertIn(TEST_EMAIL, navbar.text)\n\n # 现在她要退出\n self.wait_for(\n lambda :self.browser.find_element_by_link_text('Log out').click()\n )\n # 她退出了\n self.wait_for(\n lambda :self.browser.find_element_by_name('email')\n )\n navbar=self.browser.find_element_by_css_selector('.navbar')\n self.assertNotIn(TEST_EMAIL,navbar.text)\n","sub_path":"functional_tests/test_login.py","file_name":"test_login.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"398092929","text":"import sys\nimport os\n\n# Using https://stackoverflow.com/questions/51520/how-to-get-an-absolute-file-path-in-python\nutils_path = os.path.abspath(\"utils\")\n\n# Using https://askubuntu.com/questions/470982/how-to-add-a-python-module-to-syspath/471168\nsys.path.insert(0, utils_path)\n\nimport getROICOG as roicog\nfrom atlasUtility import queryAtlas\nimport nibabel as nib\nimport numpy as np\n\n\"\"\"\nThe folowing script goes through the AAL atlas index locations and finds\nthe COG for each of the region and check if it lies inside the region or not.\n\"\"\"\n\nAALROIindex = [\"2001\", \"2002\", \"2101\", \"2102\", \"2111\", \"2112\", \"2201\", \"2202\", \"2211\", \"2212\", \"2301\", \"2302\", \"2311\", \"2312\", \"2321\", \"2322\", \"2331\", \"2332\", \"2401\", \"2402\", \"2501\", \"2502\", \"2601\", \"2602\",\n \"2611\", \"2612\", \"2701\", \"2702\", \"3001\", \"3002\", \"4001\", \"4002\", \"4011\", \"4012\", \"4021\", \"4022\", \"4101\", \"4102\", \"4111\", \"4112\", \"4201\", \"4202\", \"5001\", \"5002\", \"5011\", \"5012\", \"5021\", \"5022\", \"5101\",\n \"5102\", \"5201\", \"5202\", \"5301\", \"5302\", \"5401\", \"5402\", \"6001\", \"6002\", \"6101\", \"6102\", \"6201\", \"6202\", \"6211\", \"6212\", \"6221\", \"6222\", \"6301\", \"6302\", \"6401\", \"6402\", \"7001\", \"7002\", \"7011\", \"7012\",\n \"7021\", \"7022\", \"7101\", \"7102\", \"8101\", \"8102\", \"8111\", \"8112\", \"8121\", \"8122\", \"8201\", \"8202\", \"8211\", \"8212\", \"8301\", \"8302\", \"9001\", \"9002\", \"9011\", \"9012\", \"9021\", \"9022\", \"9031\", \"9032\", \"9041\",\n \"9042\", \"9051\", \"9052\", \"9061\", \"9062\", \"9071\", \"9072\", \"9081\", \"9082\", \"9100\", \"9110\", \"9120\", \"9130\", \"9140\", \"9150\", \"9160\", \"9170\"]\n\n\natlas = '/home/varun/Projects/fmri/Autism-survey-connectivity-links-analysis/aalAtlas/AAL.nii'\n\nbrain = nib.load(atlas).get_data()\n\nobj = roicog.getROICOG(atlas)\n\n\ndef getNearestVoxel(brain_data, roi, COG):\n roi_mask = np.zeros(brain_data.shape)\n roi_mask[np.where(brain_data == roi)] = 1\n roiCoord = np.where(roi_mask == 1)\n\n peak_list = []\n dist = float(np.inf)\n for [x, y, z] in zip(roiCoord[0], roiCoord[1], roiCoord[2]):\n peak = [x, y, z]\n current_dist = abs(x - COG[0]) + abs(y - COG[1]) + abs(z - COG[2])\n if current_dist < dist:\n if len(peak_list) != 0:\n peak_list = []\n peak_list.append(peak)\n dist = current_dist\n elif current_dist == dist:\n peak_list.append(peak)\n dist = current_dist\n\n # The above 'For loop' might result in miltiple peak coordinates(peak list)\n # having same distance from COG Check which of the peak list has least\n # x coordinate i.e closest to midline (My heuristic) to select one peak\n\n x = float(np.inf)\n res = []\n for coordinates in peak_list:\n current_x = abs(coordinates[0])\n if current_x < x:\n res = []\n res.append(coordinates)\n elif current_x == x:\n res.append(coordinates)\n else:\n pass\n\n # Find the MNI coordinates of the peak coordinates\n MNI = []\n for res_peak in res:\n MNI.append(queryAtlas.XYZ2MNI2mm(res_peak))\n\n return MNI\n\n\nfor roi in AALROIindex:\n roi = int(roi)\n COG = obj.getCOG(roi)\n COG = [int(COG[0]), int(COG[1]), int(COG[2])]\n print('Index %s : %s' % (roi, COG))\n XYZ = queryAtlas.MNI2XYZ2mm(COG)\n if brain[XYZ[0], XYZ[1], XYZ[2]] != roi:\n print('COG Lies outside for ROI Index %s' % roi)\n newCOG = getNearestVoxel(brain, roi, XYZ)[0]\n print('Index %s : %s (Modified)' % (roi, newCOG))\n","sub_path":"utils/getAALCOG.py","file_name":"getAALCOG.py","file_ext":"py","file_size_in_byte":3454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"555274808","text":"#!/usr/bin/env python\nimport rospy\nfrom sensor_msgs.msg import JointState\nimport copy\nimport numpy as np\n\nclass JV_Estimator:\n def __init__(self):\n rospy.init_node('jv_estimator')\n # Subscriber to /joint_states\n rospy.Subscriber('joint_states', JointState, self.callbackJS, queue_size=1)\n # Publisher of /estimated_joint_states\n self.js_pub = rospy.Publisher('estimated_joint_states', JointState, queue_size=10)\n # Buffer storing previous joint positions\n self.previous_j_pos = None\n # Buffer storing previous joint velocities\n self.previous_j_vel = 0\n\n rospy.spin()\n\n def callbackJS(self,data):\n if self.previous_j_pos is None:\n self.previous_j_pos = copy.deepcopy(data.position)\n self.js_pub.publish(data)\n else:\n velocities = self.filtering_derivative(self.previous_j_pos,data.position,self.previous_j_vel,0.008,0.01)\n data.velocity = copy.deepcopy(velocities)\n self.js_pub.publish(data)\n self.previous_j_pos = copy.deepcopy(data.position)\n\n def filtering_derivative(self, q_t0, q_t1, previous_dq_dt,T_signal, T_filter):\n \"\"\"Short summary.\n\n An higher time contant for the filter gives a smoothter derivative with higher delay.\n\n Args:\n q_t0 (type): Description of parameter `q_t0`.\n q_t1 (type): Description of parameter `q_t1`.\n T_signal (type): Description of parameter `T_signal`.\n T_filter (type): Time constant of filter.\n\n Returns:\n type: Description of returned object.\n\n \"\"\"\n a = T_signal/(T_filter + T_signal)\n dq = np.subtract(np.array(q_t1),np.array(q_t0))\n dt = np.full(len(q_t0),T_signal)\n dq_dt = np.divide(dq,dt)\n\n filtered_dq_dt = (1-a)*np.array(previous_dq_dt) + a*dq_dt\n\n return filtered_dq_dt\n\n\n\n\nif __name__ == '__main__':\n try:\n jv_estimator = JV_Estimator()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"ur_robot_server/scripts/joint_velocity_estimator.py","file_name":"joint_velocity_estimator.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"561959935","text":"from uvicorn.importer import import_from_string\nfrom uvicorn.main import Server\nfrom uvicorn.config import Config\nfrom uvicorn.supervisors import Multiprocess, StatReload\n\nfrom aioli.log import setup_logging\n\n\nclass UvicornServer(Server):\n def __init__(self, app_path, *args, **kwargs):\n super(UvicornServer, self).__init__(*args, **kwargs)\n self.app_path = app_path\n\n def run(self, *args, **kwargs):\n app = import_from_string(self.app_path)\n setup_logging(level=self.config.log_level.upper())\n app.load_units()\n\n super().run(*args, **kwargs)\n\n\ndef uvicorn_server(app_path, **kwargs):\n config = Config(app_path, **kwargs)\n setup_logging(level=config.log_level.upper())\n server = UvicornServer(app_path, config=config)\n\n if config.reload and not isinstance(app_path, str):\n config.logger_instance.warn(\n \"auto-reload only works when app is passed as an import string.\"\n )\n\n if isinstance(app_path, str) and (config.debug or config.reload):\n socket = config.bind_socket()\n supervisor = StatReload(config)\n supervisor.run(server.run, sockets=[socket])\n elif config.workers > 1:\n socket = config.bind_socket()\n supervisor = Multiprocess(config)\n supervisor.run(server.run, sockets=[socket])\n else:\n server.run()\n","sub_path":"aioli/servers.py","file_name":"servers.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"535364578","text":"import nltk\nimport math \nimport operator\nimport numpy as np\nfrom pickle import dump, load\nfrom bs4 import BeautifulSoup\nfrom nltk.corpus import cess_esp\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import RegexpTokenizer,sent_tokenize\n\n'''\n+-----------------------------------------------------------------------+\n| |\n| This program obtains the context of one word |\n| and found the words similarity it. Using the |\n| Syntagmatic Relations of the words and |\n| Conditional Entropy |\n| |\n+-----------------------------------------------------------------------+\n'''\n\ndef cleaningText(text):\n soup = BeautifulSoup(text, 'lxml') \n text = soup.get_text()\n return text\n\ndef openText():\n f = open('../../Corpus/e961024.htm', encoding = 'utf-8')\n text = f.read()\n f.close()\n return text\n\ndef normalization(Sentences):\n sent=[]\n for s in Sentences:\n aux=tokens(s)\n sent.append(aux)\n return sent \n\ndef tokens(text):\n stop=stopwords.words('spanish')\n words = nltk.word_tokenize(text)\n words=[w.lower() for w in words if w.isalpha()]\n words=[w for w in words if w.lower() not in stop]\n words= \" \".join(words)\n return words\n\ndef tagSentences(Sentences,combined_tagger):\n Stag=[]\n for s in Sentences:\n aux=s.split(' ')\n s_tagged=combined_tagger.tag(aux)\n aux=cleanTagger(s_tagged)\n tag=' '.join(aux)\n Stag.append(tag)\n return Stag\n\ndef lemaSentences(Sentences,lemmas):\n sentencesL=[]\n for s in Sentences:\n aux=s.split(' ')\n newSentences=[]\n for word in aux:\n if word in lemmas:\n newSentences.append(lemmas[word])\n else:\n newSentences.append(word)\n sentencesL.append(' '.join(newSentences))\n return sentencesL\n\ndef getSentences(text):\n text=cleaningText(text)\n sentences=sent_tokenize(text)\n \n return sentences\n\ndef getVocabulary(text):\n stop=stopwords.words('spanish')\n t=cleaningText(text)\n t=nltk.word_tokenize(t)\n t=[w.lower() for w in t if w.isalpha()]\n t=[w for w in t if w.lower() not in stop]\n return t\n\ndef getProbability(word,sentences):\n suma=0\n for s in sentences:\n if(bool(s.count(word))):\n suma=suma+1\n return (suma+0.5) / ( len(sentences) + 1 )\n\ndef getProbability2(word1,word2,sentences):\n suma=0\n for s in sentences:\n if(bool(s.count(word1) and bool(s.count(word2)))):\n suma=suma+1\n return (suma + 0.25) / ( len(sentences) + 1 )\n\n'''\n-----------------------------------------------------------\n| | P1 p(w2=0) | P2 p(w2=1) |\n-----------------------------------------------------------\n| P3 p(W1=0) | P4 p(w1=0|w2=0) | P5 p(w1=0|w2=1) |\n-----------------------------------------------------------\n| P6 p(W1=1) | P7 p(w1=1|w2=0) | P8 p(w1=1|w2=1) |\n-----------------------------------------------------------\n\n'''\ndef getTableProbability( pWord1 , pWord2 , pW1AndpW2 ):\n p5 = pWord2 - pW1AndpW2\n p1 = 1 - pWord2\n p7 = pWord1 - pW1AndpW2\n p4 = p1 - p7\n p3 = p4 + p5\n table = [ p1 , pWord2 , p3 , p4 , p5 , pWord1 , p7 , pW1AndpW2 ]\n return table \n\ndef getEntropy( table ):\n x1 = table[3] * math.log2( table[3] / table[0] ) + table[6] * math.log2( table[6] / table[0] )\n x2 = table[4] * math.log2( table[4] / table[1] ) + table[7] * math.log2( table[7] / table[1] )\n H = -1 * ( x1 + x2 )\n return H \n\ndef lemmetization(tokens,lemmas):\n newTokens=[]\n for token in tokens:\n if token in lemmas:\n newTokens.append(lemmas[token])\n else:\n newTokens.append(token)\n return newTokens\n\ndef getGenerate():\n fopen=\"../../Corpus/generate.txt\"\n archivo= open(fopen,encoding='utf-8')\n lemmas={}\n for linea in archivo.readlines(): \n lemmas[linea.split(' ')[0].replace(\"#\",\"\")]=linea.split(' ')[-1][:-1]\n archivo.close()\n return lemmas\n\ndef generateTagger(): \n default_tagger=nltk.DefaultTagger('V')\n patterns=[ (r'.*o$', 'NMS'), # noun masculine singular\n (r'.*os$', 'NMP'), # noun masculine plural\n (r'.*a$', 'NFS'), # noun feminine singular\n (r'.*as$', 'NFP') # noun feminine plural\n ]\n regexp_tagger=nltk.RegexpTagger(patterns, backoff=default_tagger)\n cess_tagged_sents=cess_esp.tagged_sents()\n combined_tagger=nltk.UnigramTagger(cess_tagged_sents, backoff=regexp_tagger)\n \n return combined_tagger\n\ndef cleanTagger(s_tagged):\n list(s_tagged)\n vocabulary=[]\n for i in range(len(s_tagged)):\n vocabulary.append(s_tagged[i][0]+\" \"+s_tagged[i][1])\n \n return vocabulary\n\ndef pkl(f,info):\n output=open(f, 'wb')\n dump(info, output, -1)\n output.close()\n \ndef getPKL(fileName): \n with open(fileName,'rb') as f:\n return load(f)\n \nif __name__ == \"__main__\":\n #**********************************************************************************\n # Run the first time for generate the files .pkl\n #**********************************************************************************\n text=openText()\n #Vocabulario con lemmas\n print(\"get vocabulary\")\n lemmas = getGenerate()\n stop = stopwords.words('spanish')\n \n vocabulary= getVocabulary(text)\n vocabulary=lemmetization(vocabulary,lemmas)\n s_tagged=generateTagger(vocabulary)\n vocabulary=cleanTagger(s_tagged)\n vocabulary=sorted(set(vocabulary))\n pkl('vocabulary.pkl',vocabulary)\n \n sentences=getSentences(text)\n pkl('Sentences1.pkl',sentences)\n\n print(\"Normalization\")\n CleanSentences=normalization(sentences)\n pkl('Sentences2.pkl',CleanSentences)\n print(\"Lemmas\")\n lemmasSent=lemaSentences(CleanSentences,lemmas)\n pkl('Sentences3.pkl',lemmasSent)\n print(\"Tag\")\n print(lemmasSent)\n combined_tagger=generateTagger()\n tagSent=tagSentences(lemmasSent,combined_tagger)\n pkl('Sentences4.pkl',tagSent)\n\n #**********************************************************************************\n # Load the files .pkl\n #**********************************************************************************\n\n #vocabulary = getPKL('vocabulary.pkl')\n #sentences = getPKL('Sentences1.pkl')\n #CleanSentences = getPKL('Sentences2.pkl')\n #lemmasSent = getPKL('Sentences3.pkl')\n #tagSent = getPKL('Sentences4.pkl')\n\n #word1='grande aq0cs0'\n #word1='abastecer V'\n word1 = 'economía ncfs000'\n #word1='nacional aq0cs0'\n\n entropy = [ ]\n\n pWord1= getProbability( word1,tagSent )\n for termn in vocabulary:\n pWord2 = getProbability( termn,tagSent )\n pW1AndpW2 = getProbability2( word1 , termn , tagSent )\n table = getTableProbability( pWord1 , pWord2 , pW1AndpW2 ) \n H = getEntropy( table )\n entropy.append( (termn,H) )\n\n entropy = sorted(entropy,key=operator.itemgetter(1))\n\n fv=open('Entropy_'+ word1.split(' ')[0] +'.txt','w')\n for e in entropy:\n fv.write( '{:30}{:30}\\n'.format(e[0],e[1]) )\n\n","sub_path":"Practices/SyntagmaticRelations/Practice10/Practice10.py","file_name":"Practice10.py","file_ext":"py","file_size_in_byte":7374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"212172694","text":"# -*- coding: utf-8 -*-\n\nimport logging\n\nfrom luckycommon.account.model.account import AccountStatus\nfrom luckycommon.account.db import account as api_user\nfrom luckycommon.db import admin as admin_user\nfrom luckycommon.utils.decorator import JsonResponse\nfrom luckycommon.utils.exceptions import PermissionError\n\n_LOGGER = logging.getLogger(__name__)\n\n\ndef check_perm(url_array, perm, role):\n l = len(url_array)\n while l >= 1:\n url = '/'.join(url_array[0:l])\n if not url.endswith('/'):\n url += '/'\n k = admin_user.get_perm(url, perm)\n if k and k.min_role <= role:\n return True\n l -= 1\n return False\n\n\nclass UserMiddleware(object):\n\n \"\"\"get user_id and token from header\"\"\"\n\n def process_request(self, req):\n user_id, token = req.META.get(\n 'HTTP_X_AUTH_USER'), req.META.get('HTTP_X_AUTH_TOKEN')\n if not user_id:\n user_id, token = req.COOKIES.get('lucky_user_id'), req.COOKIES.get(\n 'lucky_user_token')\n if user_id and token:\n try:\n user_id = long(user_id)\n except ValueError:\n _LOGGER.error('user id format wrong!')\n req.user_id = None\n return\n if req.path.startswith('/api'):\n user = api_user.get_account(user_id)\n # check banned\n if not user or user.status == AccountStatus.BANNED.value:\n # raise PermissionError('forbidden')\n req.user_id = req.user = None\n return\n info = api_user.get_online_info(user_id, token)\n if info and info.deleted == 0:\n req.user_id = user_id\n for k in 'token', 'device_type', 'os_version', 'extend':\n v = getattr(info, k)\n setattr(user, k, v)\n req.user = user\n return\n else:\n _LOGGER.error(\n \"can't find user_id:%s, token:%s\", user_id, token)\n else:\n info = admin_user.get_online_info(user_id, token)\n if info and info.deleted == 0:\n req.user_id = user_id\n user = admin_user.get_user(user_id)\n if user.role > 0:\n url_array = req.path.split('/')\n if req.method == 'GET':\n need_perm = 1\n else:\n need_perm = 2\n if not check_perm(url_array, need_perm, user.role):\n return JsonResponse(dict(\n status=PermissionError.STATUS,\n msg=str('permission not enough')),\n status=PermissionError.HTTPCODE)\n else:\n req.user = user\n return\n else:\n return JsonResponse(dict(\n status=PermissionError.STATUS,\n msg=str(\"user is forbidden or not activited\")),\n status=PermissionError.HTTPCODE)\n\n req.user_id = req.user = None\n","sub_path":"luckyplatform/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":3337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"483534789","text":"# Find the contiguous subarray within an array (containing at least one number) which has the largest sum.\n# For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguous subarray [4,−1,2,1] has the largest sum = 6.\n\nclass Solution:\n # @param A, a list of integers\n # @return an integer\n def maxSubArray(self, nums):\n if not nums: return None\n l, g = nums[0], nums[0]\n for i in range(1, len(nums)):\n l = max(l+nums[i], nums[i])\n g = max(l, g)\n return g\n","sub_path":"LEETCODE/0053. Maximum Subarray.py","file_name":"0053. Maximum Subarray.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"179908309","text":"import pandas as pd\r\n\r\n\r\ndef merge_nearest_sample(\r\n left: pd.DataFrame,\r\n right: pd.DataFrame,\r\n dhid: str = \"bhid\",\r\n ifrom: str = \"from\",\r\n ito: str = \"to\",\r\n tolerance: float = 1.5,\r\n) -> pd.DataFrame:\r\n \"\"\"Merge right sample table with left by nearest downhole depth.\r\n\r\n Alex Trueman, 2019-08-01\r\n\r\n Useful for merging sample tables (tables with dhid, from, and to depth)\r\n where the from and to depths in the two table do not match. Rather than\r\n creating new records in the left table, the nearest record from the right\r\n table is assigned.This method can cause data loss and should be checked.\r\n\r\n Parameters\r\n ----------\r\n left : DataFrame to be updated, must have dhid, from, and to depths.\r\n right : DataFrame to merge, must have dhid, from, and to depths.\r\n dhid : Name of the hole identification column.\r\n ifrom : Name of the downhole sample from-depth column.\r\n ito : Name of the downhole sample to-depth column.\r\n tolerance : Tolerance parameter for finding nearest sample. Can be\r\n though of as a downhole distance within which a nearest sample\r\n must be found. This parameter should be tested for data loss.\r\n\r\n Return\r\n ------\r\n The left DataFrame is returned with the addition of columns from the\r\n right DataFrame.\r\n\r\n \"\"\"\r\n c_left = left.copy()\r\n c_right = right.copy()\r\n\r\n # Calculate sample mid-points.\r\n mid_samp = lambda df, ifrom, ito: df[ifrom] + (df[ito] - df[ifrom]) / 2\r\n c_left[\"mid_samp\"] = mid_samp(c_left, ifrom, ito)\r\n c_right[\"mid_samp\"] = mid_samp(c_right, ifrom, ito)\r\n\r\n # Prepare for merging.\r\n c_right.drop(columns=[ifrom, ito], inplace=True)\r\n c_right.sort_values(by=\"mid_samp\", inplace=True)\r\n c_left.sort_values(by=\"mid_samp\", inplace=True)\r\n\r\n # Merge by nearest midpoint and by hole id.\r\n df = (\r\n pd.merge_asof(\r\n c_left,\r\n c_right,\r\n on=\"mid_samp\",\r\n by=dhid,\r\n tolerance=tolerance,\r\n direction=\"nearest\",\r\n )\r\n .drop(columns=[\"mid_samp\"])\r\n .sort_values(by=[dhid, ifrom, ito])\r\n )\r\n\r\n return df\r\n","sub_path":"myutils/merge_nearest_sample.py","file_name":"merge_nearest_sample.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"616868188","text":"from __future__ import division\nimport numpy as np\nimport math\nimport collections\n\nimport xml.etree.ElementTree as ET\nfrom xml.dom import minidom\n\n\n\nclass Queue:\n def __init__(self):\n self.items = []\n\n def isEmpty(self):\n return self.items == []\n\n def enqueue(self, item):\n self.items.insert(0,item)\n\n def dequeue(self):\n return self.items.pop()\n\nclass info_gain:\n\tdef __init__(self, file_name, delimit = ',', names = True, skiprows=1, decision_column = -1):\n\t\tself.file_name = file_name\n\t\tself.delimit = delimit\n\t\tself.decision_column = decision_column #usually the last column which contains what you want to induce\n\n\t\tself.my_data = np.genfromtxt(self.file_name, delimiter = self.delimit, names = True, dtype=None) #Delimiter using numpy\n\t\tself.column_names = self.my_data.dtype.names #all column names\n\t\tself.classify_name = self.column_names[self.decision_column] #the column name to predict/classify\n\n\t\tself.q = Queue() #Queue Instance\n\t\tself.root = ET.Element('ROOT')\n\n\tdef process(self):\n\t\tself.root.set('table', self.my_data)\n\n\t\tself.q.enqueue(self.root)\n\t\tcounter = 0\n\n\t\twhile True :\n\t\t\tcurrent_tree_element = self.q.dequeue() #the current XML (sub)element\n\t\t\tcurrent_matrix = current_tree_element.get('table') #the current matrix to be looked at\n\t\t\tcurrent_tree_element.attrib.pop('table')\n\t\t\ttemp_classify_array = current_matrix[self.classify_name] # the last column usually which contains what we are trying to predict\n\t\t\tfirst_entropy = self.calculate_entropy(temp_classify_array) #the entropy\n\t\t\tnon_decision_column_names= tuple(list(current_matrix.dtype.names)[:-1])\n\n\t\t\tif first_entropy > 0:\t#If the entropy is not zero then run\n\t\t\t\tgains = []\n\n\t\t\t\t#determine which column has the highest gain?\n\t\t\t\tfor i in non_decision_column_names:\n\t\t\t\t\tgains.append(self.calculate_gain(current_matrix,i,first_entropy)) #append gains & rounding\n\n\t\t\t\t#this column index has the highest gain\n\t\t\t\tkey = gains.index(max(gains))\n\t\t\t\tkey_name = current_matrix.dtype.names[key]\n\n\t\t\t\tcurrent_tree_element.set('column_split', key_name)#adding attribute column split by column with highest gain\n\t\t\t\tcurrent_tree_element.set('gain',str(round(max(gains),4))) #gain tag\n\n\t\t\t\t#splits columns & enqueues new elements\n\t\t\t\tself.splitting_by_column(current_matrix, key_name, current_tree_element)\n\n\t\t\t#the entropy is zero\n\t\t\telse:\n\t\t\t\tcurrent_tree_element.set('Entropy',str(1.0)) #gain tag\n\t\t\t\tsolution = current_matrix[self.classify_name][0]\n\t\t\t\ttemp_element = ET.SubElement(current_tree_element,\"LEAF\")\n\t\t\t\ttemp_element.set('answer',str(solution))\n\n\n\t\t\t\n\t\t\tif self.q.isEmpty():\n\t\t\t\tbreak\n\n\t#calculate entropy\n\tdef calculate_entropy(self,table):\n\n\t\tself.frequency = collections.Counter(table)#frequency of yes and no's (Dictionary)\n\t\ttotal = sum(self.frequency.values())#Total yes and no's from dictionary\n\t\tself.entropy = 0\n\n\t\tfor keys in self.frequency: #loop through keys of frequency \n\t\t\tp_i = self.frequency[keys]/total #probability\n\t\t\tself.entropy+= -1 * p_i * math.log(p_i,2) #entropy\n\t\t\n\t\treturn self.entropy\n\n\t#info gained from splitting items \n\tdef calculate_gain(self,data_matrix,which_column,entropy_par_):#, column_number):\n\t\tfrequency = collections.Counter(data_matrix[which_column])\n\n\t\tlocal_total = sum(frequency.values())\n\t\tsets = zip(data_matrix[which_column], data_matrix[self.classify_name])\n\t\tcollect = collections.Counter(sets)\n\t\t\n\t\tlocal_info = 0 #initiating calculation for info_A\n\n\t\tfor keys in frequency:\n\t\t\tdenom = frequency[keys] #denominator or total\n\t\t\tinside_parenthesis = 0 \t #to be added to\n\n\t\t\tfor j in collect:\n\t\t\t\tif (j[0] == keys):\n\t\t\t\t\ttemp_p_i = collect[j]/denom\n\t\t\t\t\tinside_parenthesis+= -1 * temp_p_i * math.log(temp_p_i,2)\n\n\t\t\tlocal_info += denom/local_total * inside_parenthesis\n\n\t\treturn entropy_par_ - local_info\n\n\t#process the table and add vertices's for each splitting\n\tdef splitting_by_column(self, t_table, temp_name, parent):\n\t\ttemp_frequency = collections.Counter(t_table[temp_name]) #get frequency\n\n\t\t#Renaming Column Names by removing the column that will be removed\n\t\tnew_names = list(t_table.dtype.names)\n\t\tnew_names.remove(temp_name) #removing one column\n\n\t\tfor keys in temp_frequency:\t#creating sub_tables\n\t\t\tsub_table = t_table[np.where(t_table[temp_name] == keys)]\n\t\t\t\n\t\t\tsub_table = sub_table[new_names]\n\n\t\t\tnew_sub = ET.SubElement(parent,'BRANCH')\n\t\t\tnew_sub.set('value',str(keys))\n\t\t\tnew_sub.set('table', sub_table)\n\t\t\tself.q.enqueue(new_sub) #enqueuing new subelement to further calculate later\n\n\t#Write out XML Tree\n\tdef write_xml(self,new_file_name):\n\t\ts = ET.tostring(self.root) #convert XML to String\n\t\tf = open(new_file_name, 'w') #open file\n\t\tf.write(minidom.parseString(s).toprettyxml()) #write out to file\n\t\tf.close()\n\n\t#Bin specified rows into nominal data atributes\n\tdef binning(self):\n\t\t'Will bin specified rows into numeric atributes'\n\n\t#Run the trained tree on test data set.\n\tdef testing(self, test_data_file):\n\t\taccurate = 0\n\t\tincorrect = 0\n\t\tfor row in test_data_file:\n\t\t\t'Do nothing'\n\n\n\ndef main():\n\tbase = info_gain('iris_data.csv', delimit = ',', decision_column=4)\n\tbase.process()\n\tbase.write_xml('ID3.xml')\n\t#base.testing()\nmain()\n\n","sub_path":"ID3.py","file_name":"ID3.py","file_ext":"py","file_size_in_byte":5153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"527921439","text":"\"\"\" This module contains utilities for plotting histgrams comparisons.\n\"\"\"\n\nimport math\nimport random\nimport sys\nif sys.version_info <= (2, 7):\n from enum import Enum\nimport ROOT\nfrom . import root_utils\nfrom .physics import MeasuredQuantity\n\nclass CompareHistograms:\n \"\"\" Compare histograms\n \"\"\"\n def __init__(self, name):\n self.name = name\n self.baseline_histogram = None\n self.histograms = None\n self.ratios = []\n self.fit_results = []\n self.opt_spectrum_baseline = \"\"\n self.opt_spectrum = \"\"\n self.opt_ratio = \"\"\n self.y_axis_ratio = \"Ratio\"\n self.do_spectra_plot = \"logy\"\n self.do_ratio_plot = \"lineary\"\n self.canvas_spectra = None\n self.canvas_ratio = None\n self.legend_spectra = None\n self.legend_ratio = None\n self.baseline_ratio = None\n self.marker_size = 1.2\n self.colors = [ROOT.kBlack, ROOT.kBlue + 2, ROOT.kRed + 2, ROOT.kGreen + 2, ROOT.kOrange + 2, ROOT.kAzure + 2, ROOT.kMagenta + 2, ROOT.kCyan + 2, ROOT.kPink + 1, ROOT.kTeal + 2, ROOT.kYellow + 2]\n self.markers = [ROOT.kOpenCircle, ROOT.kFullCircle, ROOT.kFullSquare, ROOT.kFullTriangleUp, ROOT.kFullTriangleDown, ROOT.kFullDiamond, ROOT.kFullStar, ROOT.kStar, ROOT.kFullCross, ROOT.kMultiply, ROOT.kPlus]\n self.lines = [1, 2, 9, 5, 7, 10, 4, 3, 6, 8]\n self.line_widths = [2] * 10\n self.fill_styles = [3001, 3002, 3003, 3004, 3005, 3006, 3007]\n self.main_histogram = None\n self.main_ratio_histogram = None\n self.max_spectrum = None\n self.min_spectrum = None\n self.max_ratio = None\n self.min_ratio = None\n self.results = None\n self.n_cols_leg_ratio = 1\n self.n_cols_leg_spectrum = 1\n self.x1_leg_ratio = 0.55\n self.x2_leg_ratio = 0.90\n self.y1_leg_ratio = 0.87\n self.x1_leg_spectrum = 0.55\n self.x2_leg_spectrum = 0.90\n self.y1_leg_spectrum = 0.87\n self.log_upper_space = 10 # this factor will be used to adjust the y axis in log scale\n self.log_lower_space = 2 # this factor will be used to adjust the y axis in log scale\n self.lin_upper_space = 0.9 # this factor will be used to adjust the y axis in linear scale\n self.lin_lower_space = 0.2 # this factor will be used to adjust the y axis in linear scale\n self.leg_text_size = 18\n self.leg_line_height = 0.06\n self.fixed_lower_ratio_bound = None\n\n self.baseline_for_ratio = None\n self.separate_baseline_uncertainty = False\n self.no_error_in_baseline = False\n self.ratio_relative_uncertainty = None\n self.ratio_relative_uncertainty_title = \"Rel. Unc.\"\n self.grid_y_ratio = True\n\n self.grid_y_spectrum = False\n\n self.fit_function = \"expo(0)+expo(2)\"\n self.do_spectrum_legend = True\n self.do_ratio_legend = True\n self.units = \"\"\n self.minimum_limit = 0\n\n def set_ratio_relative_uncertainty_from_histogram(self, hist):\n self.ratio_relative_uncertainty = hist.Clone(\"{0}_unc\".format(hist.GetName()))\n self.ratio_relative_uncertainty.SetTitle(self.ratio_relative_uncertainty_title)\n for ibin in range(0, self.ratio_relative_uncertainty.GetNbinsX() + 2):\n if self.ratio_relative_uncertainty.GetBinContent(ibin) != 0:\n self.ratio_relative_uncertainty.SetBinError(ibin, self.ratio_relative_uncertainty.GetBinError(ibin) / self.ratio_relative_uncertainty.GetBinContent(ibin))\n self.ratio_relative_uncertainty.SetBinContent(ibin, 1)\n else:\n self.ratio_relative_uncertainty.SetBinError(ibin, 0)\n self.ratio_relative_uncertainty.SetBinContent(ibin, 0)\n\n def add_stat(self, h):\n mean = MeasuredQuantity(h.GetMean(), h.GetMeanError(), self.units)\n sigma = MeasuredQuantity(h.GetStdDev(), h.GetStdDevError(), self.units)\n entry = self.legend_spectra.AddEntry(ROOT.nullptr, \"#mu = {}\".format(mean.to_string()), \"\")\n entry.SetTextSize(self.leg_text_size * 0.8)\n entry = self.legend_spectra.AddEntry(ROOT.nullptr, \"#sigma = {}\".format(sigma.to_string()), \"\")\n entry.SetTextSize(self.leg_text_size * 0.8)\n\n def prepare_spectra_canvas(self):\n if not self.canvas_spectra:\n print(\"Creating new canvas {0}\".format(self.name))\n self.canvas_spectra = ROOT.TCanvas(self.name, self.name)\n\n if self.do_spectrum_legend:\n if self.do_spectrum_legend == \"stat\":\n self.leg_line_height *= 2.5\n if self.legend_spectra:\n y1 = self.legend_spectra.GetY1() - self.leg_line_height * (len(self.histograms) + 1) / self.n_cols_leg_spectrum\n if y1 < 0.2: y1 = 0.2\n self.legend_spectra.SetY1(y1)\n else:\n y1 = self.y1_leg_spectrum - self.leg_line_height * (len(self.histograms) + 1) / self.n_cols_leg_spectrum\n if y1 < 0.2: y1 = 0.2\n self.legend_spectra = ROOT.TLegend(self.x1_leg_spectrum, y1, self.x2_leg_spectrum, self.y1_leg_spectrum)\n self.legend_spectra.SetName(\"{0}_legend\".format(self.canvas_spectra.GetName()))\n self.legend_spectra.SetNColumns(self.n_cols_leg_spectrum)\n self.legend_spectra.SetFillStyle(0)\n self.legend_spectra.SetBorderSize(0)\n self.legend_spectra.SetTextFont(43)\n self.legend_spectra.SetMargin(0.1)\n self.legend_spectra.SetTextSize(self.leg_text_size)\n\n if self.grid_y_spectrum:\n self.canvas_spectra.SetGridy()\n\n if \"hist\" in self.opt_spectrum_baseline:\n self.baseline_histogram.SetLineColor(self.colors[0])\n self.baseline_histogram.SetLineWidth(self.line_widths[0])\n self.baseline_histogram.SetLineStyle(self.lines[0])\n if self.do_spectrum_legend:\n self.legend_spectra.AddEntry(self.baseline_histogram, self.baseline_histogram.GetTitle(), \"l\")\n if self.do_spectrum_legend == \"stat\":\n self.add_stat(self.baseline_histogram)\n elif \"e2\" in self.opt_spectrum_baseline:\n self.baseline_histogram.SetLineColor(self.colors[0])\n self.baseline_histogram.SetFillColor(self.colors[0])\n self.baseline_histogram.SetLineWidth(1)\n self.baseline_histogram.SetLineStyle(self.lines[0])\n self.baseline_histogram.SetFillStyle(self.fill_styles[0])\n if self.do_spectrum_legend:\n self.legend_spectra.AddEntry(self.baseline_histogram, self.baseline_histogram.GetTitle(), \"f\")\n if self.do_spectrum_legend == \"stat\":\n self.add_stat(self.baseline_histogram)\n else:\n self.baseline_histogram.SetMarkerColor(self.colors[0])\n self.baseline_histogram.SetLineColor(self.colors[0])\n self.baseline_histogram.SetMarkerStyle(self.markers[0])\n self.baseline_histogram.SetMarkerSize(self.marker_size)\n if self.do_spectrum_legend:\n self.legend_spectra.AddEntry(self.baseline_histogram, self.baseline_histogram.GetTitle(), \"pe\")\n if self.do_spectrum_legend == \"stat\":\n self.add_stat(self.baseline_histogram)\n\n if isinstance(self.baseline_histogram, ROOT.TGraph):\n if not \"a\" in self.opt_spectrum_baseline or not \"A\" in self.opt_spectrum_baseline:\n self.opt_spectrum_baseline += \"A\"\n \n if len(self.baseline_histogram.GetListOfFunctions()) > 0:\n for obj in self.baseline_histogram.GetListOfFunctions():\n if isinstance(obj, ROOT.TF1):\n obj.SetLineColor(self.colors[0])\n obj.SetLineStyle(self.lines[0])\n obj.SetLineWidth(self.line_widths[0])\n\n print(\"Plotting histogram '{0}' with option '{1}'\".format(self.baseline_histogram.GetName(), self.opt_spectrum_baseline))\n self.canvas_spectra.cd()\n self.baseline_histogram.Draw(self.opt_spectrum_baseline)\n\n if \"frac\" in self.baseline_histogram.GetYaxis().GetTitle():\n self.canvas_spectra.SetLeftMargin(0.12)\n self.baseline_histogram.GetYaxis().SetTitleOffset(1.4)\n if \"same\" not in self.opt_spectrum:\n self.opt_spectrum += \"same\"\n\n if not self.main_histogram:\n if isinstance(self.baseline_histogram, ROOT.TH1):\n self.main_histogram = self.baseline_histogram\n elif isinstance(self.baseline_histogram, ROOT.TGraph):\n self.main_histogram = self.baseline_histogram.GetHistogram()\n else:\n print(\"Type of object '{}' not recognized!\".format(self.baseline_histogram))\n self.baseline_for_ratio = self.baseline_histogram.Clone(\"{0}_copy\".format(self.baseline_histogram.GetName()))\n\n minimum = root_utils.find_minimum(self.baseline_histogram, self.minimum_limit, \"hist\" not in self.opt_spectrum_baseline)\n if not minimum is None:\n if self.min_spectrum is None:\n self.min_spectrum = minimum\n else:\n self.min_spectrum = min(self.min_spectrum, minimum)\n maximum = root_utils.find_maximum(self.baseline_histogram, self.minimum_limit, \"hist\" not in self.opt_spectrum_baseline)\n if not maximum is None:\n if self.max_spectrum is None:\n self.max_spectrum = maximum\n else:\n self.max_spectrum = max(self.max_spectrum, maximum)\n\n def prepare_ratio_canvas(self):\n cname = \"{0}_Ratio\".format(self.name)\n if not self.canvas_ratio:\n self.canvas_ratio = ROOT.TCanvas(cname, cname)\n self.canvas_ratio.cd()\n\n n = len(self.histograms)\n if self.ratio_relative_uncertainty or self.separate_baseline_uncertainty:\n n += 1\n\n if self.do_ratio_legend:\n if self.legend_ratio:\n y1 = self.legend_ratio.GetY1() - self.leg_line_height * n / self.n_cols_leg_ratio\n if y1 < 0.2: y1 = 0.2\n self.legend_ratio.SetY1(y1)\n else:\n y1 = self.y1_leg_ratio - self.leg_line_height * n / self.n_cols_leg_ratio\n if y1 < 0.2: y1 = 0.2\n self.legend_ratio = ROOT.TLegend(self.x1_leg_ratio, y1, self.x2_leg_ratio, self.y1_leg_ratio)\n self.legend_ratio.SetName(\"{0}_legend\".format(self.canvas_ratio.GetName()))\n self.legend_ratio.SetNColumns(self.n_cols_leg_ratio)\n self.legend_ratio.SetFillStyle(0)\n self.legend_ratio.SetBorderSize(0)\n self.legend_ratio.SetTextFont(43)\n self.legend_ratio.SetTextSize(self.leg_text_size)\n\n if self.grid_y_ratio:\n self.canvas_ratio.SetGridy()\n\n if self.separate_baseline_uncertainty or self.no_error_in_baseline:\n for ibin in range(0, self.baseline_for_ratio.GetNbinsX() + 2):\n self.baseline_for_ratio.SetBinError(ibin, 0)\n\n if self.separate_baseline_uncertainty:\n self.set_ratio_relative_uncertainty_from_histogram(self.baseline_histogram)\n opt = \"e2\"\n if \"same\" in self.opt_ratio:\n opt += \"same\"\n h = self.ratio_relative_uncertainty.DrawCopy(opt)\n h.SetFillColor(self.colors[0])\n h.SetFillStyle(self.fill_styles[0])\n h.SetLineColor(self.colors[0])\n h.GetYaxis().SetTitle(self.y_axis_ratio)\n if self.do_ratio_legend: self.legend_ratio.AddEntry(h, h.GetTitle(), \"f\")\n self.results.append(h)\n if \"same\" not in self.opt_ratio:\n self.opt_ratio += \"same\"\n if not self.main_ratio_histogram:\n self.main_ratio_histogram = h\n minimum = root_utils.find_minimum(h, self.minimum_limit, True)\n if not minimum is None:\n if self.min_ratio is None:\n self.min_ratio = minimum\n else:\n self.min_ratio = min(self.min_ratio, minimum)\n maximum = root_utils.find_maximum(h, self.minimum_limit, True)\n if not maximum is None:\n if self.max_ratio is None:\n self.max_ratio = maximum\n else:\n self.max_ratio = max(self.max_ratio, maximum)\n\n def plot_histogram(self, color, marker, line, lwidth, h):\n minimum = root_utils.find_minimum(h, self.minimum_limit, not \"hist\" in self.opt_spectrum)\n if not minimum is None:\n if self.min_spectrum is None:\n self.min_spectrum = minimum\n else:\n self.min_spectrum = min(self.min_spectrum, minimum)\n maximum = root_utils.find_maximum(h, self.minimum_limit, not \"hist\" in self.opt_spectrum)\n if not maximum is None:\n if self.max_spectrum is None:\n self.max_spectrum = maximum\n else:\n self.max_spectrum = max(self.max_spectrum, maximum)\n\n print(\"Plotting histogram '{0}' with option '{1}'\".format(h.GetName(), self.opt_spectrum))\n self.canvas_spectra.cd()\n h.Draw(self.opt_spectrum)\n\n if \"hist\" in self.opt_spectrum:\n h.SetLineColor(color)\n h.SetLineWidth(lwidth)\n h.SetLineStyle(line)\n if self.do_spectrum_legend:\n self.legend_spectra.AddEntry(h, h.GetTitle(), \"l\")\n if self.do_spectrum_legend == \"stat\":\n self.add_stat(h)\n else:\n h.SetMarkerColor(color)\n h.SetLineColor(color)\n h.SetMarkerStyle(marker)\n h.SetMarkerSize(self.marker_size)\n if self.do_spectrum_legend:\n self.legend_spectra.AddEntry(h, h.GetTitle(), \"pe\")\n if self.do_spectrum_legend == \"stat\":\n self.add_stat(h)\n\n if len(h.GetListOfFunctions()) > 0:\n for obj in h.GetListOfFunctions():\n if isinstance(obj, ROOT.TF1):\n obj.SetLineColor(color)\n obj.SetLineStyle(line)\n obj.SetLineWidth(lwidth)\n\n def fit_and_make_consistent(self, h, templateH):\n fit_func = ROOT.TF1(\"{0}_fit\".format(h.GetName()), self.fit_function, h.GetXaxis().GetXmin(), h.GetXaxis().GetXmax())\n fit_func.SetParameter(0, 1)\n fit_func.SetParameter(1, -0.5)\n fit_func.SetParameter(2, 0)\n fit_func.SetParameter(3, 0)\n fit_func.SetParameter(0, 1. / fit_func.Eval(h.GetXaxis().GetBinCenter(1)))\n fit_func.SetParameter(2, 1)\n fit_func.SetParameter(3, -0.2)\n fit_func.SetParameter(2, 1. / fit_func.Eval(h.GetXaxis().GetBinCenter(int(h.GetNbinsX() / 2))))\n fitR = h.Fit(fit_func, \"NS\")\n fitOk = int(fitR)\n if not fitOk == 0: return None\n h_fit = root_utils.soft_clone(templateH, \"{0}_fith\".format(h.GetName()))\n for ibin in range(1, h_fit.GetNbinsX() + 1):\n valErr = fit_func.IntegralError(h_fit.GetXaxis().GetBinLowEdge(ibin), h_fit.GetXaxis().GetBinUpEdge(ibin)) / (h_fit.GetXaxis().GetBinUpEdge(ibin) - h_fit.GetXaxis().GetBinLowEdge(ibin))\n val = fit_func.Integral(h_fit.GetXaxis().GetBinLowEdge(ibin), h_fit.GetXaxis().GetBinUpEdge(ibin)) / (h_fit.GetXaxis().GetBinUpEdge(ibin) - h_fit.GetXaxis().GetBinLowEdge(ibin))\n print(\"integral = {0:.5f}, central = {1:.5f}\".format(val, fit_func.Eval((h_fit.GetXaxis().GetBinCenter(ibin)))))\n h_fit.SetBinContent(ibin, val)\n h_fit.SetBinError(ibin, valErr)\n self.fit_results.append(fit_func)\n self.fit_results.append(h_fit)\n fit_func.SetLineColor(h.GetLineColor())\n self.canvas_spectra.cd()\n fit_func.Draw(\"same\")\n return h_fit\n\n def rebin_and_make_consistent(self, h, templateH):\n return root_utils.rebin_1D(h, templateH.GetXaxis())\n\n def plot_ratio(self, color, marker, line, lwidth, h):\n compBinning = root_utils.AxisCompare.check_consistency(h.GetXaxis(), self.baseline_for_ratio.GetXaxis())\n print(\"Result of the binning comparison between {} and {} is: {}\".format(h.GetName(), self.baseline_for_ratio.GetName(), compBinning))\n if compBinning == root_utils.AxisCompare.Identical:\n hRatio = h.Clone(\"{0}_Ratio\".format(h.GetName()))\n elif compBinning == root_utils.AxisCompare.ContainsSameBinning or compBinning == root_utils.AxisCompare.IsContainedSameBinning or compBinning == root_utils.AxisCompare.OverlapsSameBinning:\n print(\"Trying to rebin histogram {0}\".format(h.GetName()))\n hRatio = self.rebin_and_make_consistent(h, self.baseline_for_ratio)\n if not hRatio:\n print(\"Rebin unsuccessfull!\")\n return\n elif compBinning == root_utils.AxisCompare.Contains or compBinning == root_utils.AxisCompare.IsContained or compBinning == root_utils.AxisCompare.Overlaps:\n print(\"Need to rebin.\")\n bins = \"[\"\n for x in h.GetXaxis().GetXbins(): bins += \"{}, \".format(x)\n bins = bins[:-2]\n bins += \"]\"\n print(\"Original binning: {}\".format(bins))\n bins = \"[\"\n for x in self.baseline_for_ratio.GetXaxis().GetXbins(): bins += \"{}, \".format(x)\n bins = bins[:-2]\n bins += \"]\"\n print(\"Final binning: {}\".format(bins))\n print(\"Trying to fit histogram {0} with function {1}\".format(h.GetName(), self.fit_function))\n hRatio = self.fit_and_make_consistent(h, self.baseline_for_ratio)\n if not hRatio:\n print(\"Fit unsuccessfull!\")\n return\n elif compBinning == root_utils.AxisCompare.NoOverlap:\n print(\"The two histograms {}, {} have no overlap. Unable to generate a ratio.\".format(h.GetName(), self.baseline_for_ratio.GetName()))\n return\n else:\n print(\"compare_histograms, plot_ration: Should not end up here!\")\n exit(1)\n\n hRatio.GetYaxis().SetTitle(self.y_axis_ratio)\n if not self.baseline_ratio:\n self.baseline_ratio = hRatio\n if \"hist\" in self.opt_ratio:\n hRatio.SetLineColor(color)\n hRatio.SetLineWidth(lwidth)\n hRatio.SetLineStyle(line)\n if self.do_ratio_legend: self.legend_ratio.AddEntry(hRatio, h.GetTitle(), \"l\")\n else:\n hRatio.SetMarkerColor(color)\n hRatio.SetLineColor(color)\n hRatio.SetMarkerStyle(marker)\n hRatio.SetLineStyle(1)\n hRatio.SetMarkerSize(self.marker_size)\n if self.do_ratio_legend: self.legend_ratio.AddEntry(hRatio, h.GetTitle(), \"pe\")\n self.ratios.append(hRatio)\n hRatio.SetTitle(\"{0} Ratio\".format(h.GetTitle()))\n hRatio.Divide(self.baseline_for_ratio)\n self.canvas_ratio.cd()\n hRatio.Draw(self.opt_ratio)\n if not self.main_ratio_histogram:\n self.main_ratio_histogram = hRatio\n minimum = root_utils.find_minimum(hRatio, self.minimum_limit, not \"hist\" in self.opt_ratio)\n if not minimum is None:\n if self.min_ratio is None:\n self.min_ratio = minimum\n else:\n self.min_ratio = min(self.min_ratio, minimum)\n maximum = root_utils.find_maximum(hRatio, self.minimum_limit, not \"hist\" in self.opt_ratio)\n if not maximum is None:\n if self.max_ratio is None:\n self.max_ratio = maximum\n else:\n self.max_ratio = max(self.max_ratio, maximum)\n\n if not \"same\" in self.opt_ratio:\n self.opt_ratio += \" same\"\n\n def compare_spectra(self, baseline, histos):\n while len(histos) + 1 > len(self.colors): self.colors += random.sample(self.colors[1:], len(self.colors) - 1)\n while len(histos) + 1 > len(self.markers): self.markers += random.sample(self.markers[1:], len(self.markers) - 1)\n while len(histos) + 1 > len(self.lines): self.lines += random.sample(self.lines[1:], len(self.lines) - 1)\n while len(histos) + 1 > len(self.line_widths): self.line_widths += random.sample(self.line_widths[1:], len(self.line_widths) - 1)\n while len(histos) + 1 > len(self.fill_styles): self.fill_styles += random.sample(self.fill_styles[1:], len(self.fill_styles) - 1)\n self.results = []\n print(\"compare_spectra: {0}\".format(self.name))\n self.baseline_histogram = baseline\n self.histograms = histos\n if not isinstance(baseline, ROOT.TH1) and self.do_ratio_plot:\n print(\"Ratio is only available for histograms. Option is disabled.\")\n self.do_ratio_plot = False\n print(\"Baseline: {0}\".format(self.baseline_histogram.GetName()))\n for s in self.histograms:\n print(s.GetName())\n\n if self.do_spectra_plot:\n self.prepare_spectra_canvas()\n\n if self.do_ratio_plot:\n self.prepare_ratio_canvas()\n\n for color, marker, line, linew, h in zip(self.colors[1:], self.markers[1:], self.lines[1:], self.line_widths[1:], self.histograms):\n if self.do_spectra_plot:\n self.plot_histogram(color, marker, line, linew, h)\n if self.do_ratio_plot:\n self.plot_ratio(color, marker, line, linew, h)\n self.adjust_y_limits()\n self.generate_results()\n if self.main_histogram not in self.histograms:\n self.results.append(self.main_histogram)\n return self.results\n\n def compare_uncertainties(self, baseline, histos):\n baseline_unc = root_utils.get_relative_uncertainty(baseline)\n histos_unc = [root_utils.get_relative_uncertainty(h) for h in histos]\n self.CompareSpectra(baseline_unc, histos_unc)\n self.results.append(baseline_unc)\n self.results.extend(histos_unc)\n return self.results\n\n def generate_results(self):\n self.results.extend(self.ratios)\n self.results.extend(self.fit_results)\n if self.canvas_spectra:\n self.results.append(self.canvas_spectra)\n if self.canvas_ratio:\n self.results.append(self.canvas_ratio)\n if self.legend_spectra:\n self.results.append(self.legend_spectra)\n if self.legend_ratio:\n self.results.append(self.legend_ratio)\n if self.ratio_relative_uncertainty:\n self.results.append(self.ratio_relative_uncertainty)\n\n def adjust_y_limits(self):\n if not self.max_ratio is None and not self.min_ratio is None and self.do_ratio_plot:\n print(\"Adjusting y limits for Ratio\")\n if self.min_ratio <= 0 and self.do_ratio_plot == \"logy\":\n print(\"{}: requested logy ratio, but minimum is <= 0. Switching to linear scale.\".format(self.name))\n self.do_ratio_plot = \"lineary\"\n if self.do_ratio_plot == \"logy\":\n max = self.max_ratio * self.log_upper_space\n min = self.min_ratio / self.log_lower_space\n self.canvas_ratio.SetLogy()\n else:\n max = self.max_ratio + (self.max_ratio - self.min_ratio) * self.lin_upper_space\n min = self.min_ratio - (self.max_ratio - self.min_ratio) * self.lin_lower_space\n if min < 0 and self.min_ratio > 0: min = 0\n self.main_ratio_histogram.GetYaxis().UnZoom()\n self.main_ratio_histogram.SetMinimum(min)\n self.main_ratio_histogram.SetMaximum(max)\n if self.do_ratio_legend:\n self.canvas_ratio.cd()\n self.legend_ratio.Draw()\n if not self.fixed_lower_ratio_bound is None:\n self.main_ratio_histogram.SetMinimum(self.fixed_lower_ratio_bound)\n\n if not self.max_spectrum is None and not self.min_spectrum is None and self.do_spectra_plot:\n print(\"Adjusting y limits for Spectrum\")\n if self.min_spectrum <= 0 and self.do_spectra_plot == \"logy\":\n print(\"{}: requested logy spectra, but minimum is <= 0. Switching to linear scale.\".format(self.name))\n self.do_spectra_plot = \"lineary\"\n if self.do_spectra_plot == \"logy\":\n max = self.max_spectrum * self.log_upper_space\n min = self.min_spectrum / self.log_lower_space\n self.canvas_spectra.SetLogy()\n else:\n max = self.max_spectrum + (self.max_spectrum - self.min_spectrum) * self.lin_upper_space\n min = self.min_spectrum - (self.max_spectrum - self.min_spectrum) * self.lin_lower_space\n if min < 0 and self.min_spectrum > 0: min = 0\n self.main_histogram.SetMinimum(min)\n self.main_histogram.SetMaximum(max)\n if self.do_spectrum_legend:\n self.canvas_spectra.cd()\n self.legend_spectra.Draw()\n","sub_path":"pyutils/compare_histograms.py","file_name":"compare_histograms.py","file_ext":"py","file_size_in_byte":25032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"628338335","text":"def ricBinaria(v, x):\r\n inizio = 0\r\n fine = len(v) - 1\r\n while inizio <= fine:\r\n print(\"x\")\r\n med = (inizio + fine) // 2\r\n if v[med] == x:\r\n return med\r\n if v[med] > x:\r\n fine = med - 1\r\n else:\r\n inizio = med + 1\r\n return -1\r\n\r\n#Versione alternativa \r\ndef ricBinaria2(v, x, inizio, fine):\r\n print(\"x\")\r\n if inizio > fine:\r\n return -1\r\n med = (inizio + fine) // 2\r\n if v[med] == x:\r\n return med\r\n if v[med] > x:\r\n return ricBinaria2(v, x, inizio, med-1)\r\n else:\r\n return ricBinaria2(v, x, med+1, fine)\r\n return -1\r\n\r\n#Verzione per potenza di 2\r\n#Assumiamo il n elementi una potenza di 2\r\n##_INCOMPLETO_##\r\n##def ricBinariaPotenza(v, x):\r\n## inizio = 0\r\n## fine = len(v) - 1\r\n## while inizio <= fine:\r\n## med = (inizio + fine) // 2\r\n## if v[med] == x:\r\n## return med\r\n## if v[med] > x:\r\n## fine = med - 1\r\n## else:\r\n## inizio = med + 1\r\n## return -1\r\n##_INCOMPLETO_##\r\n\r\nv = [1,5,6,11,13,16,18,24,30,36,44,49,62,123,157,255]\r\nx = int(input(\"\"))\r\nl = ricBinaria(v, x)\r\n\r\nprint(l)\r\n \r\n","sub_path":"ricBinaria.py","file_name":"ricBinaria.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"531531191","text":"class ListNode(object):\n\tdef __init__(self, x):\n\t\tself.val = x\n\t\tself.next = None\n\nclass Solution(object):\n\tdef getIntersectionNode(self, headA, headB):\n\t\tnodeA, nodeB = headA, headB\n\t\twhile nodeA != nodeB:\n\t\t\tnodeA = nodeA.next if nodeA else nodeB\n\t\t\tnodeB = nodeB.next if nodeB else nodeA\n\n\t\treturn nodeA\n\n\tdef getIntersectionNode_diff(self, headA, headB):\n\t\tdef get_length(node):\n\t\t\tlength = 0\n\t\t\twhile node:\n\t\t\t\tnode = node.next\n\t\t\t\tlenght += 1\n\t\t\treturn length \n\n\t\tlen1 = get_length(headA)\n\t\tlen2 = get_length(headB)\n\n\t\tif len1 > len2:\n\t\t\tfor __ in range(len1 - len2):\n\t\t\t\theadA = headA.next\n\t\telse:\n\t\t\tfor __ in range(len2 - len1):\n\t\t\t\theadB = headB.next\n\t\twhile headA:\n\t\t\tif headA == headB:\n\t\t\t\treturn headA\n\t\t\theadA = headA.next\n\t\t\theadB = headB.next\n\t\t\t","sub_path":"Part4/Insersection_Of_Two_Linked_Lists.py","file_name":"Insersection_Of_Two_Linked_Lists.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"467543837","text":"import torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.nn.init as init\r\n\r\n\r\nclass Conv2d_ReLU(nn.Module):\r\n \"\"\" Convolutional layer followed by ReLU activation\r\n\r\n Methods:\r\n forward: compute the output of the module given the input\r\n\r\n \"\"\"\r\n\r\n def __init__(self, in_channels, out_channels, kernel_size, stride):\r\n \"\"\" Parameters:\r\n in_channels: number of input channels\r\n out_channels: number of output channels\r\n kernel_size: kernel size\r\n stride: stride\r\n \"\"\"\r\n super(Conv2d_ReLU, self).__init__()\r\n self.conv = nn.Conv2d(in_channels=in_channels,\r\n out_channels=out_channels,\r\n kernel_size=kernel_size,\r\n stride=stride)\r\n self.relu = nn.ReLU()\r\n\r\n def forward(self, x):\r\n \"\"\" forward method\r\n\r\n Args:\r\n x: input Tensor of shape [batch_size, in_channels, hi, wi]\r\n Returns:\r\n out_conv: output Tensor of shape [batch_size, out_channels, ho, wo]\r\n \"\"\"\r\n out_conv = self.conv(x) # Convolution\r\n out_conv = self.relu(out_conv) # Activation\r\n\r\n return out_conv\r\n\r\n\r\nclass Conv2d_BN_ReLU(nn.Module):\r\n \"\"\" Convolutional layer followed by Batch Normalization and ReLU activation\r\n\r\n Methods:\r\n forward: compute the output of the module given the input\r\n\r\n \"\"\"\r\n\r\n def __init__(self, in_channels, out_channels, kernel_size, stride, padding=1, momentum=0.99, eps=0.001):\r\n \"\"\" Parameters:\r\n in_channels: number of input channels\r\n out_channels: number of output channels\r\n kernel_size: kernel size\r\n stride: stride\r\n padding: padding for the convolution (default = 1)\r\n momentum: momentum for the Batch Normalization (default = 0.99)\r\n eps: value for numerical stability of the Batch Normalization (default = 0.001)\r\n \"\"\"\r\n super(Conv2d_BN_ReLU, self).__init__()\r\n self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size,\r\n stride=stride, padding=padding)\r\n self.batchnorm = nn.BatchNorm2d(num_features=out_channels, momentum=momentum, eps=eps)\r\n self.relu = nn.ReLU()\r\n\r\n def forward(self, x):\r\n \"\"\" forward method\r\n\r\n Args:\r\n x: input Tensor of shape [batch_size, in_channels, hi, wi]\r\n Returns:\r\n out_conv: output Tensor of shape [batch_size, out_channels, ho, wo]\r\n \"\"\"\r\n out_conv = self.conv(x)\r\n out_conv = self.relu(out_conv)\r\n out_conv = self.batchnorm(out_conv)\r\n\r\n return out_conv\r\n\r\n\r\ndef squash(x, dim=2):\r\n \"\"\" Computes the squash function of a Tensor along dimension dim\r\n\r\n Args:\r\n x: input tensor\r\n dim: dimension along which the squash must be performed (default = 2)\r\n\r\n Returns:\r\n A tensor squashed along dimension dim of the same shape of x \"\"\"\r\n norm = torch.norm(x, dim=dim, keepdim=True)\r\n return x * norm / (1 + norm ** 2)\r\n\r\n\r\ndef update_routing(votes, logits, iterations, bias):\r\n \"\"\" Dynamic routing algorithm (paper: Dynamic Routing Between Capsules, Sabour et al., 2017)\r\n\r\n Args:\r\n votes : hat{u_{j|i}} Tensor [bs, ci, co, no] / [bs, ci, co, no, ho, wo]\r\n logits : b_{ij} Tensor [bs, ci, co] / [bs, ci, co, ho, wo]\r\n iterations : Number of iterations of the algorithm\r\n bias : Bias term Tensor [co, no] / [co, no, 1, 1]\r\n\r\n Returns:\r\n activation : v_j Tensor [bs, co, no] / [bs, co, no, ho, wo]\r\n\r\n Other variables of the algorithm:\r\n votes_trans : equivalent to votes, but with shape [no, bs, ci, co] / [no, bs, ci, co, ho, wo]\r\n route : c_{ij} Tensor [bs, ci, co] / [bs, ci, co, ho, wo]\r\n preactivate_unrolled : c_{ij} * hat{u_{j|i}} Tensor [no, bs, ci, co] / [no, bs, ci, co, ho, wo]\r\n preactivate_trans : equivalent to preactivate_unrolled\r\n but with shape [bs, ci, co, no] / [bs, ci, co, no, ho, wo]\r\n preactivate : s_j Tensor [bs, co, no] / [bs, co, no, ho, wo]\r\n act_3d : equivalent to activation, but with shape [bs, 1, co, no] / [bs, 1, co, no, ho, wo]\r\n distances : \\hat{u_{j|i}} \\cdot v_j Tensor [bs, ci, co] / [bs, ci, co, ho, wo]\r\n\r\n Meaning of the dimensions:\r\n bs: batch size\r\n ci: number of input channels / number of input capsules\r\n co: number of output channels / number of output capsules\r\n ni: dimension of input capsules\r\n no: dimension of output capsules\r\n ho/wo: height/width of the output feature maps if the capsule layer is convolutional\r\n \"\"\"\r\n # Raise an error if the number of iterations is lower than 1\r\n if iterations < 1:\r\n raise ValueError('The number of iterations must be greater or equal than 1')\r\n\r\n # Perform different permutations depending on the number of dimensions of the vector (4 or 6)\r\n dimensions = len(votes.size())\r\n if dimensions == 4: # [bs, ci, co, no]\r\n votes_trans = votes.permute(3, 0, 1, 2).contiguous() # [no, bs, ci, co]\r\n\r\n else: # [bs, ci, co, no, ho, wo]\r\n votes_trans = votes.permute(3, 0, 1, 2, 4, 5).contiguous() # [no, bs, ci, co, ho, wo]\r\n\r\n for iteration in range(iterations):\r\n route = F.softmax(logits, dim=2)\r\n preactivate_unrolled = route * votes_trans\r\n if dimensions == 4:\r\n preactivate_trans = preactivate_unrolled.permute(1, 2, 3, 0).contiguous() # bs, ci, co, no\r\n else:\r\n preactivate_trans = preactivate_unrolled.permute(1, 2, 3, 0, 4, 5).contiguous() # bs, ci, co, no, ho, wo\r\n\r\n preactivate = preactivate_trans.sum(dim=1) + bias # bs, co, no, (ho, wo)\r\n activation = squash(preactivate, dim=2) # bs, co, no, (ho, wo)\r\n\r\n act_3d = activation.unsqueeze(1) # bs, 1, co, no, (ho,wo)\r\n distances = (votes * act_3d).sum(dim=3) # bs, ci, co, ho, wo\r\n logits = logits + distances\r\n\r\n return activation\r\n\r\n\r\ndef update_routing_6D_DeepCaps(votes, logits, iterations, bias): # differs from above\r\n \"\"\" Dynamic routing algorithm used in DeepCaps for the convolutional capsule layers\r\n\r\n Args:\r\n votes : hat{u_{j|i}} Tensor [bs, ci, co, no, ho, wo]\r\n logits : b_{ij} Tensor [bs, ci, co, ho, wo]\r\n iterations : Number of iterations of the algorithm\r\n bias : Bias term Tensor [bs, co, no, 1, 1]\r\n\r\n Returns:\r\n activation : v_j Tensor [bs, co, no, ho, wo]\r\n\r\n Meaning of the dimensions:\r\n bs: batch size\r\n ci: number of input channels / number of input capsules\r\n co: number of output channels / number of output capsules\r\n ni: dimension of input capsules\r\n no: dimension of output capsules\r\n ho/wo: height/width of the output feature maps if the capsule layer is convolutional\r\n \"\"\"\r\n # Raise an error if the number of iterations is lower than 1\r\n if iterations < 1:\r\n raise ValueError('The number of iterations must be greater or equal than 1')\r\n\r\n bs, ci, co, no, ho, wo = votes.size()\r\n\r\n # Perform different permutations depending on the number of dimensions of the vector (4 or 6)\r\n for iteration in range(iterations):\r\n logits_temp = logits.view(bs, ci, -1) # bs, ci, co*ho*wo\r\n route_temp = F.softmax(logits_temp, dim=2) # bs, ci, co*ho*wo\r\n route = route_temp.view(bs, ci, co, ho, wo) # bs, ci, co, ho, wo\r\n preactivate_unrolled = route.unsqueeze(3) * votes # bs, ci, co, no, ho, wo\r\n preactivate = preactivate_unrolled.sum(1) + bias # bs, co, no, ho, wo\r\n activation = squash(preactivate, dim=2) # bs, co, no, ho, wo\r\n act_3d = activation.unsqueeze(1) # bs, 1, co, no, ho, wo\r\n distances = (act_3d * votes).sum(3) # bs, ci, co, no, ho, wo --> bs, ci, co, ho, wo\r\n logits = logits + distances\r\n\r\n return activation\r\n\r\n\r\nclass ConvPixelToCapsules(nn.Module):\r\n \"\"\" Convolutional layer that transforms the traditional feature maps in capsules\r\n\r\n Methods:\r\n forward: compute the output of the layer given the input\r\n \"\"\"\r\n\r\n def __init__(self, ci, ni, co, no, kernel_size, stride, padding, iterations):\r\n \"\"\" Parameters:\r\n ci: number of input channels\r\n ni: dimension of input capsules (1 if the inputs are traditional feature maps)\r\n co: number of output channels\r\n no: dimension of output capsules\r\n kernel_size: dimension of the kernel (square kernel)\r\n stride : stride parameter (horizontal and vertical strides are equal)\r\n padding : padding applied to the input\r\n iterations: number of iterations of the dynamic routing algorithm\r\n \"\"\"\r\n super(ConvPixelToCapsules, self).__init__()\r\n\r\n self.ci = ci\r\n self.ni = ni\r\n self.co = co\r\n self.no = no\r\n self.iterations = iterations\r\n\r\n self.conv3d = nn.Conv2d(in_channels=ni,\r\n out_channels=co * no,\r\n kernel_size=kernel_size,\r\n stride=stride,\r\n padding=padding,\r\n bias=False)\r\n\r\n self.bias = torch.nn.Parameter(torch.zeros(co, no, 1, 1))\r\n\r\n def forward(self, x):\r\n \"\"\" forward method\r\n\r\n Args:\r\n x: input Tensor of shape [bs, ci, ni, hi, wi]\r\n Returns:\r\n activation: output Tensor of shape [bs, co, no, ho, wo]\r\n \"\"\"\r\n bs, ci, ni, hi, wi = x.size()\r\n\r\n # Reshape input and perform convolution to compute \\hat{u_{j|i}} = votes\r\n input_reshaped = x.view(bs * ci, ni, hi, wi)\r\n votes = self.conv3d(input_reshaped) # bs*ci, co*no, ho, wo\r\n _, _, ho, wo = votes.size()\r\n\r\n # Reshape votes, initialize logits and perform dynamic routing\r\n votes_reshaped = votes.view(bs, ci, self.co, self.no, ho, wo).contiguous()\r\n logits = votes_reshaped.new(bs, ci, self.co, ho, wo).zero_()\r\n\r\n activation = update_routing(votes_reshaped, logits, self.iterations, self.bias)\r\n\r\n return activation\r\n\r\n\r\nclass Capsules(nn.Module):\r\n \"\"\" Capsule layer\r\n\r\n Methods:\r\n forward: compute the output of the layer given the input\r\n \"\"\"\r\n\r\n def __init__(self, ci, ni, co, no, iterations):\r\n \"\"\" Parameters:\r\n ci: number of input channels\r\n ni: dimension of input capsules\r\n co: number of output channels\r\n no: dimension of output capsules\r\n iterations: number of iterations of the dynamic routing algorithm\r\n \"\"\"\r\n super(Capsules, self).__init__()\r\n\r\n self.weight = nn.Parameter(torch.randn(ci, ni, co * no))\r\n self.bias = nn.Parameter(torch.zeros(co, no))\r\n self.ci = ci\r\n self.co = co\r\n self.no = no\r\n self.ni = ni\r\n self.iterations = iterations\r\n\r\n init.kaiming_uniform_(self.weight)\r\n init.constant_(self.bias, 0.1)\r\n\r\n def forward(self, x):\r\n \"\"\" forward method\r\n\r\n Args:\r\n x: input Tensor of shape [bs, ci, ni]\r\n Returns:\r\n activation: output Tensor of shape [bs, co, no]\r\n \"\"\"\r\n bs = x.size(0)\r\n\r\n # Compute \\hat{u_{j|i}} = votes\r\n votes = (x.unsqueeze(3) * self.weight).sum(dim=2).view(-1, self.ci, self.co, self.no)\r\n\r\n # Initialize logits and perform dynamic routing\r\n logits = votes.new(bs, self.ci, self.co).zero_()\r\n activation = update_routing(votes, logits, self.iterations, self.bias)\r\n\r\n return activation\r\n\r\n\r\nclass Conv2DCaps(nn.Module): \r\n \"\"\" 2D Convolutional layer used in DeepCaps (no dynamic routing)\r\n\r\n Methods:\r\n forward: computes the output given the input\r\n \"\"\"\r\n def __init__(self, ci, ni, co, no, kernel_size, stride, padding):\r\n \"\"\" Parameters:\r\n ci: number of input channels\r\n ni: dimension of input capsules\r\n co: number of output channels\r\n no: dimension of output capsules\r\n kernel_size: kernel size\r\n stride: stride\r\n padding: padding\r\n \"\"\"\r\n super(Conv2DCaps, self).__init__()\r\n\r\n self.ci = ci # number of capsules in input layer\r\n self.ni = ni # atoms of capsules in input layer\r\n self.co = co # number of capsules in output layer\r\n self.no = no # atoms of capsules in output layer\r\n\r\n # input shape: bs, ci, ni, hi, wi\r\n\r\n self.conv = nn.Conv2d(in_channels=ci * ni,\r\n out_channels=co * no,\r\n kernel_size=kernel_size,\r\n stride=stride,\r\n padding=padding)\r\n init.xavier_uniform_(self.conv.weight)\r\n init.zeros_(self.conv.bias)\r\n\r\n def forward(self, x):\r\n \"\"\" forward method\r\n\r\n Args:\r\n x: input Tensor of shape [batch_size, ci, ni, hi, wi]\r\n Returns:\r\n output: Tensor of shape [bathc_size, co, no, ho, wo]\r\n \"\"\"\r\n bs, ci, ni, hi, wi = x.size()\r\n input_reshaped = x.view(bs, ci * ni, hi, wi)\r\n\r\n output_reshaped = self.conv(input_reshaped) # bs, co*no, ho, wo\r\n _, _, ho, wo = output_reshaped.size()\r\n\r\n output = output_reshaped.view(bs, self.co, self.no, ho, wo) # bs, co, no, ho, wo\r\n\r\n output = squash(output, dim=2)\r\n\r\n return output\r\n\r\n\r\nclass Conv3DCaps(nn.Module):\r\n \"\"\" 3D convolutional capsule layer with dynamic routing\r\n\r\n Methods:\r\n forward: computes the output given the input\r\n \"\"\"\r\n def __init__(self, ci, ni, co, no, kernel_size, stride, padding, iterations):\r\n \"\"\" Parameters:\r\n ci: number of input channels\r\n ni: dimension of input capsules\r\n co: number of output channels\r\n no: dimension of output capsules\r\n kernel_size: kernel size\r\n stride: stride\r\n padding: padding\r\n iterations: number of iterations of the dynamic routing algorithm\r\n \"\"\"\r\n super(Conv3DCaps, self).__init__()\r\n self.ci = ci\r\n self.ni = ni\r\n self.co = co\r\n self.no = no\r\n\r\n self.conv = nn.Conv3d(in_channels=1,\r\n out_channels=co * no,\r\n kernel_size=(ni, kernel_size, kernel_size),\r\n stride=(ni, stride, stride),\r\n padding=(0, padding, padding))\r\n\r\n self.bias = nn.Parameter(torch.zeros(co, no, 1, 1))\r\n\r\n init.kaiming_uniform_(self.conv.weight)\r\n init.zeros_(self.conv.bias)\r\n init.constant_(self.bias, 0.1)\r\n\r\n self.iterations = iterations\r\n\r\n def forward(self, x):\r\n \"\"\" forward method\r\n\r\n Args:\r\n x: Tensor of shape [batch_size, ci, ni, hi, wi]\r\n Returns:\r\n activation: Tensor of shape [batch_size, co, no, ho, wo]\r\n \"\"\"\r\n bs, ci, ni, hi, wi = x.size()\r\n\r\n input_tensor_reshaped = x.view(bs, 1, ci * ni, hi, wi)\r\n\r\n conv = self.conv(input_tensor_reshaped) # bs, co*no, ci, ho, wo\r\n _, _, _, ho, wo = conv.size()\r\n\r\n votes = conv.permute(0, 2, 1, 3, 4).contiguous().view(bs, ci, self.co, self.no, ho, wo)\r\n\r\n logits = votes.new(bs, ci, self.co, ho, wo).zero_() # bs, ci, co, ho, wo\r\n\r\n activation = update_routing_6D_DeepCaps(votes, logits, self.iterations, self.bias)\r\n\r\n return activation # bs, co, no, ho, wo\r\n\r\n\r\nclass DeepCapsBlock(nn.Module):\r\n \"\"\" DeepCaps block used in the DeepCaps architecture\r\n\r\n Consists of three serial layers and one parallel layer\r\n Methods:\r\n forward: computes the output given the input\r\n \"\"\"\r\n def __init__(self, ci, ni, co, no, kernel_size, stride, padding, iterations):\r\n \"\"\"Parameters:\r\n ci: number of input channels,\r\n ni: dimension of input capsules\r\n co: number of output channels\r\n no: dimension of output capsules\r\n kernel_size: kernel size of the convolutions\r\n stride: stride of the first convolution\r\n padding: list of four elements, padding factors for the four convolutions\r\n iterations: number of iterations of the dynamic routing. If 1, no dynamic routing is performed\r\n \"\"\"\r\n super(DeepCapsBlock, self).__init__()\r\n\r\n self.l1 = Conv2DCaps(ci=ci, ni=ni, co=co, no=no, kernel_size=kernel_size, stride=stride, padding=padding[0])\r\n self.l2 = Conv2DCaps(ci=co, ni=no, co=co, no=no, kernel_size=kernel_size, stride=1, padding=padding[1])\r\n self.l3 = Conv2DCaps(ci=co, ni=no, co=co, no=no, kernel_size=kernel_size, stride=1, padding=padding[2])\r\n if iterations == 1:\r\n self.l_skip = Conv2DCaps(ci=co, ni=no, co=co, no=no, kernel_size=kernel_size, stride=1, padding=padding[2])\r\n else:\r\n self.l_skip = Conv3DCaps(ci=co, ni=no, co=co, no=no, kernel_size=kernel_size, stride=1, padding=padding[3],\r\n iterations=iterations)\r\n\r\n def forward(self, x):\r\n \"\"\" forward method\r\n Args:\r\n x: input Tensor of size [batch_size, ci, ni, hi, wi]\r\n Returns:\r\n x: output Tensor of size [batch_size, co, no, ho, wo]\r\n \"\"\"\r\n x = self.l1(x)\r\n x_skip = self.l_skip(x)\r\n x = self.l2(x)\r\n x = self.l3(x)\r\n x = x + x_skip\r\n\r\n return x\r\n","sub_path":"full_precision_layers.py","file_name":"full_precision_layers.py","file_ext":"py","file_size_in_byte":17976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"207724949","text":"# from __future__ import print_function\nfrom __future__ import division\nfrom itertools import combinations\nimport operator\nfrom pprint import pprint\n\ndef processTransactions(transactions,minsup,minconf):\n\t\"\"\"Processes transactions, returns printable data structures\n\t\n\tThe results will be printed on screen directly.\n\n\t\"\"\"\n\treturn _processTransactions(False,transactions,minsup,minconf)\t\n\ndef _processTransactions(DEBUG,transactions,minsup,minconf):\n\n\tDEBUG=DEBUG\n\n\ttransSize = len(transactions)\n\tdicts=[]\n\n\t\"\"\"Generate the itemsets with 1 item\"\"\"\n\td={}\n\tfor tran in transactions:\n\t\tfor itemSet in tran.values():\n\t\t\tfor item in itemSet:\n\t\t\t\tif frozenset([item]) in d:\n\t\t\t\t\td[frozenset([item])]+=1\n\t\t\t\telse:\n\t\t\t\t\td[frozenset([item])]=1\n\t# \n\t# pprint(d)\n\t\t\t\n\tif DEBUG:\n\t\tpprint(d)\n\t\tprint(\"============================\")\n\t\tprint(\"Above is all the items\")\n\t\tprint(\"============================\")\n\t\tnumItems = len(d.keys())\n\n\tdef delLowSupItems(d):\n\t\tfor dKey in d.keys():\n\t\t\tif d[dKey] < minsup * transSize:\n\t\t\t\tdel d[dKey]\n\t\tdicts.append(d)\n\n\tdelLowSupItems(d)\n\t# \n\t# pprint(dicts[0])\n\n\tif DEBUG:\n\t\tnumSurvive = len(dicts[0].keys())\n\t\tpprint(dicts[0])\n\t\tprint(\"============================\")\n\t\tprint(\"Above is the surviving ones\")\n\t\tprint(\"============================\")\n\t\tprint(\"With min_sup of \"+str(minsup)+\", we have \"+str(numItems)+\" items, of which \"+ str(numSurvive)+\" survived, the # of transactions is \"+str(transSize)+\".\")\n\n\n\tdef getOccurrence(subSet):\n\t\tcount=0\n\t\tfor tran in transactions:\n\t\t\tfor itemSet in tran.values():\n\t\t\t\tif subSet<=itemSet:\n\t\t\t\t\tcount+=1\n\t\treturn count\n\n\tdef inPreviousSet(setCandidate,previousSet,sizeMinusOne):\n\t\tfor subCandidate in set(combinations(setCandidate,sizeMinusOne+1)):\n\t\t\tif set(subCandidate) not in previousSet.keys():\n\t\t\t\treturn False\n\t\treturn True\n\n\t\"\"\"Compute supports\"\"\"\n\tsizeMinusOne=0\n\twhile len(d)!=0:\n\t\td={}\n\t\tsetList = dicts[sizeMinusOne].keys()\n\t\tfor setCandidate in set([k1|k2 for k1 in setList for k2 in setList if len(k1|k2)==sizeMinusOne+2]):\n\t\t\tif inPreviousSet(setCandidate,dicts[sizeMinusOne],sizeMinusOne):\n\t\t\t\tcandidateSup = getOccurrence(setCandidate)\n\t\t\t\tif candidateSup >= minsup * transSize:\n\t\t\t\t\t# print frozenset(setCandidate),candidateSup\n\t\t\t\t\td[frozenset(setCandidate)]=candidateSup\n\n\t\tsizeMinusOne+=1\n\t\tif len(d)!=0:\n\t\t\tdicts.append(d)\n\t# \n\t# print \"largest item set size :\", sizeMinusOne\n\n\t\"\"\"Compute rules\"\"\"\n\trules={}\n\tfor i in range(0,len(dicts)):\n\t\tdict_=dicts[i]\n\t\tfor largeset in dict_.keys():\n\t\t\tdividend=dict_[largeset]\n\t\t\tfor lSize in range(1,len(largeset)):\n\t\t\t\tfor lCandidate in set(combinations(largeset,lSize)):\n\t\t\t\t\tconf=dividend/dicts[lSize-1][frozenset(lCandidate)]\n\t\t\t\t\tif conf >= minconf:\n\t\t\t\t\t\trules[tuple([frozenset(lCandidate),largeset-frozenset(lCandidate)]+[dicts[lSize-1][frozenset(lCandidate)]])]=conf\n\t# \n\t# pprint(rules)\n\n\t\"\"\"Rearange and print the support dicts[] and rules{} data structures\"\"\"\n\tdSup={}\n\tfor dict_ in dicts:\n\t\tdSup.update(dict_)\n\tlargeSetToPrint = sorted(dSup.iteritems(), key=operator.itemgetter(1))\n\tprint (\"==Frequent itemsets (min_sup=\"+str(minsup*100)+\"%)\")\n\tfor line in reversed(largeSetToPrint):\n\t\tprint (str(list(line[0]))+\", \"+str(line[1]/transSize*100)+\"%\")\n\tprint ('')\n\trulesToPrint = sorted(rules.iteritems(), key=operator.itemgetter(1))\n\tprint (\"==High-confidence association rules (min_conf=\"+str(minconf*100)+\"%)\")\n\tfor line in reversed(rulesToPrint):\n\t\tleft=line[0][0]\n\t\tright=line[0][1]\n\t\truleStr=\"[\"\n\t\tfor i in range(0,len(left)):\n\t\t\tif i==len(left)-1:\n\t\t\t\truleStr=ruleStr+str(list(left)[i])+\"] => [\"\t\n\t\t\telse:\n\t\t\t\truleStr=ruleStr+str(list(left)[i])+\", \"\n\t\tfor i in range(0,len(right)):\n\t\t\tif i==len(right)-1:\n\t\t\t\truleStr=ruleStr+str(list(right)[i])+\"] (Conf: \"\t\n\t\t\telse:\n\t\t\t\truleStr=ruleStr+str(list(right)[i])+\", \"\n\t\truleStr=ruleStr+str(line[1]*100)+\"%, Supp: \"+str(line[0][2]/transSize*100)+\"%)\"\n\t\tprint (ruleStr)\n\n\tif DEBUG:\n\t\t# log = open(\"./log.txt\", \"w\")\n\t\t# print(d, file = log)\n\t\t# log.close()\n\t\tpass\n\n\n\nif __name__ == \"__main__\":\n\t_processTransactions(True,[{1:frozenset(['a','b'])}],0.3,0.3)\n\n\n\n\n","sub_path":"apriori.py","file_name":"apriori.py","file_ext":"py","file_size_in_byte":4046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"302463975","text":"#!/usr/bin/python -u\nimport sys\nimport os\nimport time\nfrom subprocess import call\n\nimport string\ndigs = string.digits + string.letters\n\ndef base36(x):\n if x == 0: return digs[0]\n digits = []\n while x:\n digits.append(digs[x % 36].upper())\n x /= 36\n digits.reverse()\n return ''.join(digits)\n\ndef get_binary(z):\n msg = 'Binary\\n'\n for i in range(int(z)-1):\n for j in range(i+1,int(z)):\n msg += ' xe' + base36(i+1) + base36(j+1) + '\\n'\n msg += 'END\\n'\n return msg\n\n\ndef main():\n if(len(sys.argv) != 3):\n return\n maxcut_time = []\n scip_time = []\n sssf = []\n mxc_out = 'mxc.out'\n scp_out = 'scp.out'\n dmp_fle = 'dump.lp'\n z = sys.argv[1]\n binary_vars = get_binary(int(z))\n exp_num = int(sys.argv[2])\n for i in range(exp_num):\n #run maxcut\n call([\"bin/maxcut\", \"-r\",z, \"-p\", \"1\", \"-o\", mxc_out])\n with open(mxc_out) as tmp:\n for line in tmp:\n if 'Search space frac' in line:\n frac = float(line.split(':')[-1])\n sssf.append(frac)\n elif 'Total time' in line:\n t = float(line.split(':')[-1][:-2])\n maxcut_time.append(t)\n print('Parcial Mog times: ', maxcut_time)\n time.sleep(1)\n break\n os.remove(mxc_out)\n\n #modify lp file\n with open(dmp_fle, 'a') as lp:\n #erase END marker\n lp.seek(0, os.SEEK_END)\n pos = lp.tell()\n lp.seek(pos-4, os.SEEK_SET)\n lp.truncate()\n lp.write(binary_vars)\n\n #run scip\n call([\"scip\", \"-f\", dmp_fle, \"-l\", scp_out, \"-q\"])\n with open(scp_out) as tmp:\n for line in tmp:\n if 'Solving Time' in line:\n t = float(line.split(':')[-1])\n scip_time.append(t)\n print('Parcial scip times: ', scip_time)\n time.sleep(1)\n break\n os.remove(scp_out)\n\n print('')\n print('Mog times: ', maxcut_time)\n sm = sum(maxcut_time)\n print('Mog total: ', sm)\n print('Mog avg: ', sm/exp_num)\n print('sssf avg: ', sum(sssf)/exp_num)\n print('')\n\n print('scip times: ', scip_time)\n ss = sum(scip_time)\n print('scip total: ', ss)\n print('scip avg: ', ss/exp_num)\n print('')\n\n print('Mog/scip', sm/ss)\n\n\nif __name__ == '__main__':\n main()","sub_path":"test_random.py","file_name":"test_random.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"532576297","text":"#\n# Codigo RC 1.0 - 03/06/2018\n# Lago Terra Alta, 3a visita em 04/06/2018\n# Wifi desabilitado no boot\n# Sem RTC externo\n# Sem Expansion Board (sem gravar no cartão de memoria)\n# Deepsleep de 10 minutos\n#\n\nflagDebug = False\nflagRun = True\nif flagDebug or flagRun:\n from machine import Timer\n chrono = Timer.Chrono()\n chrono.start()\n\n# Builtin modules\nfrom network import LoRa\nimport socket\nimport binascii\nimport struct\nimport time\nfrom machine import Pin, I2C, ADC, deepsleep\nimport machine\nfrom onewire import DS18X20, OneWire\nimport pycom\nimport os\n\npycom.heartbeat(False)\n\n# Additional modules\nimport bme280\nimport max44009\nimport cayenneLPP\nimport config\nimport myfuncs\n\n\nif flagDebug:\n lap1 = chrono.read_ms()\n print(\"Tempo de importacao dos modulos: {} ms\".format(lap1))\n\n\n#\n# Inicialização de LoRaWan com ABP\n#\n\nlora = LoRa(mode=LoRa.LORAWAN, region=LoRa.US915)\n\n# create an ABP authentication params\ndev_addr = struct.unpack(\">l\", binascii.unhexlify('260XXXX6'))[0]\nnwk_swkey = binascii.unhexlify('50BDE0FD219E1XXXXXXXXXXXXXXXXXXX')\napp_swkey = binascii.unhexlify('F9E4XXXXXXXXXXXXXXXXX3CBD3B830ED')\n\n# remove all the channels\nfor channel in range(0, 72):\n lora.remove_channel(channel)\n\nfor channel in range(0, 72):\n lora.add_channel(channel, frequency=config.LORA_FREQUENCY, dr_min=0, dr_max=3)\n\n# join a network using ABP (Activation By Personalization)\nlora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey))\n\n# create a LoRa socket\ns = socket.socket(socket.AF_LORA, socket.SOCK_RAW)\n\n# set the LoRaWAN data rate\ns.setsockopt(socket.SOL_LORA, socket.SO_DR, config.LORA_NODE_DR)\n\n# make the socket blocking\ns.setblocking(False)\n\nif flagDebug:\n lap2 = chrono.read_ms()\n print(\"Tempo apos inicializaco LoRA: {} ms\".format(lap2))\n\n\n#\n# Inicialização e leitura dos sensores\n#\nif flagRun:\n lap1 = chrono.read_ms()\n\ni2c = I2C(0, I2C.MASTER, pins=('G10', 'G9'),baudrate=400000)\nconnectedI2C = i2c.scan()\nif flagDebug:\n print(\"Connected I2C devices: \" + str(connectedI2C))\n\now = OneWire(Pin('G8'))\ntemp = DS18X20(ow)\nconnectedOW = ow.scan()\nif flagDebug:\n print(\"Connected 1-Wire devices: \" + str(connectedOW))\n\nilum = [] # Lista com as luminosidades lidas com o MAX44009\nbmet = [] # Lista com as temperaturas lidas com o BME280\nbmeh = [] # Lista com as umiadades lidas com o BME280\nbmep = [] # Lista com as pressoes lidas com o BME280\nowTemp = [] # Lista com as temperaturas lidas com o OneWire\n\nlight_s = False # Flag para indicar se o MAX44009 esta conectado\nbme_s = False # Flag para indicar se o BME280 esta conectado\now_s = False # Flag para indicar se possui algum sensor 1-Wire conectado\nif len(connectedOW) > 0:\n ow_s = True\n\nconnected_i2c = False # Flag para indicar se possui algum sensor I2C conectado\nif len(connectedI2C) > 0:\n connected_i2c = True\n\nif connected_i2c:\n for device in connectedI2C:\n if device == 0x4A: # MAX44009 - 74\n light_sensor = max44009.MAX44009(i2c)\n light_s = True\n elif device == 0x76: # BME280 - 118\n bme = bme280.BME280(i2c=i2c, pressure_mode=bme280.OSAMPLE_8, iir=bme280.FILTER_8)\n bme_s = True\n else:\n if flagDebug:\n print(\"I2C nao reconhecido\") # Dispositivo nao cadastrado\n\nif ow_s:\n count = 0\n for sensors in connectedOW:\n temp.start_conversion(temp.roms[count])\n count += 1\n\nif light_s:\n # Le iluminancia em lux do MAX44009\n data = int(light_sensor.illuminance_lux)\n ilum.append(data)\nif bme_s:\n # Le valores BME280 com media para ter maior precisao :\n numreadings = 15\n samples_temperature = [0.0]*numreadings; mean_temperature = 0.0\n samples_pressure = [0.0]*numreadings; mean_pressure = 0.0\n samples_humidity = [0.0]*numreadings; mean_humidity = 0.0\n for i in range (numreadings):\n samples_temperature[i], samples_pressure[i], samples_humidity[i] = bme.values\n mean_temperature = sum(samples_temperature)/len(samples_temperature)\n mean_pressure = sum(samples_pressure)/len(samples_pressure)\n mean_humidity = sum(samples_humidity)/len(samples_humidity)\n t = mean_temperature\n p = mean_pressure/100 # Pa -> hectoPa\n h = mean_humidity\n bmet.append(t)\n bmep.append(p)\n bmeh.append(h)\n\nif ow_s:\n count = 0\n for sensor in connectedOW:\n tempOW = temp.read_temp_async(temp.roms[count])\n # tempOW_c = myfuncs.sensor_calibration(sensor, tempOW)\n # tempOW_clpp = str(tempOW_c)\n # owTemp.append(tempOW_clpp)\n # print(\"Sensor: \" +str(sensor)+\"| Temperatura: \"+str(tempOW) +\"| Temperatura Calibrada: \"+str(tempOW_c))\n owTemp.append(tempOW)\n count += 1\n\nif flagDebug:\n lap3 = chrono.read_ms()\n print(\"Tempo apos sensores: {} ms\".format(lap3))\n\nif flagRun:\n lap2 = chrono.read_ms()\n timeSensors=lap2-lap1\n\n#\n# Criando pacote Cayenne LPP\n#\n\nlpp = cayenneLPP.CayenneLPP(size = 100, sock = s)\n\nif bme_s:\n lpp.add_temperature(bmet[0])\n lpp.add_barometric_pressure(bmep[0])\n lpp.add_relative_humidity(bmeh[0])\nif light_s:\n lpp.add_luminosity(ilum[0])\n\nowChannel = 150\n\nif ow_s:\n for tempValue in owTemp:\n val = float(tempValue)\n lpp.add_temperature(value = val, channel = owChannel)\n owChannel += 1\n\nVBAT = myfuncs.get_batt_mV()\n\nlpp.add_generic(lpp_id=2, values = VBAT, channel = 13, data_size = 2, is_signed = False, precision = 1)\n\nif machine.wake_reason()[0] == machine.PWRON_WAKE:\n pycom.nvs_erase_all() # 1st time power on\n\npayloadcount = pycom.nvs_get('count')\nif payloadcount is not None:\n payloadcount += 1\n pycom.nvs_set('count', payloadcount)\nelse:\n payloadcount = 1\n pycom.nvs_set('count', 1) # Starts from 1\nif flagDebug:\n print(\"# pacote LoRaWan = {}\".format(payloadcount))\n\nlpp.add_luminosity( value = payloadcount, channel = 155) # Numero do Pacote enviado\n\nif flagDebug:\n print(\"Tamanho do pacote LPP = {} bytes\".format(lpp.get_size()))\n\nif flagDebug:\n lap4 = chrono.read_ms()\n print(\"Tempo antes do LPP send: {} ms\".format(lap4))\n\nif flagRun:\n lap3 = chrono.read_ms()\n totalAwake = lap3+210+3\n\nlpp.add_luminosity( value = timeSensors, channel = 158) # Tempo dos sensores (inicializacao + leitura)\nlpp.add_luminosity( value = totalAwake, channel = 159) # Tempo total acordado\nlpp.send(reset_payload = True) # Envio do pacote LoRaWan usando Cayenne LPP\n\nif flagDebug:\n lap5 = chrono.read_ms()\n print(\"Tempo apos LPP send: {} ms\".format(lap5))\n\ntime.sleep_ms(300) # pausa para garantir o envio do pacote\n\n#\n# Entrando em deepsleep\n#\n\nif flagDebug:\n print(\"Entrando em deepsleep por 600s = 10 minutos...\")\n\nmachine.deepsleep(600*1000) # deep sleep por 10 minutos\n","sub_path":"NodeABP/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"52940141","text":"import argparse\nimport os\nimport pdb\nimport sys\n\nimport cv2\n\nimport constants\n\ndef make_video_recursive(directory, new_video=False):\n if directory[-1] != '/':\n directory += '/'\n files = [directory + f for f in os.listdir(directory)]\n interaction_data_dirs = [f for f in files if os.path.isdir(f)]\n all_frame_dirs = []\n for interaction_data_dir in interaction_data_dirs:\n interaction_files = [interaction_data_dir + '/' + f for f in os.listdir(interaction_data_dir)]\n frame_dirs = [f for f in interaction_files if os.path.isdir(f)]\n for frame_dir in frame_dirs:\n frame_dir_videos = [f for f in os.listdir(frame_dir) if f[-4:] == '.mp4']\n if new_video or len(frame_dir_videos) == 0:\n all_frame_dirs.append(frame_dir)\n print('Frame directories:', all_frame_dirs, len(all_frame_dirs))\n for frame_dir in all_frame_dirs:\n make_video(frame_dir)\n\ndef make_video(frame_dir, video_name=None):\n if frame_dir[-1] != '/':\n frame_dir += '/'\n frames = sorted([frame for frame in os.listdir(frame_dir) if frame.endswith(\".png\")],\n key=lambda f: int(f.split('.png')[0]))\n frame = cv2.imread(os.path.join(frame_dir, frames[-1]))\n height, width, layers = frame.shape\n fourcc = cv2.VideoWriter_fourcc(*'mp4v')\n if video_name is None:\n video_name = frame_dir.split('/')[-2] + '.mp4'\n print('video:', frame_dir + video_name)\n out = cv2.VideoWriter(frame_dir + video_name, fourcc, 10.0, (width, height))\n for frame in frames:\n out.write(cv2.imread(os.path.join(frame_dir, frame)))\n out.release()\n cv2.destroyAllWindows()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('directory', \n help=\"The frame directory if not using the recursive option. Otherwise, the directory of frame direcories.\")\n parser.add_argument('-v', '--video_name', help=\"The name of the video.\")\n parser.add_argument('-r', '--recursive', action='store_true', \n help=\"If True, make videos for all of the directories inside of the given directory.\")\n parser.add_argument('-n', '--new_video', action='store_true', \n help=\"If True, make a new video to overwrite the existing one. Otherwise, don't create a new video if one already exists.\")\n args = parser.parse_args(sys.argv[1:])\n if args.recursive:\n make_video_recursive(args.directory, args.new_video)\n else:\n make_video(args.directory, args.video_name)","sub_path":"video_maker.py","file_name":"video_maker.py","file_ext":"py","file_size_in_byte":2501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"229544433","text":"'''\nquestion link: \n\nhttps://practice.geeksforgeeks.org/problems/count-possible-triangles-1587115620/1/?track=DS-Python-Sorting&batchId=273\n\n\n'''\nimport timeit\n\ndef findNumberOfTriangles(arr,n):\n arr.sort()\n c=0\n for i in range(n):\n for next in range(i+1,n):\n sum=arr[i]+arr[next]\n for j in range(next+1,n):\n if sum>arr[j]:\n c+=1\n return c\n\n\ndef findTriangles(arr):\n arr.sort()\n n=len(arr)\n c=0\n for i in range(n-1,0,-1):\n l=0\n r=i-1\n while larr[i]:\n c+=r-l\n r-=1\n else:\n l+=1\n return c\n \n\nif __name__=='__main__':\n \n start=timeit.timeit()\n arr=[ 7,8,3,4,6,9]\n n=len(arr)\n c=findNumberOfTriangles(arr,n)\n end=timeit.timeit()\n print(c,end-start)\n \n s=timeit.timeit()\n d=findTriangles(arr)\n e=timeit.timeit()\n print(d,e-s)","sub_path":"practice/possible_triangles.py","file_name":"possible_triangles.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"10889837","text":"import os\nimport shutil\nimport tempfile\n\nimport pytest\n\nfrom galaxy.tool_util.deps.mulled.mulled_update_singularity_containers import docker_to_singularity, get_list_from_file, singularity_container_test\nfrom galaxy.util import which\nfrom ..util import external_dependency_management\n\n\ndef test_get_list_from_file():\n test_dir = tempfile.mkdtemp()\n try:\n list_file = os.path.join(test_dir, 'list_file.txt')\n with open(list_file, 'w') as f:\n f.write('bbmap:36.84--0\\nbiobambam:2.0.42--0\\nconnor:0.5.1--py35_0\\ndiamond:0.8.26--0\\nedd:1.1.18--py27_0')\n assert get_list_from_file(list_file) == ['bbmap:36.84--0', 'biobambam:2.0.42--0', 'connor:0.5.1--py35_0', 'diamond:0.8.26--0', 'edd:1.1.18--py27_0']\n finally:\n shutil.rmtree(test_dir)\n\n\n@external_dependency_management\n@pytest.mark.skipif(not which('singularity'), reason=\"requires singularity but singularity not on PATH\")\ndef test_docker_to_singularity(tmp_path):\n tmp_dir = str(tmp_path)\n docker_to_singularity('abundancebin:1.0.1--0', 'singularity', tmp_dir, no_sudo=True)\n assert tmp_path.joinpath('abundancebin:1.0.1--0').exists()\n\n\n@external_dependency_management\n@pytest.mark.skipif(not which('singularity'), reason=\"requires singularity but singularity not on PATH\")\ndef test_singularity_container_test(tmp_path):\n test_dir = tempfile.mkdtemp()\n try:\n for n in ['pybigwig:0.1.11--py36_0', 'samtools:1.0--1', 'yasm:1.3.0--0']:\n docker_to_singularity(n, 'singularity', test_dir, no_sudo=True)\n results = singularity_container_test({'pybigwig:0.1.11--py36_0': {'imports': ['pyBigWig'], 'commands': ['python -c \"import pyBigWig; assert(pyBigWig.numpy == 1); assert(pyBigWig.remote == 1)\"'], 'import_lang': 'python -c'}, 'samtools:1.0--1': {'commands': ['samtools --help'], 'import_lang': 'python -c', 'container': 'samtools:1.0--1'}, 'yasm:1.3.0--0': {}}, 'singularity', test_dir)\n assert 'samtools:1.0--1' in results['passed']\n assert results['failed'][0]['imports'] == ['pyBigWig']\n assert 'yasm:1.3.0--0' in results['notest']\n finally:\n shutil.rmtree(test_dir)\n","sub_path":"test/unit/tool_util/mulled/test_mulled_update_singularity_containers.py","file_name":"test_mulled_update_singularity_containers.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"130879524","text":"\r\n#合并两个顺序表\r\n\r\ndef merge_list(list1, list2):\r\n length1 = len(list1)\r\n length2 = len(list2)\r\n out_list = []\r\n i = 0\r\n j = 0\r\n while i 1:\n req.add_header('Referer', referer)\n if data:\n req.add_header('Content-Length', len(data))\n response = urlopen(req, timeout=60)\n if response.info().get('Content-Encoding') == 'gzip':\n buf = StringIO( response.read())\n f = gzip.GzipFile(fileobj=buf)\n data = f.read()\n f.close()\n else:\n data = response.read() \n if not NoCookie:\n # Cope with problematic timestamp values on RPi on OpenElec 4.2.1\n try:\n cj.save(cookiePath)\n except: pass\n response.close()\n return data\n\n \ndef postHtml(url, form_data={}, headers={}, compression=True):\n _user_agent = 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.1 ' + \\\n '(KHTML, like Gecko) Chrome/13.0.782.99 Safari/535.1'\n req = urllib2.Request(url)\n if form_data:\n form_data = urllib.urlencode(form_data)\n req = urllib2.Request(url, form_data)\n req.add_header('User-Agent', _user_agent)\n for k, v in headers.items():\n req.add_header(k, v)\n if compression:\n req.add_header('Accept-Encoding', 'gzip')\n response = urllib2.urlopen(req)\n data = response.read()\n cj.save(cookiePath)\n response.close()\n return data\n\n \ndef getHtml2(url):\n req = Request(url)\n response = urlopen(req, timeout=60)\n data = response.read()\n response.close()\n return data \n\n \ndef getVideoLink(url, referer):\n req2 = Request(url, '', headers)\n req2.add_header('Referer', referer)\n url2 = urlopen(req2).geturl()\n return url2\n\n\ndef cleantext(text):\n text = text.replace('–','-')\n text = text.replace('&','&')\n text = text.replace('’','\\'')\n text = text.replace('‘','\\'')\n text = text.replace('…','...')\n text = text.replace('"','\"')\n text = text.replace(''','`')\n text = text.replace('&','&')\n text = text.replace('ñ','ñ')\n return text\n\n\ndef addDownLink(name, url, mode, iconimage, desc, stream=None, fav='add', fanart=None):\n if fav == 'add': favtext = \"Add to\"\n elif fav == 'del': favtext = \"Remove from\"\n u = (sys.argv[0] +\n \"?url=\" + urllib.quote_plus(url) +\n \"&mode=\" + str(mode) +\n \"&name=\" + urllib.quote_plus(name))\n dwnld = (sys.argv[0] +\n \"?url=\" + urllib.quote_plus(url) +\n \"&mode=\" + str(mode) +\n \"&download=\" + str(1) +\n \"&name=\" + urllib.quote_plus(name))\n favorite = (sys.argv[0] +\n \"?url=\" + urllib.quote_plus(url) +\n \"&fav=\" + fav +\n \"&favmode=\" + str(mode) +\n \"&mode=\" + str('900') +\n \"&img=\" + urllib.quote_plus(iconimage) +\n \"&name=\" + urllib.quote_plus(name)) \n ok = True\n liz = xbmcgui.ListItem(name, iconImage=\"DefaultVideo.png\", thumbnailImage=iconimage)\n liz.setArt({'thumb': iconimage, 'icon': iconimage})\n if stream:\n liz.setProperty('IsPlayable', 'true')\n if len(desc) < 1:\n liz.setInfo(type=\"Video\", infoLabels={\"Title\": name})\n else:\n liz.setInfo(type=\"Video\", infoLabels={\"Title\": name, \"plot\": desc, \"plotoutline\": desc})\n if fanart:\n liz.setArt({'fanart': fanart})\n liz.addContextMenuItems([('[COLOR lime]Download Video[/COLOR]', 'xbmc.RunPlugin('+dwnld+')'),\n ('[COLOR lime]' + favtext + ' favorites[/COLOR]', 'xbmc.RunPlugin('+favorite+')')])\n ok = xbmcplugin.addDirectoryItem(handle=addon_handle, url=u, listitem=liz, isFolder=False)\n return ok\n \ndef playyt(url, name):\n iconimage = xbmc.getInfoImage(\"ListItem.Thumb\")\n liz=xbmcgui.ListItem(name, iconImage=\"DefaultFolder.png\", thumbnailImage=iconimage)\n liz.setInfo( type=\"Video\", infoLabels={ \"Title\": name } )\n xbmc.Player().play(url, liz, False)\n\ndef addDir(name, url, mode, iconimage, page=None, channel=None, section=None, keyword='', Folder=True, fanart=None):\n if url.startswith(\"plugin://\"):\n u = url\n else:\n u = (sys.argv[0] +\n \"?url=\" + urllib.quote_plus(url) +\n \"&mode=\" + str(mode) +\n \"&page=\" + str(page) +\n \"&channel=\" + str(channel) +\n \"§ion=\" + str(section) +\n \"&keyword=\" + urllib.quote_plus(keyword) +\n \"&name=\" + urllib.quote_plus(name))\n ok = True\n liz = xbmcgui.ListItem(name, iconImage=\"DefaultFolder.png\", thumbnailImage=iconimage)\n liz.setArt({'thumb': iconimage, 'icon': iconimage})\n if not fanart:\n fanart = 'https://raw.githubusercontent.com/DutchMusic/DutchMusic/master/plugin.video.DutchMusic/fanart.JPG'\n liz.setArt({'fanart': fanart})\n liz.setInfo(type=\"Video\", infoLabels={\"Title\": name})\n ok = xbmcplugin.addDirectoryItem(handle=addon_handle, url=u, listitem=liz, isFolder=Folder)\n return ok\n \ndef _get_keyboard(default=\"\", heading=\"\", hidden=False):\n \"\"\" shows a keyboard and returns a value \"\"\"\n keyboard = xbmc.Keyboard(default, heading, hidden)\n keyboard.doModal()\n if keyboard.isConfirmed():\n return unicode(keyboard.getText(), \"utf-8\")\n return default\n","sub_path":"script.dokionderhoud/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"504037744","text":"'''\naccess the information of turn loading\n'''\n\nimport sqlite3\nfrom datetime import datetime\nfrom datetime import timedelta\n\n\nclass TurnDB():\n \n def __init__(self):\n \n self.turn_conn = sqlite3.connect('turn.db')\n self.turn_curs = self.turn_conn.cursor()\n self.turn_curs.execute('''CREATE TABLE IF NOT EXISTS turn\n (turn_addr VARCHAR(15) PRIMARY KEY,\n loading REAL,\n history REAL,\n conn_state BOOLEAN,\n resolution INTEGER,\n time TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL)''')\n\n def get_turn_info(self, addr):\n '''\n get the info of the turn server\n '''\n\n self.turn_curs.execute(\n '''SELECT * from turn where turn_addr = ?''', (addr,))\n\n # return None if doesn't exist\n return self.turn_curs.fetchone()\n \n def get_min_loading_turn_addr(self):\n '''\n get the info of the turn server which has the minimum loading\n '''\n\n #self.turn_curs.execute(\n # '''SELECT turn_addr, history, loading FROM turn WHERE loading = \n # (SELECT min(loading) FROM turn)''')\n\n self.turn_curs.execute(\n '''SELECT * FROM turn WHERE conn_state = 1 AND loading < 80 ORDER BY loading''')\n \n turn_info = self.turn_curs.fetchall()\n\n if turn_info:\n for i in range(0, len(turn_info)):\n data_time = datetime.strptime(turn_info[i][5], \"%Y-%m-%d %H:%M:%S\")\n if (data_time - data_time.now()) > timedelta(seconds = 185):\n self.update_turn_info(turn_info[i][0], turn_info[i][1], turn_info[i][2], 0)\n else:\n return turn_info[i][0]\n\n return \"0.0.0.0\"\n\n def update_turn_info(self, addr, loading, history, conn_state = 1, resolution = 1080):\n '''\n update data of the turn server\n '''\n\n self.delete_turn_info(addr)\n self.add_turn_info(addr, loading, history, conn_state, resolution)\n\n def add_turn_info(self, addr, loading, history = 0.0, conn_state = 1, resolution = 1080):\n '''\n add the turn server into the database\n '''\n\n ins = 'INSERT INTO turn\\\n (turn_addr, loading, history, conn_state, resolution) VALUES(?, ?, ?, ?, ?)'\n\n self.turn_curs.execute(ins, (addr, loading, history, conn_state, resolution))\n self.turn_conn.commit()\n\n def delete_turn_info_disconnect(self):\n '''\n delete the turn server if it doesn't send data over 3 time windows(9 mins)\n '''\n\n pass\n\n def delete_turn_info(self, addr):\n '''\n delete turn server\n '''\n\n self.turn_curs.execute(\n '''DELETE FROM turn where turn_addr = ?''', (addr,))\n self.turn_conn.commit()\n\n def get_connecting_turn_info(self):\n '''\n return a turn address or return False\n '''\n\n self.turn_curs.execute(\n '''SELECT * FROM turn WHERE conn_state = 1''')\n \n return self.turn_curs.fetchone()\n","sub_path":"controller_dresolution/turn_db_manipulation.py","file_name":"turn_db_manipulation.py","file_ext":"py","file_size_in_byte":3049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"75011441","text":"from django.shortcuts import render, get_object_or_404, redirect, render_to_response\nfrom django.utils import timezone\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nfrom django.db.models import Sum\nfrom django.db.models import Q\nfrom django.http import HttpResponse, Http404, JsonResponse\nfrom django.contrib import messages\nfrom django.core.cache import cache\nfrom django.views import View\nfrom django.views.generic import ListView\nfrom django.utils.decorators import method_decorator\n\nfrom datetime import date, timedelta\nimport json\n\nfrom .forms import ExpenseForm, SelectDateExpenseForm, SelectDateRangeExpenseForm\nfrom .models import Expense, Remark\nfrom decorators import login_required_message\n\n# Create your views here.\n\n\n\nclass AddExpense(View):\n form_class = ExpenseForm\n template_name = \"add_expense.html\"\n context = {\n 'form': form_class,\n 'title': \"Add expense\"\n }\n\n @method_decorator(login_required_message)\n def dispatch(self, *args, **kwargs):\n return super().dispatch(*args, **kwargs)\n\n def get(self, request, *args, **kwargs):\n last_10_expenses = Expense.objects.all(user=request.user).order_by(\n '-created_at', '-timestamp',\n )[:10]\n \n self.context['objects'] = last_10_expenses\n self.context['total'] = Expense.objects.amount_sum(user=request.user)\n return render(request, self.template_name, self.context)\n\n def post(self, request, *args, **kwargs):\n form = self.form_class(request.POST)\n if form.is_valid():\n amount = form.cleaned_data.get('amount')\n remark = form.cleaned_data.get('remark', '').title()\n timestamp = form.cleaned_data.get('timestamp')\n\n expense = Expense.objects.create(\n user = request.user,\n amount = amount,\n timestamp = timestamp\n )\n\n if remark:\n try:\n rem = Remark.objects.get(user=request.user, name=remark)\n except:\n rem = Remark.objects.create(user=request.user, name=remark)\n expense.remark = rem\n expense.save()\n \n\n return HttpResponse(status=200)\n else:\n return HttpResponse(status=400)\n\n\n\nclass UpdateExpense(View):\n form_class = ExpenseForm\n template_name = \"update_expense.html\"\n context = {\n \"title\": \"Update expense\"\n }\n\n @method_decorator(login_required_message)\n def dispatch(self, *args, **kwargs):\n return super().dispatch(*args, **kwargs)\n\n def get_object(self, request, *args, **kwargs):\n id = int(kwargs['id'])\n instance = Expense.objects.all(user=request.user).filter(id=id).first()\n\n if not instance:\n raise Http404\n return instance\n\n def get(self, request, *args, **kwargs):\n instance = self.get_object(request, *args, **kwargs)\n\n # thirty_day = date.today() - timedelta(days=30)\n # if not instance.timestamp >= thirty_day:\n # return HttpResponse(\"

    Too late! Cannot be changed now.

    \", status=400)\n\n initial_data = {\n 'amount': instance.amount,\n 'remark': instance.remark,\n 'timestamp': instance.timestamp\n }\n form = self.form_class(initial=initial_data)\n self.context['form'] = form\n return render(request, self.template_name, self.context)\n\n\n def post(self, request, *args, **kwargs):\n instance = self.get_object(request, *args, **kwargs)\n\n form = self.form_class(request.POST)\n if form.is_valid():\n amount = form.cleaned_data.get('amount')\n remark = form.cleaned_data.get('remark', '').title()\n timestamp = form.cleaned_data.get('timestamp')\n\n instance.amount = amount\n instance.timestamp = timestamp\n rem = None\n if remark:\n try:\n rem = Remark.objects.get(user=request.user, name=remark)\n except:\n rem = Remark.objects.create(user=request.user, name=remark)\n \n instance.remark = rem\n instance.save()\n\n return HttpResponse(status=200)\n else:\n return HttpResponse(status=400)\n\n\n\nclass ExpenseList(View):\n template_name = \"expense_list.html\"\n\n @method_decorator(login_required_message)\n def dispatch(self, *args, **kwargs):\n return super().dispatch(*args, **kwargs)\n\n\n def get(self, request, *args, **kwargs):\n objects_list = Expense.objects.all(user=request.user)\n first_date = None\n\n if objects_list:\n first_date = objects_list.last().timestamp or None\n\n q = request.GET.get(\"q\")\n object_total = None\n if q:\n objects_list = objects_list.filter(\n Q(remark__name__icontains=q) |\n Q(amount__icontains=q)\n ).distinct()\n object_total = objects_list.aggregate(Sum('amount'))['amount__sum']\n\n order_field = request.GET.get(\"field\")\n if order_field:\n ordering = request.GET.get(\"order\", \"\")+order_field\n print(ordering)\n objects_list = objects_list.order_by(ordering)\n\n paginator = Paginator(objects_list, 15)\n\n page = request.GET.get('page')\n\n try:\n objects = paginator.page(page)\n except PageNotAnInteger:\n objects = paginator.page(1)\n except EmptyPage:\n objects = paginator.page(paginator.num_pages)\n\n total = Expense.objects.amount_sum(user=request.user)\n\n context = {\n \"title\": \"Expenses\",\n \"objects\": objects,\n \"total\": total,\n \"first_date\": first_date,\n \"object_total\": object_total,\n }\n\n return render(request, self.template_name, context)\n\n\n# class DayWiseExpense(ListView):\n\n# template_name = \"day-expense.html\"\n# paginate_by = 30\n\n# @method_decorator(login_required)\n# def dispatch(self, *args, **kwargs):\n# return super().dispatch(*args, **kwargs)\n\n# def get_queryset(self, *args, **kwargs):\n# return Expense.objects.all(user=self.request.user).dates('timestamp', 'day').order_by('-timestamp')\n\n# def get_context_data(self, *args, **kwargs):\n# context = super().get_context_data(*args, **kwargs)\n# queryset = self.get_queryset()\n# days = queryset\n# data = []\n# for day in days:\n# sum_day = queryset.filter(timestamp=day).aggregate(Sum('amount'))['amount__sum']\n# data.append((day, sum_day))\n \n# context['data'] = data\n# context['title'] = 'Day Wise Expense'\n# return context\n\n\n\nclass DayWiseExpense(View):\n\n template_name = \"day-expense.html\"\n context = {\n 'title': 'Day Wise Expense',\n }\n\n @method_decorator(login_required_message)\n def dispatch(self, *args, **kwargs):\n return super().dispatch(*args, **kwargs)\n\n def get(self, request, *args, **kwargs):\n expense = Expense.objects.all(user=request.user)\n days = expense.dates('timestamp', 'day').order_by('-timestamp')\n data = []\n for day in days:\n sum_day = expense.filter(timestamp=day).aggregate(Sum('amount'))['amount__sum']\n data.append((day, sum_day))\n \n self.context['data'] = data\n return render(request, self.template_name, self.context)\n\n\n\nclass MonthWiseExpense(View):\n template_name = \"month-expense.html\"\n context = {\n 'title': 'Monthly Expense',\n }\n\n @method_decorator(login_required_message)\n def dispatch(self, *args, **kwargs):\n return super().dispatch(*args, **kwargs)\n\n def get(self, request, *args, **kwargs):\n dates = Expense.objects.all(user=request.user).dates('timestamp', 'month')\n data = []\n for date in dates:\n amount = Expense.objects.this_month(\n user=request.user, year=date.year, month=date.month\n ).aggregate(Sum('amount'))['amount__sum']\n data.append((date, amount))\n self.context['data'] = data\n return render(request, self.template_name, self.context)\n\n\n\nclass DateSearch(View):\n date_form_class = SelectDateExpenseForm\n range_form_class = SelectDateRangeExpenseForm\n template_name = \"search.html\"\n context = {\n \"title\": \"Search\"\n }\n\n @method_decorator(login_required_message)\n def dispatch(self, *args, **kwargs):\n return super().dispatch(*args, **kwargs)\n\n def get(self, request, *args, **kwargs):\n self.context['date_form'] = self.date_form_class()\n self.context['range_form'] = self.range_form_class()\n\n if request.GET:\n date_form = self.date_form_class(request.GET)\n range_form = self.range_form_class(request.GET)\n\n objects = None\n\n if range_form.is_valid():\n remark = range_form.cleaned_data.get('remark')\n f_dt = range_form.cleaned_data.get('from_date')\n t_dt = range_form.cleaned_data.get('to_date')\n objects = Expense.objects.all(user=request.user).filter(timestamp__range=(f_dt, t_dt))\n if remark:\n objects = objects.filter(remark__name__icontains=remark)\n else:\n range_form = self.range_form_class()\n\n if date_form.is_valid():\n remark = date_form.cleaned_data.get('remark')\n dt = date_form.cleaned_data.get('date')\n objects = Expense.objects.all(user=request.user).filter(timestamp=dt)\n if remark:\n objects = objects.filter(remark__name__icontains=remark)\n else:\n date_form = self.date_form_class()\n\n if objects:\n object_total = objects.aggregate(Sum('amount'))['amount__sum']\n else:\n object_total = None\n\n \n self.context['date_form'] = date_form\n self.context['range_form'] = range_form\n self.context['objects'] = objects\n self.context['object_total'] = object_total\n\n return render(request, self.template_name, self.context)\n\n\n\nclass GoToExpense(View):\n \"\"\"\n provies expenses for particular day, month or year.\n \"\"\"\n template_name = 'goto.html'\n\n @method_decorator(login_required_message)\n def dispatch(self, *args, **kwargs):\n return super().dispatch(*args, **kwargs)\n\n def get(self, request, *args, **kwargs):\n day = kwargs.get('day')\n month = kwargs.get('month')\n year = kwargs.get('year')\n \n if day:\n objects = Expense.objects.this_day(user=request.user, year=year, month=month, day=day)\n elif month:\n objects = Expense.objects.this_month(user=request.user, year=year, month=month)\n elif year:\n objects = Expense.objects.this_year(user=request.user, year=year)\n\n goto_total = objects.aggregate(Sum('amount'))['amount__sum']\n\n paginator = Paginator(objects, 50)\n\n page = request.GET.get('page')\n\n try:\n objects = paginator.page(page)\n except PageNotAnInteger:\n objects = paginator.page(1)\n except EmptyPage:\n objects = paginator.page(paginator.num_pages)\n\n context = {\n \"title\": \"Expenses\",\n \"objects\": objects,\n \"goto_total\": goto_total,\n }\n\n return render(request, self.template_name, context)\n\n\n\nclass GoToRemarkWiseExpense(View):\n \"\"\"\n provies expenses for particular day, month or year.\n \"\"\"\n template_name = 'remark-month-expense.html'\n\n @method_decorator(login_required_message)\n def dispatch(self, *args, **kwargs):\n return super().dispatch(*args, **kwargs)\n\n def get(self, request, *args, **kwargs):\n day = int(kwargs.get('day', 0))\n month = int(kwargs.get('month', 0))\n year = int(kwargs.get('year', 0))\n _day = None\n _month = None\n _year = None\n \n if day:\n objects = Expense.objects.this_day(user=request.user, year=year, month=month, day=day)\n _day = date(year, month, day)\n elif month:\n objects = Expense.objects.this_month(user=request.user, year=year, month=month)\n _month = date(year, month, 1)\n elif year:\n objects = Expense.objects.this_year(user=request.user, year=year)\n _year = date(year, 1, 1)\n\n objects = objects.select_related('remark')\n remarks = set()\n for instance in objects:\n remarks.add(instance.remark)\n\n remark_dict = {}\n for remark in remarks:\n remark_dict[remark] = objects.filter(remark=remark).aggregate(\n Sum('amount')\n )['amount__sum']\n\n remark_dict = sorted(remark_dict.items(), key=lambda x: x[1], reverse=True)\n\n total = objects.aggregate(Sum('amount'))['amount__sum']\n\n context = {\n \"title\": \"Expenses\",\n \"remarks\": remark_dict,\n \"total\": total,\n \"day\": _day,\n \"month\": _month,\n \"year\": _year,\n }\n\n return render(request, self.template_name, context)\n\n\n\nclass GetRemark(View):\n \"\"\"\n will be used to autocomplete the remarks\n \"\"\"\n @method_decorator(login_required_message)\n def dispatch(self, *args, **kwargs):\n return super().dispatch(*args, **kwargs)\n\n def get(self, request, *args, **kwargs):\n if request.is_ajax():\n q = request.GET.get('term', '')\n # remarks = Expense.objects.all(user=request.user).filter(remark__icontains=q).order_by(\n # ).values_list('remark', flat=True).distinct()\n remarks = Remark.objects.filter(user=request.user).filter(name__icontains=q).order_by(\n ).values_list('name', flat=True)\n results = []\n for remark in remarks:\n remark_json = {}\n remark_json['value'] = remark\n results.append(remark_json)\n data = json.dumps(results)\n else:\n data = 'fail'\n mimetype = 'application/json'\n return HttpResponse(data, mimetype)\n\n\n\nclass GetYear(View):\n \"\"\"\n return all the year in which expenses are registered.\n \"\"\"\n @method_decorator(login_required_message)\n def dispatch(self, *args, **kwargs):\n return super().dispatch(*args, **kwargs)\n\n def get(self, request, *args, **kwargs):\n cache_key = 'expense_year'\n cache_time = 15768000 # 182.5 days\n data = cache.get(cache_key)\n\n if not data:\n years = Expense.objects.all(user=request.user).dates('timestamp', 'year')\n result = []\n\n for y in years:\n result.append(y.year)\n data = json.dumps(result)\n\n cache.set(cache_key, data, cache_time)\n\n return HttpResponse(data, content_type='application/json')\n\n\n\nclass Error404(View):\n def get(self, request, *args, **kwargs):\n return render(request, \"404.html\", {})\n\n\nclass Error500(View):\n def get(self, request, *args, **kwargs):\n return render(request, \"500.html\", {})\n\n\nclass Error400(View):\n def get(self, request, *args, **kwargs):\n return render(request, \"400.html\", {})\n\n\nclass Error403(View):\n def get(self, request, *args, **kwargs):\n return render(request, \"403.html\", {})","sub_path":"expense/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":15702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"297874060","text":"from PIL import Image\n\nimages = []\n\nhand = input(\"Please input hand: \")\nhand_length = 0\n\nfolder = \"hai\"\nfilenames = []\nkakan_idx = []\nseperates = []\n\ntiles = []\nfor c in hand.split()[0]:\n if c.isdigit():\n tiles.append(c)\n hand_length += 1\n elif c.isalpha():\n tiles = [num+c for num in tiles]\n for tile in tiles:\n filenames.append(f\"{folder}/{tile}.png\")\n tiles = []\n\nseperates.append(hand_length-1)\n\nfor file in filenames:\n images.append(Image.open(file))\n\ni = 0\ntiles = []\ncall = \" \".join(hand.split()[1:])\nwhile i < len(call):\n c = call[i]\n if c == \"p\":\n from_whom = call[i+1]\n idx = 0\n if from_whom == \"l\":\n idx = 0\n elif from_whom == \"m\":\n idx = 1\n elif from_whom == \"r\":\n idx = 2\n i += 2\n\n name = call[i:i+2]\n name = f\"{folder}/{name}.png\"\n i += 2\n for j in range(0, 3):\n if j == idx:\n img = Image.open(name)\n rotated = Image.new(\"RGBA\", (img.size[1], img.size[1]))\n rotated.paste(img.rotate(90, expand=True), (0, img.size[1]-img.size[0]))\n images.append(rotated)\n else:\n img = Image.open(name)\n images.append(img)\n seperates.append(seperates[-1]+3)\n elif c == \"c\":\n from_whom = call[i+1]\n idx = 0\n if from_whom == \"l\":\n idx = 0\n elif from_whom == \"m\":\n idx = 1\n elif from_whom == \"r\":\n idx = 2\n i += 2\n\n names = [call[i], call[i+1], call[i+2]]\n names = [f\"{folder}/{name+call[i+3]}.png\" for name in names]\n i += 3\n for j in range(0, 3):\n if j == idx:\n img = Image.open(names[j])\n rotated = Image.new(\"RGBA\", (img.size[1], img.size[1]))\n rotated.paste(img.rotate(90, expand=True), (0, img.size[1]-img.size[0]))\n images.append(rotated)\n else:\n img = Image.open(names[j])\n images.append(img)\n seperates.append(seperates[-1]+3)\n elif c == \"k\":\n\n mode = call[i+1]\n i += 1\n\n idx = 0\n if mode != \"a\" or mode != \"k\":\n from_whom = call[i+1]\n if from_whom == \"l\":\n idx = 0\n elif from_whom == \"m\":\n idx = 1\n elif from_whom == \"r\":\n idx = 3\n if mode == \"k\":\n from_whom = call[i+1]\n if from_whom == \"l\":\n idx = 0\n elif from_whom == \"m\":\n idx = 1\n elif from_whom == \"r\":\n idx = 2\n if mode != \"a\":\n i += 2\n else:\n i += 1\n\n if mode == \"a\":\n name = call[i:i+2]\n name = f\"{folder}/{name}.png\"\n images.append(Image.open(f\"{folder}/b.png\"))\n images.append(Image.open(name))\n images.append(Image.open(name))\n images.append(Image.open(f\"{folder}/b.png\"))\n i += 1\n seperates.append(seperates[-1]+4)\n elif mode == \"k\":\n name = call[i:i+2]\n name = f\"{folder}/{name}.png\"\n for j in range(3):\n if j == idx:\n kakan_idx.append(len(images))\n\n img = Image.open(name)\n rotated = Image.new(\"RGBA\", (img.size[1], 2*img.size[0]))\n rotated.paste(img.rotate(90, expand=True), (0, 0))\n rotated.paste(img.rotate(90, expand=True), (0, img.size[0]))\n images.append(rotated)\n else:\n img = Image.open(name)\n images.append(img)\n i += 2\n seperates.append(seperates[-1]+3)\n elif mode == \"m\":\n name = call[i:i+2]\n name = f\"{folder}/{name}.png\"\n i += 2\n for j in range(4):\n if j == idx:\n img = Image.open(name)\n rotated = Image.new(\"RGBA\", (img.size[1], img.size[1]))\n rotated.paste(img.rotate(90, expand=True), (0, img.size[1]-img.size[0]))\n images.append(rotated)\n else:\n img = Image.open(name)\n images.append(img)\n seperates.append(seperates[-1]+4)\n\n i += 1\n\nwidths, heights = zip(*(img.size for img in images))\ntotal_width = sum(widths)\nif call != \"\":\n total_width += max(widths)*(len(seperates)-1)\n\nmax_height = max(heights)\n\nnew_image = Image.new(\"RGBA\", (total_width, max_height))\n\nx_offset = 0\ny_offset = max(heights)-max(widths) if len(kakan_idx) > 0 else 0\n\nseperates.pop()\nfor i, img in enumerate(images):\n if i in kakan_idx:\n new_image.paste(img, (x_offset, 0))\n else:\n new_image.paste(img, (x_offset, y_offset))\n\n if i in seperates:\n x_offset += max(widths) + img.size[0]\n else:\n x_offset += img.size[0]\n\nnew_image.save(f\"{hand}.png\")","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"568757110","text":"import logging\n#ip初始评分\nMAX_SCORE=50\n#日志默认配置\nLOG_LEVEL=logging.INFO #默认级别\nLOG_FMT='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s'\nLOG_DATEFMT='%Y-%M-%d %H:%M:%S'\nLOG_FILENAME='log.log'\n\n#测试代理的ip超时时间\nTEST_TIMEOUT=15\n\n#MongoDB的数据的的URL\nMONGO_URL='mongodb://127.0.0.1:27017'\n#获取每个网页的间隔\nSLEEP_TIME=1\n\n# 配置代理爬虫列表\nPROXIES_SPIDERS = [\n 'core.proxy_spider.proxy_spider.IphaiSpider',\n 'core.proxy_spider.proxy_spider.XiciSpider',\n 'core.proxy_spider.proxy_spider.ProxylistplusSpider',\n]\n\n#爬虫的时间间隔\nRUN_SPIDERS_INTERVAL=12\n\n#用于配置检测代理ip的异步数量\nTEST_PROXIES_ASYNC_COUNT=10\n\n#检测代理ip的时间间隔\nRUN_PROXY_TEST_INTERVAL=2\n\n#获取最大IP的数量;值越下,可以信越高,随机性就越差\nPROXIES_MAX_COUNT=10","sub_path":"ip代理池/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"141195611","text":"# -*- coding: utf-8 -*-\n\nfrom django import forms\nfrom django.forms import ModelForm\nfrom models import Subscription\n\nclass SubscriptionForm(ModelForm):\n def __init__(self, *args, **kwargs):\n super(SubscriptionForm, self).__init__(*args, **kwargs)\n\n self.fields['user_name'].required = True\n self.fields['email'].required = True\n\n class Meta:\n model = Subscription\n fields = ['user_name', 'email', ]\n widjets = {\n 'user_name': forms.TextInput(attrs={'placeholder': 'Имя пользователя'}),\n 'email': forms.EmailInput(attrs={'placeholder': 'Имейл'}),\n }","sub_path":"src/apps/subscription/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"492533388","text":"from typing import List\nfrom fastapi import APIRouter\nfrom fastapi import Depends\nfrom fastapi import FastAPI\nfrom fastapi import HTTPException\nfrom fastapi import Response\nfrom fastapi import status\n\nfrom ..exseptions import EntityConflictError, EntiyDoesNotExistError\nfrom ..accounts.schemas import Account\nfrom ..accounts.auth import get_current_user\nfrom .schemas import ShopName, Shop\nfrom .service import ShopsServices\n\n\nrouter = APIRouter(prefix='/shops')\n\n\ndef initialize_app(app: FastAPI):\n app.include_router(router)\n\n\n@router.get('', response_model=List[Shop], tags=['Shops'])\ndef get_user_shops(\n current_account: Account = Depends(get_current_user),\n shop_service: ShopsServices = Depends(),\n):\n return shop_service.get_shops(current_account)\n\n\n@router.post(\n '',\n response_model=Shop,\n status_code=status.HTTP_201_CREATED,\n tags=['Shops'],\n)\ndef add_new_shop(\n new_shop: ShopName,\n current_account: Account = Depends(get_current_user),\n shop_service: ShopsServices = Depends(),\n):\n try:\n return shop_service.add_new_shop(new_shop, current_account)\n except EntityConflictError:\n raise HTTPException(status.HTTP_409_CONFLICT)\n\n\n@router.patch('/{shop_id}', response_model=Shop, tags=['Shops'])\ndef edit_shop(\n shop_id: int,\n shop: ShopName,\n current_account: Account = Depends(get_current_user),\n shop_service: ShopsServices = Depends(),\n):\n edit_shop = Shop(\n id=shop_id,\n name=shop.name,\n )\n try:\n return shop_service.edit_shop(edit_shop, current_account)\n except EntiyDoesNotExistError:\n raise HTTPException(status.HTTP_404_NOT_FOUND)\n\n\n@router.delete(\n '/{shop_id}',\n status_code=status.HTTP_204_NO_CONTENT,\n tags=['Shops'],\n)\ndef delete_shop(\n shop_id: int,\n current_account: Account = Depends(get_current_user),\n shop_service: ShopsServices = Depends(),\n):\n try:\n shop_service.delete_shop(shop_id, current_account)\n return Response()\n except EntiyDoesNotExistError:\n raise HTTPException(status.HTTP_404_NOT_FOUND)\n","sub_path":"src/ShoppingAPIService/shops/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"320954409","text":"from __future__ import annotations\nfrom enum import Enum\n\n__NAMESPACE__ = \"http://www.travelport.com/schema/sharedUprofile_v20_0\"\n\n\nclass TypeProfileComponentType1(Enum):\n \"\"\"Specifies the component names.\n\n (i.e AccountInfo, AirPreference, TravelDocument etc)\n \"\"\"\n ACCOUNT_INFO = \"AccountInfo\"\n TRAVELER_INFO = \"TravelerInfo\"\n TRAVELER_IDENTITY_INFORMATION = \"TravelerIdentityInformation\"\n TRAVEL_DOCUMENT = \"TravelDocument\"\n ACCOUNTING_REFERENCE = \"AccountingReference\"\n POLICY_REFERENCE = \"PolicyReference\"\n LOYALTY_PROGRAM_ENROLLMENT = \"LoyaltyProgramEnrollment\"\n CONTRACT = \"Contract\"\n COMMISSION = \"Commission\"\n SERVICE_FEE = \"ServiceFee\"\n REMARK = \"Remark\"\n ALTERNATE_CONTACT = \"AlternateContact\"\n ALTERNATE_CONTACT_ADDRESS = \"AlternateContactAddress\"\n ALTERNATE_CONTACT_PHONE = \"AlternateContactPhone\"\n ALTERNATE_CONTACT_ELECTRONIC_ADDRESS = \"AlternateContactElectronicAddress\"\n COMMISSION_REFERENCE = \"CommissionReference\"\n ADDRESS = \"Address\"\n PHONE = \"Phone\"\n ELECTRONIC_ADDRESS = \"ElectronicAddress\"\n AIR_PREFERENCE = \"AirPreference\"\n VEHICLE_PREFERENCE = \"VehiclePreference\"\n HOTEL_PREFERENCE = \"HotelPreference\"\n RAIL_PREFERENCE = \"RailPreference\"\n PROFILE_PARENT_HISTORY = \"ProfileParentHistory\"\n FIELD_DATA = \"FieldData\"\n FIELD_GROUP_DATA = \"FieldGroupData\"\n ADVISORY = \"Advisory\"\n AGENCY_GROUP_INFO = \"AgencyGroupInfo\"\n AGENCY_INFO = \"AgencyInfo\"\n BRANCH_GROUP_INFO = \"BranchGroupInfo\"\n BRANCH_INFO = \"BranchInfo\"\n AGENT_INFO = \"AgentInfo\"\n TRAVELER_GROUP_INFO = \"TravelerGroupInfo\"\n PROFILE_STATUS = \"ProfileStatus\"\n PROFILE_LINK = \"ProfileLink\"\n OTHER_PREFERENCE = \"OtherPreference\"\n FORM_OF_PAYMENT = \"FormOfPayment\"\n EXTERNAL_IDENTIFIER = \"ExternalIdentifier\"\n","sub_path":"travelport/models/type_profile_component_type_1.py","file_name":"type_profile_component_type_1.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"100704461","text":"\nimport csv\nimport os\nfrom elasticsearch import Elasticsearch\n\n#Initalize Object#\nes = Elasticsearch(HOST=\"http://localhost\", PORT=9200)\n\n#Create an index in ES, ignore status code 400 (index already exists)\nes.indices.create(index = \"wrasslers\",ignore=400)\n\n#Build the csv indices using your csv data#\nwith open(os.path.expanduser(\"~/Projects/Elastic-Search/data/wwf.csv\")) as f:\n reader = csv.DictReader(f)\n for line in reader:\n #If uniaue ID in excel file ne _source unique ID\n es.index(index=\"wrasslers\", doc_type = \"world_champions\", body = line)\n\n \n\n#Match Query#\n#http://localhost:9200/wrasslers/_search?q=cena\nes.search(index=\"wrasslers\", body={\n \"query\": {\n \"multi_match\" : {\n \"query\" : \"kane\",\n \"fields\" : [\"Date\", \"Days\", \"Description\", \"ID\", \"Location\", \"Reign\", \"Show\", \"Wrestler^3\"]\n }\n }\n }\n)\n\n#Boost Ressults using certain field#\nes.search(index=\"wrasslers\", body={\n \"query\": {\n \"multi_match\" : {\n \"query\" : \"cena\",\n \"fields\" : [\"Date\", \"Days\", \"Description\", \"ID\", \"Location\", \"Reign\", \"Show\", \"Wrestler^3\"]\n }\n }\n }\n)\n \nes.search(index=\"wrasslers\", body={\n \"query\": {\n \"multi_match\" : {\n \"query\" : \"wes bailey\",\n \"fields\" : [\"Date\", \"Days\", \"Description^5\", \"ID\", \"Location\", \"Reign\", \"Show\", \"Wrestler\"]\n }\n }\n }\n)\n","sub_path":"code/examples/wrasslers_examples.py","file_name":"wrasslers_examples.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"571076718","text":"import datetime\nimport json\nimport os\n\nfrom log import logger, color\n\ndb_dir = \".db\"\nif not os.path.isdir(db_dir):\n os.mkdir(db_dir)\n\n\ndef load_db() -> dict:\n with open(localdb_file, 'r', encoding='utf-8') as fp:\n return json.load(fp)\n\n\ndef save_db(db):\n with open(localdb_file, 'w', encoding='utf-8') as fp:\n json.dump(db, fp, ensure_ascii=False, indent=4)\n\n\ndef update_db(callback):\n db = load_db()\n\n callback(db)\n\n save_db(db)\n\n return db\n\n\ndef load_db_for(accountName):\n db = load_db()\n\n accountDb = get_account_from_db(accountName, db)\n\n return accountDb\n\n\ndef save_db_for(accountName, accountDb):\n db = load_db()\n\n set_account_to_db(accountName, db, accountDb)\n\n save_db(db)\n\n\ndef update_db_for(accountName, callback):\n db = load_db()\n\n accountDb = get_account_from_db(accountName, db)\n callback(accountDb)\n\n save_db(db)\n\n return db\n\n\ndef get_account_from_db(accountName, db):\n if \"accounts\" not in db:\n db[\"accounts\"] = {}\n accounts = db[\"accounts\"]\n if accountName not in accounts:\n accounts[accountName] = {}\n account = accounts[accountName]\n return account\n\n\ndef set_account_to_db(accountName, db, accountDb):\n if \"accounts\" not in db:\n db[\"accounts\"] = {}\n accounts = db[\"accounts\"]\n\n accounts[accountName] = accountDb\n\n\ndef init_db():\n save_db({\n \"created_at\": datetime.datetime.now().timestamp(),\n \"created_at_str\": datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"),\n })\n logger.info(color(\"bold_green\") + \"数据库已初始化完毕\")\n\n\nlocaldb_file = os.path.join(db_dir, 'db.json')\n# 如果未创建,则初始化\nif not os.path.isfile(localdb_file):\n init_db()\n# 检测数据库是否损坏,若损坏则重新初始化\ntry:\n load_db()\nexcept json.decoder.JSONDecodeError as e:\n logger.error(\"数据库似乎损坏了,具体出错情况如下,将重新初始化数据库文件\", exc_info=e)\n init_db()\n","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"116311539","text":"import math\nfrom datetime import datetime, timedelta\nfrom random import randint\nfrom itertools import combinations\nfrom typing import List\n\nfrom ..model import TaskState, TugState, ShipState, ChargeTypeList, Tug, Task, Ship, ChargeType\nfrom ..port import get_pier_latlng\nfrom ..settings import PENALTY, TUG_SPEED\nfrom .cutil import c_move_dis_to_time, c_count_dis\nfrom typing import Union\n\ndef count_move_dis(start, to):\n \"\"\"Calculate moving distance from a coordinate to a pier\n\n Args:\n start ((float, float)): latitide and longitude\n to (int): pier number\n\n Returns:\n (float): distance in km\n \"\"\"\n dest = get_pier_latlng(to)\n dis = count_dis(float(start[0]), float(start[1]), float(dest[0]), float(dest[1]))\n return dis\n\n\ndef move_dis_to_time(dis, velo=TUG_SPEED):\n \"\"\"Convert moving distance to time\n \"\"\"\n return timedelta(hours=c_move_dis_to_time(dis, velo))\n\n\ndef count_move_time(start, to, velo=TUG_SPEED):\n \"\"\"Calculate moving time from a coordinate to a pier\n\n Args:\n start ((float, float))\n to (int)\n\n Returns:\n (timedelta): moving time\n \"\"\"\n dis = count_move_dis(start, to)\n return move_dis_to_time(dis)\n\n\ndef count_dis(base_lat, base_lng, lat, lng):\n \"\"\"Calculate the Euclidean distance\n\n Args:\n base_lat (float)\n base_lng (float)\n lat (float)\n lng (float)\n\n Returns:\n (float): distance in km\n \"\"\"\n return c_count_dis(base_lng, base_lat, lng ,lat)\n\n\ndef get_oil_price(hp):\n \"\"\"Provide oil cost per km from horsepower\n\n Arg:\n hp (int): horsepower of tugs\n\n Return:\n (float): oil price ($/km)\n \"\"\"\n hp_price = {\n 1800: 134.1075498270909,\n 2400: 185.0696699493183,\n 3200: 257.887743955886,\n 3300: 267.3812284262817,\n 3400: 276.9616518343608,\n 3500: 286.6290141801232,\n 3600: 296.3833154635688,\n 4000: 336.2699099741844,\n 4200: 356.734840855592,\n 4400: 377.5475274877326,\n 4500: 388.0842792103279,\n 5200: 464.2758315236272,\n 6400: 604.8009600994644,\n }\n return hp_price[hp]\n\n\ndef get_prices(req_types, tugs):\n \"\"\"Convert types of tugs to revenue per hour according to comparison \n between required types and dispatched tugs\n\n Args:\n req_types ([ChargeType]): a list of required types of a task\n tugs ([Tug]): a list of tugs assigned to a task\n\n Return:\n ([int]): a list of prices ($/hour)\n \"\"\"\n\n assert len(req_types) <= len(tugs)\n table = {117: 7395, 118: 10846, 119: 19720, 120: 22310, 121: 32000}\n req_types.sort()\n tugs.sort(key=lambda tug: tug.type)\n \n prices = []\n i = 0\n while i < len(req_types):\n prices.append(table[min(req_types[i], tugs[i].type)])\n i += 1\n while i < len(tugs):\n prices.append(table[tugs[i].type])\n i += 1\n return prices\n\n\ndef calculate_revenue(times: List[timedelta], req_types: List[ChargeType], tugs: List[Tug]) -> Union[float, list]:\n \"\"\"Calculate revenue for a dispatched task\n\n Args:\n times ([timedelta]): a list of timestamps when the tugs started moving\n req_types ([ChargeType]): a list of required types for a task\n tugs ([Tug]): a list of tugs assigned to a task\n sep (bool): to separate profit between tugs\n\n Return:\n (float): revenue or ([float]): list of revenue\n\n \"\"\"\n\n if not (len(times) and len(req_types) and len(tugs)):\n return 0\n \n assert len(times) == len(req_types) and len(times) == len(tugs), \"Lists length differ\"\n\n revenue = 0\n prices = get_prices(req_types, tugs)\n\n for time, price in zip(times, prices):\n cycles = math.ceil((time - timedelta(minutes=60)).seconds / 60 / 30) * 0.5 + 1 \\\n if time > timedelta(minutes=60) else 1\n revenue += price * cycles\n return revenue\n\n\n","sub_path":"nturesell/algo/utils/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":3893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"301985570","text":"#!/usr/bin/python3\n\nimport sys\nimport os\n\nif sys.platform != 'win32':\n print(\"This script only runs on Windows\")\n sys.exit(1)\n\n# just launch a command\nos.system('ipconfig')\n\n# open a command and read its output\nd = os.popen(r'dir ..\\DATA')\n\nfor entry in d:\n print(entry, end=' ')\n\n# backticks (``) equiv\nhostname = os.popen('hostname').read()[:-1]\n\nprint('Hostname is', hostname)\n\n\n","sub_path":"EXAMPLES/external_win.py","file_name":"external_win.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"460336436","text":"#!/usr/bin/env python3\n\nimport sys\nimport os\nimport argparse\nimport subprocess\nimport readline\nimport pandas as pd\nimport numpy as np\nfrom plio.io.io_bae import read_gpf, save_gpf\nfrom appl_tools.surfacefit import run_pc_align, update_gpf\n\n## Create an argument parser\ndef parse_args():\n parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,\n description = \"\"\"Transform points in a Socet Set Ground Point File (GPF).\nThe transformed latitude, longitude, and height values from the Tie Points are then written to a new GPF with their sigmas set equal to 1 and the \"known\" flag \nchanged from \"1\" (Tie Point) to \"3\" (XYZ Control). Non-Tie Points from the original GPF are written to the new GPF with their \"known\" flags changed to \"1.\" \nTie Points from the original GPF that were not active (\"stat\" = 0) are copied \"as-is\" into the new GPF. The output GPF preserves the order of the ground points from the original GPF.\n\nIf it is desired to update all active points in the input GPF, use the '--all-points' flag. The modified points will still have their \"known\" flag set to \"3\" (XYZ Control) in the output GPF.\n\nThe Ames Stereo Pipeline program pc_align must be available in the user's path or somewhere else where Python can find it. \nMore information about the Ames Stereo Pipeline is available on the project's Git repository: https://github.com/NeoGeographyToolkit/StereoPipeline\"\"\")\n parser.add_argument(\"socet_gpf\",\n help = \"The name of the Socet Ground Point File to transform.\")\n parser.add_argument(\"transform_matrix\",\n help = \"\"\"Name of a pc_align-compatible transformation matrix to apply to the input GPF.\"\"\")\n parser.add_argument(\"tfm_socet_gpf\",\n help = \"\"\"Name to use for the output (transformed) ground point file. Must include \".gpf\" extension.\"\"\")\n parser.add_argument(\"--gxp\",\n action='store_true',\n help = \"Flag to indicate input GPF is in Socet GXP format. Output GPF will be in legacy Socet Set format.\")\n parser.add_argument(\"--all-points\",\n action='store_true',\n help = \"This flag will force updating of all active (stat = 1) points in the input GPF, not just tie points.\")\n parser.add_argument(\"--s_srs\",\n help = \"\"\"PROJ string describing the projected spatial reference system of the input GPF. If omitted, script assumes a geographic SRS with shape defined by --datum or --radius.\"\"\",\n nargs='?',\n type=str)\n refshape = parser.add_mutually_exclusive_group(required=True)\n refshape.add_argument(\"--datum\",\n nargs=1,\n choices=['D_MARS', 'D_MOON', 'MOLA', 'NAD27', 'NAD83', 'WGS72', 'WGS_1984'],\n help = \"\"\"Use this datum for heights in the input GPF.\"\"\")\n refshape.add_argument(\"--radii\",\n nargs=2,\n metavar=('semi-major-axis','semi-minor-axis'),\n type=float,\n help=\"\"\"Semi-major and semi-minor axes, expressed in meters, that define the ellipsoid that heights in the input GPF are referenced to.\"\"\")\n args = parser.parse_args()\n return args\n\ndef main(user_args):\n\n socet_gpf = user_args.socet_gpf\n tfm_socet_gpf = user_args.tfm_socet_gpf\n all_points = user_args.all_points\n transform_matrix = user_args.transform_matrix\n datum = user_args.datum\n radii = user_args.radii\n s_srs = user_args.s_srs\n gxp = user_args.gxp\n\n \n if os.path.splitext(tfm_socet_gpf)[1] != \".gpf\":\n print(\"\"\"USER ERROR: Output file name must use \".gpf\" extension\"\"\")\n sys.exit(1)\n\n # Read in the Socet ground point file using plio's read_gpf()\n if gxp:\n gpf_df = read_gpf(socet_gpf, gxp=True)\n # Modify DataFrame to resemble legacy Socet Set format\n # Rename \"use\" and \"point_type\" to their Socet Set equivalents\n gpf_df.rename(columns={'use':'stat', 'point_type':'known'}, inplace=True)\n if not s_srs:\n gpf_df.lat_Y_North = np.radians(gpf_df['lat_Y_North'])\n gpf_df.long_X_East = np.radians(((gpf_df['long_X_East'] + 180) % 360) - 180)\n else:\n gpf_df = read_gpf(socet_gpf)\n\n # Set the index of the GPF dataframe to be the point_id column\n gpf_df.set_index('point_id', drop=False, inplace=True)\n\n # If user passed \"--all-points\" option, copy *all active* points to new data frame\n # Otherwise, copy active tie points (point_type == 0) only\n # Note that DataFrame is named \"tp_df\" regardless of whether it includes only tiepoints or not\n if all_points:\n tp_df = gpf_df[(gpf_df.stat == 1)].copy()\n else:\n tp_df = gpf_df[(gpf_df.known == 0) & (gpf_df.stat == 1)].copy()\n\n if not s_srs:\n tp_df.lat_Y_North = np.degrees(tp_df.lat_Y_North)\n tp_df.long_X_East = ((360 + np.degrees(tp_df.long_X_East)) % 360)\n\n gpf_align_prefix = os.path.splitext(tfm_socet_gpf)[0]\n\n # Write out CSV (compatible with pc_align) containing lat/long/height of points to be updated\n socet_gpf_csv = ((os.path.splitext(socet_gpf)[0]) + '.csv')\n tp_df.to_csv(path_or_buf=socet_gpf_csv,\n header=False,\n index=False,\n columns=['lat_Y_North','long_X_East','ht'])\n\n # Build arguments list and apply transformation to selected points from GPF using pc_align\n # Set num-iterations = 0 and turn off max-displacement (-1) because only going to apply existing transform\n apply_tfm_args = [\"--initial-transform\",transform_matrix,\n \"--num-iterations\",\"0\",\n \"--max-displacement\",\"-1\",\n \"--save-transformed-source-points\",\n \"-o\", gpf_align_prefix ]\n \n ## Extend the list of arguments for pc_align to include the datum or radii as necessary\n if datum is not None:\n apply_tfm_args.extend([\"--datum\", str(datum[0])])\n elif radii is not None:\n apply_tfm_args.extend([\"--semi-major-axis\", str(radii[0]), \"--semi-minor-axis\", str(radii[1])])\n\n if s_srs:\n apply_tfm_args.extend([\"--csv-proj4\", str(s_srs)])\n apply_tfm_args.extend([\"--csv-format\", str('''2:easting 1:northing 3:height_above_datum''')])\n\n # Extend the list to place point clouds at the end of the list of arguments for pc_align\n # Note that we're specifying the same file as the reference and source clouds because pc_align requires 2 files as input,\n # even if we're only applying a transform and not iterating\n apply_tfm_args.extend([socet_gpf_csv,socet_gpf_csv])\n\n # Apply transform from previous pc_align run to tie points CSV\n print(\"Calling pc_align with 0 iterations to apply transform from previous run to Tie Points from GPF\")\n try:\n run_align = run_pc_align(apply_tfm_args)\n except subprocess.CalledProcessError as e:\n print(e)\n sys.exit(1)\n\n # mergeTransformedGPFTies\n # Convert the transformed tie points from CSV to a pandas DataFrame\n t = np.genfromtxt((gpf_align_prefix + '-trans_source.csv'),delimiter=',',\n skip_header=3,dtype='unicode')\n id_list = tp_df['point_id'].tolist()\n tfm_index = pd.Index(id_list)\n tfm_tp_df = pd.DataFrame(t, index=tfm_index, columns=['lat_Y_North','long_X_East','ht'])\n tfm_tp_df = tfm_tp_df.apply(pd.to_numeric)\n\n # Update the original tiepoint DataFrame with the transformed lat/long/height values from pc_align\n print(\"Updating GPF coordinates\")\n tp_df.update(tfm_tp_df)\n\n # Convert long from 0-360 to +/-180 and convert lat/long to radians\n # Note: Even if gxp==True, plio only knows how to write legacy Socet Set-style GPFs,\n # so must convert to radians on output if not s_srs\n if not s_srs:\n tp_df.lat_Y_North = np.radians(tp_df['lat_Y_North'])\n tp_df.long_X_East = np.radians(((tp_df['long_X_East'] + 180) % 360) - 180)\n\n # Apply updates to the original GPF DataFrame, and save transformed GPF file\n update_gpf(gpf_df,tp_df,tfm_socet_gpf,all_pts=all_points)\n\n # Write list of pointIDs of the transformed tiepoints to a file\n # Included for legacy compatibility, not actually used for anything\n tp_df.to_csv(path_or_buf=((os.path.splitext(socet_gpf)[0]) + '.tiePointIds.txt'),\n sep=' ', header=False,\n index=False,\n columns=['point_id'])\n\n\nif __name__ == \"__main__\":\n sys.exit(main(parse_args()))\n","sub_path":"SurfaceFit/gpf_transform.py","file_name":"gpf_transform.py","file_ext":"py","file_size_in_byte":8619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"251592439","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n\turl(\n\t\tregex=r\"^api/$\",\n\t\tview=views.ContactCreateReadView.as_view(),\n\t\tname=\"flavor_rest_api\"\n\t),\n\turl(\n\t\tregex=r\"^api/(?P[-\\w]+)/$\",\n\t\tview=views.ContactReadUpdateDeleteView.as_view(),\n\t\tname=\"flavor_rest_api\"\n\t)\n]","sub_path":"datapp/contacts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"344883094","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 8 20:57:43 2019\n\n@author: Roy\n\"\"\"\n\n## conslidate learning with own example. Simple currency converter\n\ncurrency_1 = float(input('Please input amount of to convert\\t >>>'))\nconversion_rate = float(input('Please input the conversion factor\\t >>>'))\ncurrency_2 = currency_1*conversion_rate\nprint(f'At conversion rate {conversion_rate} your {currency_1} will be worth {currency_2}')\n","sub_path":"Part4/VeryBasicCurrencyConverter.py","file_name":"VeryBasicCurrencyConverter.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"252134355","text":"#Quadrato con sopra un triangolo, una casetta\r\nimport turtle\r\nwn = turtle.Screen()\r\nporta = turtle.Turtle()\r\npen = turtle.Turtle()\r\nretro = turtle.Turtle()\r\npen.pensize(4)\r\nporta.pensize(4)\r\nretro.pensize(4)\r\npen.forward(80)\r\npen.left(90)\r\npen.forward(80)\r\npen.left(90)\r\npen.forward(80)\r\npen.left(90)\r\npen.forward(80)\r\npen.left(180)\r\npen.forward(80)\r\npen.right(30)\r\npen.forward(80)\r\npen.right(120)\r\npen.forward(80)\r\nporta.forward(30)\r\nporta.left(90)\r\nporta.forward(35)\r\nporta.right(90)\r\nporta.forward(20)\r\nporta.right(90)\r\nporta.forward(35)\r\nporta.left(90)\r\nporta.forward(30)\r\nretro.left(160)\r\nretro.forward(100)\r\nretro.right(70)\r\nretro.forward(80)\r\nretro.right(110)\r\nretro.forward(100)\r\nretro.right(180)\r\nretro.forward(100)\r\nretro.right(100)\r\nretro.forward(80)\r\nretro.right(80)\r\nretro.forward(100)\r\n\r\n\r\n","sub_path":"casetta.py","file_name":"casetta.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"43638867","text":"#! python3\n\n# cmp-rbvpid.py\n# Compare the comma delimited list of RBVPIDs provided to excel spreadsheet and column provided\n\n# Module initialization\nimport csv\nimport openpyxl\nimport os\nimport sys\n\n__author__ = 'rrehders'\n\n# create a function to only extract valid RBVPIDs\ndef is_rbvpid(var):\n try:\n tmp = int(var)\n return tmp\n except:\n return False\n\n\n# Validate the correct number of command line args\nif 2 < len(sys.argv) < 3:\n print('USAGE: cmp-rbvpid [file1.csv] [file2.xlsx] {col}')\n sys.exit()\n\n# Validate 1st command line arg is a file\nfname = sys.argv[1]\nif not os.path.isfile(fname):\n print('ERR: '+fname+' is not a file')\n sys.exit()\n\n# Validate 2nd command line arg is a file\nfname = sys.argv[2]\nif not os.path.isfile(fname):\n print('ERR: '+fname+' is not a file')\n sys.exit()\n\n# Set default column if not specified\nif len(sys.argv) <= 3:\n col = 1\nelse:\n col = int(sys.argv[3])\n\n# Read in the CSV and extract RBVPIDs\ninfile = open(sys.argv[1])\ninreader = csv.reader(infile)\nidlist = set([int(rbvpid[0]) for rbvpid in inreader if is_rbvpid(rbvpid[0])])\nprint(idlist)\n\n# load the target workbook\ntry:\n wb = openpyxl.load_workbook(sys.argv[2], data_only=True)\nexcept Exception as err:\n print('ERR: '+fname+' '+str(err))\ntabs = wb.get_sheet_names()\nws = wb.get_sheet_by_name(tabs[0])\n\n# Extract the Base RBVPIP list\ncolumn = ws.columns[col]\ninvlist = set([cell.value for cell in column if is_rbvpid(cell.value)])\n\n# Compare the lists\nexceptionlist = idlist - invlist\n\n# Explain the results\nprint('There are ', len(idlist), ' IDs in the test list')\nprint('Being compared to ', len(invlist), ' IDs in the origin list')\nif len(exceptionlist) == 0:\n print('All IDs are present')\nelse:\n print('The following ', len(exceptionlist), ' IDs were missed from the list')\n print(exceptionlist)\n","sub_path":"cmp-rbvpid.py","file_name":"cmp-rbvpid.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"470069702","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport itertools\nfrom sklearn import mixture\nfrom scipy import linalg\nimport matplotlib as mpl\nfrom scipy import spatial\n\n#F = np.loadtxt(\"mapping\", unpack = True)\n#G = np.loadtxt(\"mapped\", unpack = True)\n\nX = np.loadtxt(\"samples2\", unpack=True)\n\ngmm = mixture.GMM(n_components=4, covariance_type='full')\ngmm.fit(X)\n\nX_test = np.linspace(-6, 4)\nY_test = 2*np.sin(X_test) -3\n#plt.scatter(X_test, Y_test)\n\nX_t = np.ndarray((50, 2))\n\n\n\nX_t[:, 0] = X_test\nX_t[:, 1] = Y_test\n\ncolor_iter = itertools.cycle(['r', 'g', 'b', 'c', 'm'])\n\nfor i, (clf, title) in enumerate([(gmm, 'GMM')]):\n splot = plt.subplot(1, 1, i + 1)\n Y_ = clf.predict(X_t)\n for i, (mean, covar, color) in enumerate(zip(\n clf.means_, clf._get_covars(), color_iter)):\n v, w = linalg.eigh(covar)\n u = w[0] / linalg.norm(w[0])\n\n if not np.any(Y_ == i):\n continue\n plt.scatter(X_t[Y_ == i, 0], X_t[Y_ == i, 1], 2, color=color)\n\n\n # Plot an ellipse to show the Gaussian component\n angle = np.arctan(u[1] / u[0])\n angle = 180 * angle / np.pi\n ell = mpl.patches.Ellipse(mean, v[0], v[1], 180 + angle, color=color)\n ell.set_clip_box(splot.bbox)\n ell.set_alpha(0.5)\n splot.add_artist(ell)\n\n\n\n\n\n\n'''\n#F_tree = spatial.KDTree(F)\n#G_tree = spatial.KDTree(G)\n\n\nZ = []\n\nfor i in range(len(X_test)):\n point = np.array([X_test[i], Y_test[i]])\n #ind = find_nearest(F, value)\n distance, index = F_tree.query(point)\n Z.append(G[index])\n\n\n\nZ = np.array(Z)\nplt.scatter(Z[:, 0], Z[:, 1], color= 'k')\n\n\n'''\n\nplt.show()\n","sub_path":"LearnedMap.py","file_name":"LearnedMap.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"546122665","text":"try:\n import os\n import subprocess\n import shutil\n import stat\n import json\n import sys\n import platform\n import tarfile\n import hashlib\n\n PYTHON2 = 2\n PYTHON3 = 3\n\n pyversion = None\n installpath = \"/usr/bin\"\n\n # Detect OS and architecture\n if sys.version_info[0] < 3:\n pyversion = PYTHON2\n import urllib2 as urllib\n else:\n pyversion = PYTHON3\n import urllib.request as urllib\n\n if platform.machine() != \"x86_64\":\n if platform.machine() != \"\":\n print(\"System architecture unsupported, build from source instead\")\n exit()\n elif pyversion == PYTHON3:\n q = input(\n \"Unable to detect system architecture, are you using x86_64 (AMD64) [y/N]: \")\n if q.lower() != \"y\":\n print(\"System architecture unsupported, build from source instead\")\n exit(1)\n else:\n q = raw_input(\n \"Unable to detect system architecture, are you using x86_64 (AMD64) [y/N]: \")\n if q.lower() != \"y\":\n print(\"System architecture unsupported, build from source instead\")\n exit(1)\n\n if platform.system() != \"Linux\" and platform.system() != \"Darwin\":\n if platform.system() == \"Windows\":\n print(\n \"Windows is not supported by the Python installer, use pre-compiled binaries instead\")\n else:\n print(\"OS unsupported, build from source instead\")\n exit(1)\n\n if platform.system() == \"Darwin\":\n installpath = \"/usr/local/bin\"\n\n # Check for existance and write permissions\n if not os.path.isdir(installpath):\n print(\"Unable to locate \" + installpath)\n exit(1)\n if not os.path.isdir(\"/tmp\"):\n print(\"Unable to locate /tmp\")\n exit(1)\n\n if not os.access(installpath, os.W_OK):\n print(\"Insufficient permissions, please elevate\")\n exit(1)\n if not os.access(\"/tmp\", os.W_OK):\n print(\"Insufficient permissions, please elevate\")\n exit(1)\n\n # Get latest release\n print(\"Gathering system info ...\")\n if os.path.isfile(installpath + \"/kryer\"):\n if pyversion == PYTHON2:\n q = raw_input(\n \"Kryer is already installed, reinstall/update [Y/n]: \")\n else:\n q = str(\n input(\"Kryer is already installed, reinstall/update [Y/n]: \"))\n\n if q.lower() == \"n\":\n exit(0)\n\n print(\"Removing \" + installpath + \"/kryer...\")\n\n try:\n os.remove(installpath + \"/kryer\")\n except OSError:\n print(\"Insufficient permissions, please elevate\")\n exit(1)\n\n print(\"Removed \" + installpath + \"/kryer...\")\n\n print(\"Getting release information from https://api.github.com/repos/cfschilham/kryer/releases...\")\n response = urllib.urlopen(\n \"https://api.github.com/repos/cfschilham/kryer/releases\")\n releases = json.loads(response.read())\n\n for release in releases:\n print(\"Getting asset list from \" + release[\"assets_url\"] + \"...\")\n response = urllib.urlopen(release[\"assets_url\"])\n assets = json.loads(response.read())\n\n for asset in assets:\n if platform.system().lower() in asset[\"name\"] and \"tar.gz\" in asset[\"name\"]:\n print(\"Downloading \" + asset[\"browser_download_url\"] + \"...\")\n if(pyversion == PYTHON2):\n response = urllib.urlopen(asset[\"browser_download_url\"])\n rawfile = response.read()\n\n with open(\"/tmp/kryer.tar.gz\", \"wb\") as FILE:\n FILE.write(rawfile)\n\n else:\n urllib.urlretrieve(\n asset[\"browser_download_url\"], \"/tmp/kryer.tar.gz\")\n break\n\n if os.path.isfile(\"/tmp/kryer.tar.gz\"):\n break\n\n if not os.path.isfile(\"/tmp/kryer.tar.gz\"):\n print(\"There aren't any compatible pre-compiled binaries available for your system, build from source instead\")\n exit(1)\n\n print(\"Extracting \" + asset[\"name\"] + \"...\")\n filename = asset[\"name\"].replace(\".tar.gz\", \"\")\n for asset in assets:\n if asset[\"name\"] == filename + \".sha256\":\n print(\"Getting SHA256 checksum from \" +\n asset[\"browser_download_url\"] + \"...\")\n if pyversion == PYTHON2:\n response = urllib.urlopen(asset[\"browser_download_url\"])\n rawfile = response.read()\n\n with open(\"/tmp/kryer.sha256\", \"wb\") as FILE:\n FILE.write(rawfile)\n\n else:\n urllib.urlretrieve(\n asset[\"browser_download_url\"], \"/tmp/kryer.sha256\")\n break\n\n if os.path.isfile(\"/tmp/kryer.sha256\"):\n with open(\"/tmp/kryer.sha256\", \"r\") as checksum:\n checksum = checksum.read().split(\" \")[0]\n print(\"Verifying checksum \" + checksum + \"...\")\n\n checksumFILE = hashlib.sha256()\n with open(\"/tmp/kryer.tar.gz\", \"rb\") as FILE:\n for chunk in iter(lambda: FILE.read(4096), b\"\"):\n checksumFILE.update(chunk)\n\n if checksum.strip() != checksumFILE.hexdigest().strip():\n print(\"Integrity check failed, invalid checksum\")\n print(\"Calculated checksum: \" + checksumFILE.hexdigest().strip())\n print(\"Provided checksum: \" + checksum.strip())\n\n if os.path.isfile(\"/tmp/kryer\"):\n os.remove(\"/tmp/kryer\")\n if os.path.isdir(\"/tmp/kryer.sha256\"):\n shutil.rmtree(\"/tmp/kryer.sha256\")\n if os.path.isfile(\"/tmp/kryer.tar.gz\"):\n os.remove(\"/tmp/kryer.tar.gz\")\n exit(1)\n\n print(\"Integrity check successful\")\n else:\n print(\"Can't find checksum for file, skipping integrity check...\")\n\n print(\"Extracting \" + asset[\"name\"] + \"...\")\n os.mkdir(\"/tmp/kryer\")\n tar = tarfile.TarFile.open(\"/tmp/kryer.tar.gz\", \"r:gz\")\n tar.extractall(\"/tmp/kryer\")\n tar.close()\n\n print(\"Creating files in \" + installpath + \"...\")\n shutil.move(\"/tmp/kryer/\" + filename + \"/kryer\", installpath + \"/kryer\")\n\n shutil.rmtree(\"/tmp/kryer\")\n os.remove(\"/tmp/kryer.tar.gz\")\n os.remove(\"/tmp/kryer.sha256\")\n print(\"Installation successful, use kryer command to start\")\n\nexcept KeyboardInterrupt:\n print(\"\\nKeyboard interrupt detected\")\n print(\"Cleaning up...\")\n\n if os.path.isdir(\"/tmp/kryer\"):\n shutil.rmtree(\"/tmp/kryer\")\n if os.path.isfile(\"/tmp/kryer.tar.gz\"):\n os.remove(\"/tmp/kryer.tar.gz\")\n if os.path.isfile(\"/tmp/kryer.sha256\"):\n os.remove(\"/tmp/kryer.sha256\")\n","sub_path":"install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":6724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"517850770","text":"import re\nfrom scrapy import log, FormRequest, Spider, Request\nfrom Presidency.items import Address\nfrom Presidency.pipelines import CSVHandler\nfrom scrapy import signals\nfrom scrapy.xlib.pydispatch import dispatcher\nfrom string import punctuation\nimport time, datetime\nimport Presidency.settings\n\n__author__ = 'Shay Goldman, shay@goldman.io'\n\nclass Spidresident(Spider):\n name = 'Spidresident'\n log_name = name.upper()\n allowed_domains = Presidency.settings.DOMAINS\n csv_handler = CSVHandler()\n\n def __init__(self, **kwargs):\n super(Spidresident, self).__init__(**kwargs)\n dispatcher.connect(self.spider_quit, signals.spider_closed)\n\n def spider_quit(self):\n self.csv_handler.close_file_handle()\n self.csv_handler.set_running(False)\n\n def get_csv_handler(self):\n return self.csv_handler\n\n def start_requests(self):\n log.msg(self.log_name + \": Building initial requests\", level=log.DEBUG)\n for category_id, category_name in Presidency.settings.CATEGORIES.iteritems():\n for year in range(Presidency.settings.MIN_YEAR, Presidency.settings.MAX_YEAR + 1):\n altered_formdata = Presidency.settings.FORM_BASE_DATA\n altered_formdata[Presidency.settings.FORM_FIELD_YEAR_START] = str(year)\n altered_formdata[Presidency.settings.FORM_FIELD_YEAR_END] = str(year)\n altered_formdata[Presidency.settings.FORM_FIELD_CATEGORY] = str(category_id)\n\n log.msg(self.log_name + \": Yielding category \" + str(category_id) + \" for \" + str(year), level=log.DEBUG)\n yield FormRequest(\n Presidency.settings.SITE_URL,\n formdata=altered_formdata,\n callback=lambda g, category_id=category_id:\n self.request_addresses(g, category_id))\n\n log.msg(self.log_name + \": Initial requests built\", level=log.INFO)\n\n def extract_pid(self, link):\n pid_pattern = re.compile('=\\d+&')\n pid_match = pid_pattern.search(link)\n pid = link[pid_match.start() + 1:pid_match.end() - 1]\n return pid\n\n def extract_day(self, date_pre):\n day_pattern = re.compile('\\s\\d*,')\n day_match = day_pattern.search(date_pre)\n day = date_pre[day_match.start() + 1:day_match.end() - 1]\n if (int(day) < 10):\n day = '0' + (str(day))\n return day\n\n def extract_month(self, date_pre):\n month_pattern = re.compile('^[a-zA-z]*\\s')\n month_match = month_pattern.search(date_pre)\n month = date_pre[month_match.start():month_match.end() - 1]\n if (month in Presidency.settings.MONTH_MAP.keys()):\n month = Presidency.settings.MONTH_MAP[month]\n return month\n\n def extract_year(self, date_pre):\n year_pattern = re.compile('\\d+$')\n year_match = year_pattern.search(date_pre)\n year = date_pre[year_match.start():year_match.end()]\n return year\n\n def request_addresses(self, response, category_id):\n results_table_xpath = '//html/body/table/tr[2]/td/table/tr/td[2]/table/tr/table/tr'\n results = response.selector.xpath(results_table_xpath)\n for result_num in range(1, results.__len__() - 2): # Skip header and footer of results\n link_element = results[result_num].xpath('./td[4]//a')\n\n link = unicode(''.join(link_element.xpath('./@href').extract()).strip())\n title = unicode(''.join(link_element.xpath('./text()').extract()).strip())\n pid = self.extract_pid(link)\n\n date_pre = unicode(''.join(results[result_num].xpath('./td[1]/text()').extract()).strip())\n day = self.extract_day(date_pre)\n month = self.extract_month(date_pre)\n year = self.extract_year(date_pre)\n date = year + '-' + month + '-' + day\n\n president = unicode(''.join(results[result_num].xpath('./td[2]/text()').extract()).strip())\n\n yield Request(\n url=Presidency.settings.SITE_URL_FOLDER + link,\n callback=lambda g, title=title, pid=pid, date=date, president=president:\n self.parse_address(g, title, pid, date, president, category_id))\n log.msg(self.log_name + \": Yielded address \" + title, level=log.DEBUG)\n\n def parse_address(self, response, title, pid, date, president, category_id):\n address = Address()\n url = response.url.lower()\n timestamp = time.time()\n address[Presidency.settings.FIELD_COLLECTED_AT] = datetime.datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')\n address[Presidency.settings.FIELD_PRESIDENT] = president\n address[Presidency.settings.FIELD_DATE] = date\n address[Presidency.settings.FIELD_TITLE] = title\n address[Presidency.settings.FIELD_PID] = str(pid)\n address[Presidency.settings.FIELD_CATEGORY] = Presidency.settings.CATEGORIES[category_id]\n address[Presidency.settings.FIELD_CATEGORY_ID] = str(category_id)\n\n toolbox_ver10_list = response.selector.css('.toolbox').css('.ver10::text').extract()\n\n for i in range(0, toolbox_ver10_list.__len__() - 1):\n if (toolbox_ver10_list[i] == u'Location:'):\n address[Presidency.settings.FIELD_LOCATION1] = toolbox_ver10_list[i + 1]\n address[Presidency.settings.FIELD_LOCATION2] = toolbox_ver10_list[i + 2]\n break\n\n address[Presidency.settings.FIELD_URL] = url\n\n raw_content = response.selector.css('.displaytext').xpath('.//text()').extract()\n str_raw_content = ''.join(raw_content)\n address[Presidency.settings.FIELD_CONTENT] = str_raw_content\n r = re.compile(r'[{}]'.format(punctuation))\n fixed_str_raw_content = r.sub(' ',str_raw_content)\n word_list = fixed_str_raw_content.split()\n\n address[Presidency.settings.FIELD_WORDS] = len(word_list)\n\n log.msg(self.log_name + \": Parsed address \" + title, level=log.DEBUG)\n yield address\n","sub_path":"Presidency/spiders/Spidresident.py","file_name":"Spidresident.py","file_ext":"py","file_size_in_byte":6021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"100694324","text":"import os\nimport logging\nimport re\n\nimport numpy as np\nfrom typing import *\n\nfrom Bio.Blast import NCBIXML\nfrom Bio.Blast.Applications import NcbiblastpCommandline\nfrom Bio.Blast.Record import Alignment, HSP\nfrom Bio.Seq import Seq\nfrom Bio.SubsMat import MatrixInfo as matlist\nfrom tqdm import tqdm\n\nfrom sbsp_alg.feature_computation import add_gaps_to_nt_based_on_aa\nfrom sbsp_alg.phylogeny import k2p_distance, global_alignment_aa_with_gap\nfrom sbsp_container.genome_list import GenomeInfoList, GenomeInfo\nfrom sbsp_general import Environment\nfrom sbsp_general.blast import run_blast, convert_blast_output_to_csv, create_blast_database, run_blast_alignment\nfrom sbsp_general.general import get_value\nfrom sbsp_general.labels import Labels, Label, create_gene_key_from_label\nfrom sbsp_io.general import mkdir_p\nfrom sbsp_io.labels import read_labels_from_file\nfrom sbsp_io.sequences import read_fasta_into_hash\nfrom sbsp_options.sbsp import SBSPOptions\n\nlog = logging.getLogger(__name__)\n\nvalid_starts_pos = [\"ATG\", \"GTG\", \"TTG\"]\nvalid_starts_neg = [\"CAT\", \"CAC\", \"CAA\"]\n\nvalid_stops_pos = [\"TAA\", \"TGA\", \"TAG\"]\nvalid_stops_neg = [\"TTA\", \"TCA\", \"CTA\"]\n\n\ndef is_valid_start(codon, strand):\n if strand == \"+\":\n return codon in valid_starts_pos\n else:\n return codon in valid_starts_neg\n\n\ndef is_valid_stop(codon, strand):\n if strand == \"+\":\n return codon in valid_stops_pos\n else:\n return codon in valid_stops_neg\n\n\ndef get_orthologs_from_files_deprecated(env, pf_q_list, pf_t_list, pf_output, **kwargs):\n # type: (Environment, str, str, str, Dict[str, Any]) -> str\n\n clean = get_value(kwargs, \"clean\", False)\n\n # pf_q_list = data[\"pf-q-list\"]\n # pf_t_list = data[\"pf-t-list\"]\n\n pd_work = env[\"pd-work\"]\n\n mkdir_p(pd_work)\n\n # run blast\n fn_blast_out = \"blast.xml\"\n pf_blast_out = os.path.join(pd_work, fn_blast_out)\n\n run_blast(env, pf_q_list, pf_t_list, pf_blast_out, **kwargs)\n\n # convert blast output to csv\n convert_blast_output_to_csv(pf_blast_out, pf_output, select_best_alignment_per_qt_pair=True)\n\n if clean:\n try:\n os.remove(pf_blast_out)\n except OSError:\n pass\n\n return pf_output\n\n\ndef pack_fasta_header(label, gi, **kwargs):\n # type: (Label, GenomeInfo, Dict[str, Any]) -> str\n\n def create_tags_from_dict(**local_kwargs):\n # type: (Dict[str, Any]) -> str\n out = \"\"\n for k, v in local_kwargs.items():\n out += \";{}={}\".format(k, v)\n return out\n\n return \"{} accession={};genome={};left={};right={};strand={}\".format(\n label.seqname(),\n label.seqname(),\n gi.name,\n label.left() + 1,\n label.right() + 1,\n label.strand(),\n ) + create_tags_from_dict(**kwargs)\n\n\ndef unpack_fasta_header(header):\n # type: (str) -> Dict[str, Any]\n\n fields = {}\n\n def get_key_value_from_definition_line(key, l_defline):\n m = re.match(\".*(?:^|;)\" + str(key) + \"=([^;]*)\", l_defline)\n\n if m:\n return m.group(1)\n\n raise ValueError(\"Key \" + str(key) + \" not in definition line\")\n\n # remove first accession\n header = header.strip().split(maxsplit=1)[1]\n\n # get all keys in string\n keys = re.findall(r\"([^;=]+)=\", header)\n\n type_mapper = {\n \"left\": int,\n \"right\": int,\n \"gc\": float,\n \"offset\": int,\n \"upstream_left\": int,\n \"upstream_right\": int\n }\n\n # for each key, get value\n for k in keys:\n fields[k] = get_key_value_from_definition_line(k, header)\n\n if k in type_mapper.keys():\n fields[k] = type_mapper[k](fields[k])\n\n return fields\n\n\ndef select_representative_hsp(alignment, hsp_criteria):\n # type: (Alignment, str) -> Union[HSP, None]\n\n selected_hsp = None\n max_length = None\n for hsp in alignment.hsps:\n if max_length is None:\n selected_hsp = hsp\n max_length = hsp.align_length\n else:\n if hsp.align_length > max_length:\n selected_hsp = hsp\n max_length = hsp.align_length\n\n return selected_hsp\n\n\ndef map_aligned_aa_to_aligned_nt(q_aligned_seq_aa, original_q_nt, q_start_aa, q_end_aa, offset_nt=0):\n # type: (Seq, Seq, int, int) -> Seq\n if len(original_q_nt) < (q_end_aa - q_start_aa + 1) * 3:\n raise ValueError(\"Nucleotide sequence length less than aligned amino acid fragment: {} < {}\".format(\n len(original_q_nt), (q_end_aa - q_start_aa + 1) * 3\n ))\n\n output = Seq(\"\")\n pos_nt_no_gaps = offset_nt + q_start_aa * 3\n max_pos_nt_no_gaps = offset_nt + (q_end_aa + 1) * 3\n\n for pos_aa in range(min(200, len(q_aligned_seq_aa))):\n curr_aa = q_aligned_seq_aa[pos_aa]\n\n if curr_aa == \"-\":\n output += \"---\"\n else:\n output += original_q_nt[pos_nt_no_gaps:pos_nt_no_gaps + 3]\n pos_nt_no_gaps += 3\n\n if pos_nt_no_gaps >= max_pos_nt_no_gaps:\n break\n\n return output\n\n\ndef compute_distance_based_on_local_alignment(query_info, target_info, hsp, **kwargs):\n # type: (Dict[str, Any], Dict[str, Any], HSP, Dict[str, Any]) -> float\n\n original_q_nt = get_value(kwargs, \"original_q_nt\", required=True)\n original_t_nt = get_value(kwargs, \"original_t_nt\", required=True)\n original_q_nt_offset = get_value(kwargs, \"original_q_nt_offset\", default=0)\n original_t_nt_offset = get_value(kwargs, \"original_t_nt_offset\", default=0)\n\n # aligned fragments (aa)\n q_aligned_seq_aa = hsp.query\n t_aligned_seq_aa = hsp.sbjct\n\n # indices of where alignment starts in original sequences\n q_start, q_end = hsp.query_start - 1, hsp.query_end - 2 # -2 to make inclusive\n t_start, t_end = hsp.sbjct_start - 1, hsp.sbjct_end - 1 # -2 to make inclusive\n\n # aligned fragments (nt)\n try:\n q_aligned_seq_nt = map_aligned_aa_to_aligned_nt(q_aligned_seq_aa, original_q_nt, q_start, q_end, offset_nt=original_q_nt_offset)\n t_aligned_seq_nt = map_aligned_aa_to_aligned_nt(t_aligned_seq_aa, original_t_nt, t_start, t_end, offset_nt=original_t_nt_offset)\n except ValueError:\n return 100 # FIXME: the hell is going on\n\n # compute distance metric\n try:\n distance = k2p_distance(q_aligned_seq_nt, t_aligned_seq_nt)\n except ValueError:\n distance = 100\n\n return distance\n\n\ndef create_info_for_query_target_pair(query_info, target_info, hsp, **kwargs):\n # type: (Dict[str, Any], Dict[str, Any], HSP, Dict[str, Any]) -> Dict[str, Any]\n output = {\n \"evalue\": hsp.expect,\n }\n\n for k, v in kwargs.items():\n output[k] = v\n\n source_to_info = {\"q\": query_info, \"t\": target_info}\n for source in [\"q\", \"t\"]:\n\n for key in [\"genome\", \"accession\", \"left\", \"right\", \"strand\", \"upstream_left\", \"upstream_right\", \"upstream_strand\", \"offset\"]:\n output[\"{}-{}\".format(source, key)] = source_to_info[source][key]\n\n output[\"q-prot-pos-5prime-in-frag-msa\"] = query_info[\"offset\"] / 3\n output[\"q-nucl-pos-5prime-in-frag-msa\"] = query_info[\"offset\"]\n output[\"q-prot-position-of-5prime-in-msa-fragment-no-gaps\"] = query_info[\"offset\"] / 3\n output[\"q-nucl-position-of-5prime-in-msa-fragment-no-gaps\"] = query_info[\"offset\"]\n output[\"t-prot-pos-5prime-in-frag-msa\"] = target_info[\"offset\"] / 3\n output[\"t-nucl-pos-5prime-in-frag-msa\"] = target_info[\"offset\"]\n output[\"t-prot-position-of-5prime-in-msa-fragment-no-gaps\"] = target_info[\"offset\"] / 3\n output[\"t-nucl-position-of-5prime-in-msa-fragment-no-gaps\"] = target_info[\"offset\"]\n\n output[\"q-key\"] = \"{};{};{};{}\".format(\n query_info[\"accession\"], query_info[\"left\"], query_info[\"right\"], query_info[\"strand\"]\n )\n\n #output[\"q-prot-msa\"] = Seq(query_info[\"lorf_nt\"]).translate()._data\n #output[\"t-prot-msa\"] = Seq(target_info[\"lorf_nt\"]).translate()._data\n\n output[\"q-lorf_nt\"] = Seq(query_info[\"lorf_nt\"])._data\n output[\"t-lorf_nt\"] = Seq(target_info[\"lorf_nt\"])._data\n\n return output\n\n\ndef compute_distance_based_on_global_alignment_from_sequences(q_sequence, t_sequence, q_sequence_nt, t_sequence_nt,\n matrix):\n [q_align, t_align, _, _, _] = \\\n global_alignment_aa_with_gap(q_sequence, t_sequence, matrix)\n\n q_align_nt = add_gaps_to_nt_based_on_aa(q_sequence_nt, q_align)\n t_align_nt = add_gaps_to_nt_based_on_aa(t_sequence_nt, t_align)\n\n # count number of positions without gaps\n len_without_gaps = sum([1 for i in range(len(q_align)) if q_align[i] != \"-\" and t_align[i] != \"-\"])\n\n try:\n distance = k2p_distance(q_align_nt, t_align_nt)\n except ValueError:\n distance = 100\n\n return (distance, len(q_align), len_without_gaps)\n\n\ndef parse_filter_and_convert_to_csv(pf_blast_results, pf_output, **kwargs):\n # type: (str, str, Dict[str, Any]) -> None\n\n hsp_criteria = get_value(kwargs, \"hsp_criteria\", None)\n pf_q_original_nt = get_value(kwargs, \"pf_q_original_nt\", required=True)\n pf_t_original_nt = get_value(kwargs, \"pf_t_original_nt\", required=True)\n pf_q_original_aa = get_value(kwargs, \"pf_q_original_aa\", required=True)\n pf_t_original_aa = get_value(kwargs, \"pf_t_original_aa\", required=True)\n distance_min = get_value(kwargs, \"distance_min\", 0.001, default_if_none=True)\n distance_max = get_value(kwargs, \"distance_max\", 0.4, default_if_none=True)\n\n # open csv file for writing\n try:\n f_output = open(pf_output, \"w\")\n except OSError as e:\n log.warning(\"Could not open csv file for writing converted blast output: {}\".format(pf_output))\n raise e\n\n try:\n f_blast_results = open(pf_blast_results, \"r\")\n except OSError as e:\n log.warning(\"Could not open blast results file: {}\".format(pf_blast_results))\n raise e\n\n # read original nucleotide sequences (for computing distances)\n q_original_sequences_nt = read_fasta_into_hash(pf_q_original_nt)\n t_original_sequences_nt = read_fasta_into_hash(pf_t_original_nt)\n\n # read original sequences for trying out pairwise alignment ;)\n q_original_sequences_aa = read_fasta_into_hash(pf_q_original_aa)\n t_original_sequences_aa = read_fasta_into_hash(pf_t_original_aa)\n\n matrix = matlist.blosum62\n import sbsp_alg.phylogeny\n sbsp_alg.phylogeny.add_stop_codon_to_blosum(matrix)\n\n # open blast stream\n records = NCBIXML.parse(f_blast_results)\n header_written = False\n\n # for each blast query\n for r in records:\n\n query_info = unpack_fasta_header(r.query)\n num_selected_targets_for_query = 0\n\n # for each alignment to a target protein for the current query\n for alignment in r.alignments:\n\n if num_selected_targets_for_query >= 100:\n logger.debug(\"Stopping at 100 targets (from {}) for query\".format(len(r.alignments)))\n break\n\n hsp = select_representative_hsp(alignment, hsp_criteria)\n\n target_info = unpack_fasta_header(alignment.hit_id)\n\n original_q_nt = q_original_sequences_nt[r.query]\n original_t_nt = t_original_sequences_nt[alignment.hit_id]\n\n distance = compute_distance_based_on_local_alignment(query_info, target_info, hsp,\n original_q_nt=original_q_nt,\n original_t_nt=original_t_nt,\n **kwargs)\n\n original_q_aa = q_original_sequences_aa[r.query]\n original_t_aa = t_original_sequences_aa[alignment.hit_id]\n\n #global_distance, global_length, global_length_without_gaps = compute_distance_based_on_global_alignment_from_sequences(\n # original_q_aa, original_t_aa, original_q_nt, original_t_nt, matrix\n #)\n global_distance = global_length = global_length_without_gaps = 0\n\n # FIXME: thresholds should be from input configuration files\n if distance > distance_min and distance < distance_max:\n #if True:\n num_selected_targets_for_query += 1\n\n output_info = create_info_for_query_target_pair(\n query_info, target_info, hsp,\n distance_blast=distance,\n distance=distance,\n global_distance=global_distance,\n global_length=global_length,\n global_length_without_gaps=global_length_without_gaps,\n local_distance=distance,\n local_length=hsp.align_length,\n local_length_without_gaps=sum([\n 1 for i in range(len(hsp.query)) if hsp.query[i] != \"-\" and hsp.sbjct[i] != \"-\"\n ])\n )\n\n sorted_header = sorted(output_info.keys())\n\n # if header not yet written, write it\n if not header_written:\n f_output.write(\"{}\\n\".format(\",\".join(sorted_header)))\n header_written = True\n\n # write values in sorted order\n f_output.write(\"{}\\n\".format(\n \",\".join([str(output_info[x]) for x in sorted_header])\n ))\n\n f_output.close()\n\n\n# def convert_blast_output_to_csv(pf_blast_output, pf_csv, select_best_alignment_per_qt_pair=True, delimiter=\",\", **kwargs):\n# # type: (str, str, bool) -> None\n#\n# def get_lowest_evalue_of_hsps(alignment):\n# return np.min([hsp.expect for hsp in alignment.hsps])\n#\n# def set_alignment_if_lowest_evalue(data, genome_name, alignment):\n# # type: (dict, str, dict) -> None\n#\n# if genome_name not in data:\n# data[genome_name] = alignment\n# # otherwise, check if it has a lower E-value than what's already there\n# else:\n# evalue_existing = get_lowest_evalue_of_hsps(data[genome_name])\n# evalue_new = get_lowest_evalue_of_hsps(alignment)\n#\n# if evalue_new < evalue_existing:\n# data[genome_name] = alignment\n#\n# # open output file for writing\n# with open(pf_csv, \"w\") as f_csv:\n#\n# header = None\n#\n# import sbsp_io.blast\n# records = sbsp_io.blast.read_hits(pf_blast_output)\n#\n# for r in records:\n#\n# q_def = r.query # query definition line\n# q_genome = sbsp_general.general.get_genome_name_from_defition_line(q_def)\n# if select_best_alignment_per_qt_pair:\n# # Structure:\n# # Key : target genome name\n# # Value : alignment with the lowest evalue for that target\n# best_alignment_per_genome = {}\n#\n# # for each target genome, only select the best (lowest e-value) alignment\n# for alignment in r.alignments:\n# t_def = alignment.hit_id\n# t_genome = sbsp_general.general.get_genome_name_from_defition_line(t_def)\n#\n# # keep track of the best alignment for this genome\n# set_alignment_if_lowest_evalue(best_alignment_per_genome, t_genome, alignment)\n#\n# for t_genome in best_alignment_per_genome.keys():\n# t_def = best_alignment_per_genome[t_genome].hit_id\n# curr_alignment = best_alignment_per_genome[t_genome]\n# evalue = get_lowest_evalue_of_hsps(curr_alignment)\n#\n#\n# if not blast_on_query_database:\n# # now print\n# info = {\n# \"q-def\": q_def, \"t-def\" : t_def\n# }\n#\n# q_info = sbsp_general.general.expand_definition_line(q_def, key_prefix=\"q-\")\n# t_info = sbsp_general.general.expand_definition_line(t_def, key_prefix=\"t-\")\n# else:\n# info = {\n# \"q-def\": t_def, \"t-def\": q_def\n# }\n#\n# q_info = sbsp_general.general.expand_definition_line(q_def, key_prefix=\"t-\")\n# t_info = sbsp_general.general.expand_definition_line(t_def, key_prefix=\"q-\")\n#\n# def is_frame_shifted(tmp_info, key_prefix):\n# # type: (Dict[str, Any], str) -> bool\n# return (int(tmp_info[key_prefix+\"right\"]) - int(tmp_info[key_prefix+\"left\"]) + 1) % 3 != 0\n#\n# if is_frame_shifted(q_info, \"q-\") or is_frame_shifted(t_info, \"t-\"):\n# continue\n#\n#\n# info.update(q_info)\n# info.update(t_info)\n#\n# info[\"evalue\"] = evalue\n#\n# # if first line, write header\n# if header is None:\n# header = sorted(info.keys())\n# line = \"{}\".format(delimiter).join(header) + \"\\n\"\n# f_csv.write(line)\n# # if not first line, make sure header is consistent\n# else:\n# curr_header = sorted(info.keys())\n# if curr_header != header:\n# raise ValueError(\"CSV rows don't have the same columns\")\n#\n# # write data\n# line = \"{}\".format(delimiter).join([str(info[h]) for h in header]) + \"\\n\"\n# f_csv.write(line)\n\n\ndef append_sequences_to_file(sequences, f):\n # type: (Dict[str, Seq], IO[AnyStr]) -> None\n for header, sequence in sequences.items():\n f.write(\">{}\\n{}\\n\".format(\n header, sequence\n ))\n\n\ndef get_pf_sequences_for_genome(env, gi, **kwargs):\n # type: (Environment, GenomeInfo, Dict[str, Any]) -> str\n fn_sequences = get_value(kwargs, \"fn_sequences\", \"sequence.fasta\")\n return os.path.join(env['pd-data'], gi.name, fn_sequences)\n\n\ndef get_pf_labels_for_genome(env, gi, **kwargs):\n # type: (Environment, GenomeInfo, Dict[str, Any]) -> str\n fn_labels = get_value(kwargs, \"fn_labels\", \"ncbi.gff\")\n return os.path.join(env['pd-data'], gi.name, fn_labels)\n\n\ndef get_lorf(label, sequences):\n # type: (Label, Dict[str, Seq]) -> Seq\n\n if label.strand() == \"+\":\n\n curr_pos = label.left()\n pos_lorf = curr_pos\n\n while curr_pos >= 0:\n codon = sequences[label.seqname()][curr_pos:curr_pos + 3]._data\n if is_valid_start(codon, label.strand()):\n pos_lorf = curr_pos\n if is_valid_stop(codon, label.strand()):\n break\n\n curr_pos -= 3\n\n lorf_seq = sequences[label.seqname()][pos_lorf:label.right() + 1]\n\n else:\n\n curr_pos = label.right()\n pos_lorf = curr_pos\n seq_len = len(sequences[label.seqname()])\n\n while curr_pos < seq_len:\n codon = sequences[label.seqname()][curr_pos - 2:curr_pos + 1]._data\n if is_valid_start(codon, label.strand()):\n pos_lorf = curr_pos\n if is_valid_stop(codon, label.strand()):\n break\n\n curr_pos += 3\n\n lorf_seq = sequences[label.seqname()][label.left():pos_lorf + 1]\n\n return lorf_seq\n\n\ndef extract_labeled_sequence(label, sequences, **kwargs):\n # type: (Label, Dict[str, Seq], Dict[str, Any]) -> Seq\n reverse_complement = get_value(kwargs, \"reverse_complement\", False)\n lorf = get_value(kwargs, \"lorf\", False)\n\n if lorf:\n frag = get_lorf(label, sequences)\n else:\n frag = sequences[label.seqname()][label.left():label.right() + 1]\n\n if label.strand() == \"-\" and reverse_complement:\n frag = frag.reverse_complement()\n\n return frag\n\n # return \"{}:tag={};11;:gc={}:pos={};{};{}:cds={};{};{}:type={}:key={};{};{}\".format(\n # label.seqname(),\n # gi.name,\n # gc,\n # label.left() + 1,\n # label.right() + 1,\n # label.strand(),\n # label.left() + 1,\n # label.right() + 1,\n # label.strand(),\n # seq_type,\n # label.seqname(),\n # label.right() if label.strand() == \"+\" else label.left(),\n # label.strand()\n # )\n\n\ndef get_upstream_label_per_label(labels):\n # type: (Labels) -> Dict[str, Label]\n\n sorted_labels = [l for l in labels.sort_by(\"left\")]\n num_labels = len(sorted_labels)\n\n gene_key_to_upstream_label = dict() # type: Dict[str, Label]\n\n for i, label in enumerate(sorted_labels):\n\n prev_label = None\n\n if label.strand() == \"+\":\n if i > 0:\n prev_i = i - 1\n prev_label = sorted_labels[prev_i]\n else:\n if i < num_labels - 1:\n prev_i = i + 1\n prev_label = sorted_labels[prev_i]\n\n gene_key_to_upstream_label[create_gene_key_from_label(label)] = prev_label\n\n return gene_key_to_upstream_label\n\n\ndef extract_labeled_sequences(sequences, labels, **kwargs):\n # type: (Dict[str, Seq], Labels, Dict[str, Any]) -> Dict[str, Seq]\n\n func_fasta_header_creator = get_value(kwargs, \"func_fhc\", None)\n kwargs_fasta_header_creator = get_value(kwargs, \"kwargs_fhc\", None)\n\n dict_labeled_sequences = dict() # type: Dict[str, Seq]\n\n gene_key_to_upstream_label = get_upstream_label_per_label(labels)\n\n for i, label in enumerate(labels):\n labeled_sequence = extract_labeled_sequence(label, sequences, **kwargs)\n lorf_nt = extract_labeled_sequence(label, sequences, lorf=True, **kwargs)\n offset = len(lorf_nt) - (label.right() - label.left() + 1)\n\n upstream_label = gene_key_to_upstream_label[create_gene_key_from_label(label)]\n upstream_left = upstream_right = -1\n upstream_strand = \"\"\n\n if upstream_label is not None:\n upstream_left = upstream_label.left() + 1\n upstream_right = upstream_label.right() + 1\n upstream_strand = upstream_label.strand()\n\n fasta_header = str(i)\n if func_fasta_header_creator is not None:\n if kwargs_fasta_header_creator is not None:\n fasta_header = func_fasta_header_creator(label, offset=offset, lorf_nt=lorf_nt,\n upstream_left=upstream_left,\n upstream_right=upstream_right,\n upstream_strand=upstream_strand,\n **kwargs_fasta_header_creator)\n else:\n fasta_header = func_fasta_header_creator(label, offset=offset, lorf_nt=lorf_nt)\n\n dict_labeled_sequences[fasta_header] = labeled_sequence\n\n return dict_labeled_sequences\n\n\ndef extract_labeled_sequences_for_genome(env, gi, **kwargs):\n # type: (Environment, GenomeInfo, Dict[str, Any]) -> Dict[str, Seq]\n\n pf_sequences = get_pf_sequences_for_genome(env, gi)\n pf_labels = get_pf_labels_for_genome(env, gi, **kwargs)\n\n try:\n sequences = read_fasta_into_hash(pf_sequences)\n labels = read_labels_from_file(pf_labels, **kwargs)\n except IOError as e:\n log.warning(\"Could not read sequence/labels files for genome: {}\".format(gi.name))\n raise e\n\n return extract_labeled_sequences(sequences, labels, **kwargs)\n\n\ndef translate_sequences_to_aa(sequences_nt):\n # type: (Dict[str, Seq]) -> Dict[str, Seq]\n\n sequences_aa = dict()\n for k, v in sequences_nt.items():\n try:\n v_aa = v.translate()\n sequences_aa[k] = v_aa\n except ValueError:\n log.warning(\"Could not translate sequence:\\n{}\".format(v))\n\n return sequences_aa\n\n\ndef dict_intersection_by_key(dict_a, dict_b):\n # type: (Dict, Dict) -> None\n \"\"\"Removes elements from both dictionaries with keys not in both\"\"\"\n keys_a = set(dict_a.keys())\n keys_b = set(dict_b.keys())\n keys_intersection = keys_a.intersection(keys_b)\n\n keys_a_unique = keys_a.difference(keys_intersection)\n keys_b_unique = keys_b.difference(keys_intersection)\n\n def remove_keys_from_dict(d, keys):\n # type: (Dict, Iterable) -> None\n for k in keys:\n del d[k]\n\n remove_keys_from_dict(dict_a, keys_a_unique)\n remove_keys_from_dict(dict_b, keys_b_unique)\n\n\ndef extract_labeled_sequences_for_genomes(env, gil, pf_output, **kwargs):\n # type: (Environment, GenomeInfoList, str, Dict[str, Any]) -> str\n\n # open file for writing\n try:\n f_aa = open(pf_output, \"w\")\n\n for gi in tqdm(gil, total=len(gil)):\n func_fasta_header_creator = pack_fasta_header\n kwargs_fasta_header_creator = {\"gi\": gi}\n try:\n sequences_nt = extract_labeled_sequences_for_genome(\n env, gi,\n func_fhc=func_fasta_header_creator,\n kwargs_fhc=kwargs_fasta_header_creator,\n **kwargs\n )\n sequences_aa = translate_sequences_to_aa(sequences_nt)\n\n # only keep sequences that have been translated\n dict_intersection_by_key(sequences_nt, sequences_aa)\n\n append_sequences_to_file(sequences_aa, f_aa)\n except IOError:\n pass\n\n f_aa.close()\n except OSError:\n log.warning(\"Could not open file for writing sequences:\\n{}\".format(pf_output))\n\n return pf_output\n\n\ndef run_blast_on_sequence_file(env, pf_q_aa, pf_db, pf_blast_output, **kwargs):\n # type: (Environment, str, str, str, Dict[str, Any]) -> None\n run_blast_alignment(pf_q_aa, pf_db, pf_blast_output, use_diamond=True, **kwargs)\n\n\ndef get_orthologs_from_files(env, pf_q_list, pf_t_list, pf_output, **kwargs):\n # type: (Environment, str, str, str, Dict[str, Any]) -> str\n\n sbsp_options = get_value(kwargs, \"sbsp_options\", SBSPOptions(env)) # type: SBSPOptions\n\n fn_q_labels = get_value(kwargs, \"fn_q_labels\", \"ncbi.gff\")\n fn_t_labels = get_value(kwargs, \"fn_t_labels\", \"ncbi.gff\")\n\n q_gil = GenomeInfoList.init_from_file(pf_q_list)\n t_gil = GenomeInfoList.init_from_file(pf_t_list)\n\n pd_work = env[\"pd-work\"]\n\n # Extract data for blast run\n pf_q_aa = os.path.join(pd_work, \"q.faa\")\n pf_q_nt = os.path.join(pd_work, \"q.fnt\")\n pf_t_aa = os.path.join(pd_work, \"t.faa\")\n pf_t_nt = os.path.join(pd_work, \"t.fnt\")\n\n custom = {\n \"reverse_complement\": True,\n \"ignore_frameshifted\": True,\n \"ignore_partial\": True\n }\n\n extract_labeled_sequences_for_genomes(env, q_gil, pf_q_aa, fn_labels=fn_q_labels, **custom, **kwargs)\n extract_labeled_sequences_for_genomes(env, t_gil, pf_t_aa, fn_labels=fn_t_labels, **custom, **kwargs)\n\n pf_blast_db = os.path.join(pd_work, \"blast.db\")\n create_blast_database(pf_t_aa, pf_blast_db, seq_type=\"prot\", use_diamond=True) # FIXME: cleanup\n\n # Run blast\n pf_blast_results = os.path.join(pd_work, \"blast.xml\")\n run_blast_on_sequence_file(env, pf_q_aa, pf_blast_db, pf_blast_results, **kwargs)\n\n # Parse data, filter, and write to CSV\n parse_filter_and_convert_to_csv(pf_blast_results, pf_output,\n pf_q_original_nt=pf_q_nt,\n pf_t_original_nt=pf_t_nt,\n pf_q_original_aa=pf_q_aa,\n pf_t_original_aa=pf_t_aa,\n distance_min=sbsp_options.safe_get(\"filter-min-distance\"),\n distance_max=sbsp_options.safe_get(\"filter-max-distance\"),\n **kwargs)\n\n return pf_output\n","sub_path":"code/python/lib/sbsp_alg/ortholog_finder.py","file_name":"ortholog_finder.py","file_ext":"py","file_size_in_byte":27709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"262739809","text":"from django.conf.urls import patterns, url\n\n# application imoprts\nfrom .views import Home, BarView, PieView\n\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = patterns('finance.views',\n url(r'^$', Home.as_view(), name='home'),\n url(r'^bar/$', BarView.as_view(), name='bar'),\n url(r'^pie/$', PieView.as_view(), name='pie'),\n\n url(r'^balance/(?Pget|recalculate)/$', 'balance', name='balance'),\n\n)\n","sub_path":"finance/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"317884572","text":"# -*- coding: utf-8 -*-\n\nimport pandas as pd\n\nfrom collections import Counter\n\nclass MachineLearningCommonLib():\n \n def calc_classification_error(self, accuracy):\n return 1 - accuracy\n \n # Transform categorical data into binary features\n # ===============================================\n \n # In this assignment, we will implement binary decision trees (decision trees for binary features, \n # a specific case of categorical variables taking on two values, e.g., true/false). \n # Since all of our features are currently categorical features, we want to turn them into binary features.\n \n def unpack(self, dict_data):\n return pd.Series(dict_data)\n \n '''\n This function is to convert the categories belong to a row to columns for each category and then remove the column that has the categories\n '''\n def one_hot_encoding(self, df_data):\n categorical_variables = []\n for feature_name, feature_type in zip(df_data.columns.values, df_data.dtypes):\n if feature_type == object:\n categorical_variables.append(feature_name)\n \n for feature in categorical_variables:\n print('Processing feature: {} now'.format(feature))\n df_data_one_hot_encoded = df_data[feature].apply(lambda x: {x: 1})\n df_data_unpacked = df_data_one_hot_encoded.apply(lambda x: self.unpack(x)) \n \n # Change None's to 0's\n df_data_unpacked = df_data_unpacked[df_data_unpacked.columns.values].fillna(0)\n df_data = df_data.drop(feature, 1)\n \n df_data[df_data_unpacked.columns.values] = df_data_unpacked\n \n return df_data\n \n # For instance, the home_ownership feature represents the home ownership status of the loanee, which is either own, mortgage or rent. \n # For example, if a data point has the feature\n \n # {'home_ownership': 'RENT'}\n \n # we want to turn this into three features:\n \n # { \n # 'home_ownership = OWN' : 0, \n # 'home_ownership = MORTGAGE' : 0, \n # 'home_ownership = RENT' : 1\n # }\n \n # Decision tree implementation\n # ============================\n \n # In this section, we will implement binary decision trees from scratch. There are several steps involved in building a decision tree. \n # For that reason, we have split the entire assignment into several sections.\n \n # Function to count number of mistakes while predicting majority class\n # --------------------------------------------------------------------\n \n # Recall from the lecture that prediction at an intermediate node works by predicting the majority class for all data points that belong to this node. \n # Now, we will write a function that calculates the number of misclassified examples when predicting the majority class. \n # This will be used to help determine which feature is the best to split on at a given node of the tree.\n \n # Note: Keep in mind that in order to compute the number of mistakes for a majority classifier, we only need the label (y values) of the data points in the node.\n \n # Steps to follow:\n \n # - Step 1: Calculate the number of safe loans and risky loans.\n # - Step 2: Since we are assuming majority class prediction, all the data points that are not in the majority class are considered mistakes.\n # - Step 3: Return the number of mistakes.\n \n # 7. Now, let us write the function intermediate_node_num_mistakes which computes the number of misclassified examples of an intermediate node \n # given the set of labels (y values) of the data points contained in the node. Your code should be analogous to\n def intermediate_node_num_mistakes(self, labels_in_node):\n # Corner case: If labels_in_node is empty, return 0\n if len(labels_in_node) == 0:\n return 0 \n \n #labels_in_node = [-1, -1, 1, 1, 1]\n elem_count = Counter(labels_in_node)\n majority_classifier = max(elem_count.keys(), key=(lambda key: elem_count[key]))\n #print(\"Major classifier = %s.\" % majority_classifier)\n # Count the number of 1's (safe loans)\n safe_loans_num = elem_count['1'] \n # Count the number of -1's (risky loans)\n risky_loans_num = elem_count['-1'] \n # Return the number of mistakes that the majority classifier makes.\n #labels_in_node_arr = pd.DataFrame(data=labels_in_node)\n #mistake_labels = labels_in_node_arr[labels_in_node_arr[0] != majority_classifier]\n mistake_labels_size = 0\n for label in labels_in_node:\n if label != majority_classifier:\n mistake_labels_size += 1\n \n return mistake_labels_size\n \n # Function to pick best feature to split on\n # =========================================\n \n # The function best_splitting_feature takes 3 arguments:\n \n # 1.The data\n # 2.The features to consider for splits (a list of strings of column names to consider for splits)\n # 3.The name of the target/label column (string)\n \n # The function will loop through the list of possible features, and consider splitting on each of them. \n # It will calculate the classification error of each split and return the feature that had the smallest classification error when split on.\n \n # Recall that the classification error is defined as follows:\n \n #accuracy = #correctly classified examples / #total examples\n \n # 9. Follow these steps to implement best_splitting_feature:\n \n # - Step 1: Loop over each feature in the feature list\n # - Step 2: Within the loop, split the data into two groups: one group where all of the data has feature value 0 or False (we will call this the left split), and one group where all of the data has feature value 1 or True (we will call this the right split). Make sure the left split corresponds with 0 and the right split corresponds with 1 to ensure your implementation fits with our implementation of the tree building process.\n # - Step 3: Calculate the number of misclassified examples in both groups of data and use the above formula to compute theclassification error.\n # - Step 4: If the computed error is smaller than the best error found so far, store this feature and its error.\n \n # Note: Remember that since we are only dealing with binary features, we do not have to consider thresholds for real-valued features. \n # This makes the implementation of this function much easier.\n \n # Your code should be analogous to\n \n def best_splitting_feature(self, data, features, target):\n \n target_values = data[target]\n best_feature = None # Keep track of the best feature \n best_error = 10 # Keep track of the best error so far \n # Note: Since error is always <= 1, we should intialize it with something larger than 1.\n \n # Convert to float to make sure error gets computed correctly.\n num_data_points = float(len(data)) \n \n # Loop through each feature to consider splitting on that feature\n for feature in features:\n \n # The left split will have all data points where the feature value is 0\n left_split = data[data[feature] == 0]\n \n # The right split will have all data points where the feature value is 1\n right_split = data[data[feature] == 1]\n \n # Calculate the number of misclassified examples in the left split.\n # Remember that we implemented a function for this! (It was called intermediate_node_num_mistakes)\n left_mistakes = self.intermediate_node_num_mistakes(left_split[target]) \n \n # Calculate the number of misclassified examples in the right split.\n right_mistakes = self.intermediate_node_num_mistakes(right_split[target])\n \n # Compute the classification error of this split.\n # Error = (# of mistakes (left) + # of mistakes (right)) / (# of data points)\n error = (left_mistakes + right_mistakes) / num_data_points\n \n # If this is the best error we have found so far, store the feature as best_feature and the error as best_error\n if error < best_error:\n best_feature = feature\n best_error = error\n \n return best_feature # Return the best feature we found\n \n \n # Building the tree\n # =================\n \n # With the above functions implemented correctly, we are now ready to build our decision tree. \n # Each node in the decision tree is represented as a dictionary which contains the following keys and possible values:\n # { \n # 'is_leaf' : True/False.\n # 'prediction' : Prediction at the leaf node.\n # 'left' : (dictionary corresponding to the left tree).\n # 'right' : (dictionary corresponding to the right tree).\n # 'splitting_feature' : The feature that this node splits on.\n # }\n \n # 10. First, we will write a function that creates a leaf node given a set of target values. Your code should be analogous to\n def create_leaf(self, target_values): \n # Create a leaf node\n leaf = {\n 'splitting_feature' : None,\n 'left' : None,\n 'right' : None,\n 'is_leaf': True,\n 'prediction': 0\n } \n \n # Count the number of data points that are +1 and -1 in this node.\n num_ones = len(target_values[target_values == +1])\n num_minus_ones = len(target_values[target_values == -1]) \n \n # For the leaf node, set the prediction to be the majority class.\n # Store the predicted class (1 or -1) in leaf['prediction']\n if num_ones > num_minus_ones:\n leaf['prediction'] = 1 \n else:\n leaf['prediction'] = -1 \n \n # Return the leaf node\n return leaf \n \n # Early stopping methods for decision trees\n # =========================================\n\n # In this section, we will extend the binary tree implementation from the previous assignment in order to handle some early stopping conditions. \n # Recall the 3 early stopping methods that were discussed in lecture:\n\n # Reached a maximum depth. (set by parameter max_depth).\n # Reached a minimum node size. (set by parameter min_node_size).\n # Don't split if the gain in error reduction is too small. (set by parameter min_error_reduction).\n \n # Early stopping condition 1: Maximum depth\n # =========================================\n\n # Recall that we already implemented the maximum depth stopping condition in the previous assignment. In this assignment, we will experiment with this condition a bit more \n # and also write code to implement the 2nd and 3rd early stopping conditions. \n\n # Early stopping condition 2: Minimum node size\n # =============================================\n\n # The function reached_minimum_node_size takes 2 arguments:\n \n # 1. The data (from a node)\n # 2. The minimum number of data points that a node is allowed to split on, min_node_size.\n \n # 7. This function simply calculates whether the number of data points at a given node is less than or equal to the specified minimum node size. \n # This function will be used to detect this early stopping condition in the decision_tree_create function. Your code should be analogous to\n \n def reached_minimum_node_size(self, data, min_node_size):\n # Return True if the number of data points is less than or equal to the minimum node size.\n return True if len(data) <= min_node_size else False\n \n # Early stopping condition 3: Minimum gain in error reduction\n # ===========================================================\n \n # The function error_reduction takes 2 arguments:\n \n # 1. The error before a split, error_before_split.\n # 2. The error after a split, error_after_split.\n \n # 8. This function computes the gain in error reduction, i.e., the difference between the error before the split and that after the split. \n # This function will be used to detect this early stopping condition in the decision_tree_create function. Your code should be analogous to\n \n def error_reduction(self, error_before_split, error_after_split):\n # Return the error before the split minus the error after the split.\n return error_before_split - error_after_split\n \n # Implementing early stopping condition 2: minimum node size:\n # ===========================================================\n\n # - Step 1: Use the function reached_minimum_node_size that you implemented earlier to write an if condition to detect whether we have hit the base case, i.e., the node does not have enough data points and should be turned into a leaf. Don't forget to use the min_node_size argument.\n # - Step 2: Return a leaf. This line of code should be the same as the other (pre-implemented) stopping conditions.\n\n # Implementing early stopping condition 3: minimum error reduction:\n # =================================================================\n\n # Note: This has to come after finding the best splitting feature so we can calculate the error after splitting in order to calculate the error reduction. \n # Recall that classification error is defined as:\n\n # classification error = # mistakes / # total examples\n\n # - Step 1: Calculate the classification error before splitting.\n # - Step 2: Calculate the classification error after splitting. This requires calculating the number of mistakes in the left and right splits, and then dividing by the total number \n # of examples.\n # - Step 3: Use the function error_reduction to that you implemented earlier to write an if condition to detect whether the reduction in error is less than the \n # constant provided (min_error_reduction). Don't forget to use that argument.\n \n # 11. Now, we will provide a Python skeleton of the learning algorithm. Note that this code is not complete; it needs to be completed by you if you are using Python. \n # Otherwise, your code should be analogous to\n \n def build_binary_decision_tree(self, data, features, target, current_depth = 0, max_depth = 10):\n remaining_features = features[:] # Make a copy of the features.\n \n target_values = data[target]\n print(\"--------------------------------------------------------------------\")\n print(\"Subtree, depth = %s (%s data points).\" % (current_depth, len(target_values)))\n \n # Stopping condition 1\n # (Check if there are mistakes at current node.\n # Recall you wrote a function intermediate_node_num_mistakes to compute this.)\n if self.intermediate_node_num_mistakes(target_values) == 0: \n print(\"Stopping condition 1 reached.\") \n # If not mistakes at current node, make current node a leaf node\n return self.create_leaf(target_values)\n \n # Stopping condition 2 (check if there are remaining features to consider splitting on)\n if remaining_features == None: \n print(\"Stopping condition 2 reached.\") \n # If there are no remaining features to consider, make current node a leaf node\n return self.create_leaf(target_values) \n \n # Early stopping condition 1: Reached max depth limit.\n if current_depth >= max_depth:\n print(\"Reached maximum depth. Stopping for now.\")\n # If the max tree depth has been reached, make current node a leaf node\n return self.create_leaf(target_values)\n \n # Early stopping condition 2: Reached the minimum node size.\n # If the number of data points is less than or equal to the minimum size, return a leaf.\n if self.reached_minimum_node_size(target_values, 10):\n print(\"Early stopping condition 2 reached. Reached minimum node size.\")\n return self.create_leaf(target_values)\n \n # Find the best splitting feature (recall the function best_splitting_feature implemented above)\n splitting_feature = self.best_splitting_feature(data, features, target)\n \n # Split on the best feature that we found. \n left_split = data[data[splitting_feature] == 0]\n right_split = data[data[splitting_feature] == 1]\n \n # Early stopping condition 3: Minimum error reduction\n # Calculate the error before splitting (number of misclassified examples \n # divided by the total number of examples)\n error_before_split = self.intermediate_node_num_mistakes(target_values) / float(len(data))\n \n # Calculate the error after splitting (number of misclassified examples \n # in both groups divided by the total number of examples)\n left_mistakes = self.intermediate_node_num_mistakes(left_split[target]) \n right_mistakes = self.intermediate_node_num_mistakes(right_split[target]) \n error_after_split = (left_mistakes + right_mistakes) / float(len(data))\n \n # If the error reduction is LESS THAN OR EQUAL TO min_error_reduction, return a leaf. sample values: 0.0, 0.05, 0.1, and 0.14\n if self.error_reduction(error_before_split, error_after_split) <= 0.05:\n print(\"Early stopping condition 3 reached. Minimum error reduction.\")\n return self.create_leaf(target_values)\n \n remaining_features.remove(splitting_feature)\n print(\"Split on feature %s. (%s, %s)\" % (splitting_feature, len(left_split), len(right_split)))\n \n # Create a leaf node if the split is \"perfect\"\n if len(left_split) == len(data):\n print(\"Creating leaf node.\")\n return self.create_leaf(left_split[target])\n if len(right_split) == len(data):\n print(\"Creating leaf node.\")\n return self.create_leaf(right_split[target])\n \n # Repeat (recurse) on left and right subtrees\n left_tree = self.build_binary_decision_tree(left_split, remaining_features, target, current_depth + 1, max_depth) \n right_tree = self.build_binary_decision_tree(right_split, remaining_features, target, current_depth + 1, max_depth) \n \n return {'is_leaf' : False, \n 'prediction' : None,\n 'splitting_feature': splitting_feature,\n 'left' : left_tree, \n 'right' : right_tree}\n \n \n","sub_path":"python/coursera/ml_common/commonlib.py","file_name":"commonlib.py","file_ext":"py","file_size_in_byte":18859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"244212083","text":"'''\r\n@author: Bradley \r\n'''\r\nimport random\r\n\r\n\r\nimport tkinter as tk\r\n\r\n# Window?\r\ngame=tk.Tk()\r\ngame.title(\"Dice Game\")\r\ngame.geometry(\"600x400\")\r\n\r\nlabel = tk.Label(text = \"GAME\")\r\nlabel.grid(column=0,row=0)\r\n\r\nroll = tk.Button(game,text=\"Roll\")\r\nroll.grid(column=5,row=5)\r\n\r\n\r\n\r\n\r\n\r\n\r\ngame.mainloop()\r\n\r\n# Use to add more dice\r\n'''\r\n[-----]\\n[0 0]\\n[0 0]\\n[0 0]\\n[-----]\r\n'''\r\n\r\n\r\n#die = [\"[-----]\\n[ ]\\n[ 0 ]\\n[ ]\\n[-----]\",\"[-----]\\n[0 ]\\n[ ]\\n[ 0]\\n[-----]\",\"[-----]\\n[0 ]\\n[ 0 ]\\n[ 0]\\n[-----]\",\"[-----]\\n[0 0]\\n[ ]\\n[0 0]\\n[-----]\",\"[-----]\\n[0 0]\\n[ 0 ]\\n[0 0]\\n[-----]\",\"[-----]\\n[0 0]\\n[0 0]\\n[0 0]\\n[-----]\"]\r\n\r\n#run = True\r\n\r\n#while run:\r\n# num = random.randint(0,5)\r\n# print(die[num])\r\n# go = str(input(\"Type \\\"stop\\\" to stop rolling, otherwise hit enter \\n\"))\r\n# if go == \"stop\":\r\n# run = False\r\n\r\n\r\n\r\n","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"416931282","text":"# -*- coding: utf-8 -*-\nimport os\nfrom alchemydb import Base, engine\nfrom sqlalchemy import Column, Integer, String, Text, text, DateTime\nfrom sqlalchemy.sql.functions import current_timestamp\nfrom datetime import datetime\n\nclass Tasks(Base):\n __tablename__ = 'tasks'\n\n id = Column(\n Integer,\n primary_key=True,\n autoincrement=True\n )\n name = Column(String(256))\n text = Column(String(256))\n created_at = Column(\n DateTime,\n default=datetime.now(),\n nullable=False,\n server_default=current_timestamp()\n )\n updated_at = Column(\n DateTime,\n default=datetime.now(),\n nullable=False,\n onupdate=datetime.now()\n # server_default=text(\n # 'CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'\n # )\n )\n\nif __name__ == \"__main__\":\n Base.metadata.create_all(engine)","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"63491241","text":"import os \nfrom bs4 import BeautifulSoup\n\ndef loadStudentNamesAndAliases():\n # Load in student names and their aliases\n # Names and associated aliases are stored in a text file where each line is:\n # Anonymous Name, Student Name, Alias\n dAliases = dict()\n with open(\"Student Names and Aliases.txt\") as fh:\n fh.readline() # Disregard the header\n for line in fh:\n anonName, realName, alias = [i.strip() for i in line.split(\",\")]\n dAliases[anonName] = (realName, alias)\n return dAliases\n\n\n# Load student names\ndAliases = loadStudentNamesAndAliases()\n\n\n# Path to where the posts should be put\npathToPosts = os.path.join(\"..\", \"_posts\")\n\n\nfor anonName in dAliases:\n\trealName, alias = dAliases[anonName]\n\n\t# HTML Game Post (if it exists)\n\tpathToStudentDir = os.path.join(\"..\", \"games\", \"HTML\", anonName)\n\tif os.path.exists(pathToStudentDir):\n\t\tpathToPost = os.path.join(pathToPosts, \"2014-08-04-\"+alias+\"_HTML.html\")\n\t\twith open(pathToPost, \"w\") as fh:\n\t\t\t# yaml front matter\n\t\t\tfh.write(\"---\\n\")\n\t\t\tfh.write(\"layout: htmlGame\\n\")\n\t\t\tfh.write(\"title: {0}\\n\".format(alias))\n\t\t\tfh.write(\"tags: HTML\\n\")\n\t\t\tfh.write(\"studentName: {0}\\n\".format(alias))\n\t\t\tfh.write(\"screenshotURL: ../../../games/HTML/{0}/screenshot.png\\n\".format(anonName))\n\t\t\tfh.write(\"---\\n\")\n\n\t\t\t# yaml content\n\t\t\tfh.write(\"\")\n\n\n\t# JavaScript Game Post (if it exists)\n\tpathToStudentDir = os.path.join(\"..\", \"games\", \"JavaScript\", anonName)\n\tif os.path.exists(pathToStudentDir):\n\t\tpathToPost = os.path.join(pathToPosts, \"2014-08-04-\"+alias+\"_JavaScript.html\")\n\t\tpathToJSGame = os.path.join(\"..\", \"games\", \"JavaScript\", anonName, \"index.html\")\n\t\tsoup = BeautifulSoup(open(pathToJSGame))\n\t\tscriptString = str(soup.body.script)\n\t\twith open(pathToPost, \"w\") as fh:\n\t\t\t# yaml front matter\n\t\t\tfh.write(\"---\\n\")\n\t\t\tfh.write(\"layout: javascriptGame\\n\")\n\t\t\tfh.write(\"title: {0}\\n\".format(alias))\n\t\t\tfh.write(\"tags: JavaScript\\n\")\n\t\t\tfh.write(\"studentName: {0}\\n\".format(alias))\n\t\t\tfh.write(\"screenshotURL: ../../../games/JavaScript/{0}/screenshot.png\\n\".format(anonName))\n\t\t\tfh.write(\"---\\n\")\n\n\t\t\t# yaml content\n\t\t\tfh.write(scriptString)\n\n\t# Stencyl Game Post (if it exists)\n\tpathToStudentDir = os.path.join(\"..\", \"games\", \"stencyl\", anonName)\n\tif os.path.exists(pathToStudentDir):\n\t\tpathToPost = os.path.join(pathToPosts, \"2014-08-04-\"+alias+\"_Stencyl.html\")\n\n\t\t# Get game resolution and filename\n\t\tpathToResolution = os.path.join(pathToStudentDir, \"Game Info.txt\")\n\t\twidth, height = \"0\", \"0\"\n\t\twith open(pathToResolution, \"r\") as fh:\n\t\t\ttitle = fh.readline().split(\":\")[-1].strip()\n\t\t\twidth, height = fh.readline().split(\":\")[-1].split(\",\")\n\t\t\twidth, height = width.strip(), height.strip()\n\t\tswfFilename = title+\".swf\"\n\t\tscreenshotFilename = title+\".png\"\n\n\t\twith open(pathToPost, \"w\") as fh:\n\t\t\t# yaml front matter\n\t\t\tfh.write(\"---\\n\")\n\t\t\tfh.write(\"layout: stencylGame\\n\")\n\t\t\tfh.write(\"title: {0}\\n\".format(alias))\n\t\t\tfh.write(\"tags: stencyl\\n\")\n\t\t\tfh.write(\"studentName: {0}\\n\".format(alias))\n\t\t\tfh.write(\"screenshotURL: ../../../games/Stencyl/{0}/{1}\\n\".format(anonName, screenshotFilename))\n\t\t\tfh.write(\"---\\n\")\n\n\t\t\t# yaml content\n\t\t\tfh.write(\"
    \".format(width, height))\n\t\t\tfh.write(\"\".format(anonName, swfFilename, width, height))\n\t\t\tfh.write(\"\")\n\t\t\tfh.write(\"
    \")","sub_path":"scripts/generateGamePosts.py","file_name":"generateGamePosts.py","file_ext":"py","file_size_in_byte":3514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"343581786","text":"import math\nimport torch\nimport numpy as np\nfrom torch.distributions import Poisson\nfrom torch import nn\nfrom torch import autograd\n\nclass PoissonProcess(object):\n \"\"\"docstring for PoissonProcess\"\"\"\n\n def __init__(self, intensity_grid, log_intensity=None, observations=None):\n super(PoissonProcess, self).__init__()\n\n self.intensity_grid = intensity_grid\n if log_intensity is not None:\n self.log_intensity = nn.Parameter(log_intensity)\n else:\n self.log_intensity = nn.Parameter(torch.zeros(intensity_grid.size(0)))\n self.observations = observations\n self.in_dim = self.intensity_grid.shape[-1]\n self.n_pts = self.intensity_grid.shape[0]\n self.delta_x = torch.abs(self.intensity_grid[0, -1] - self.intensity_grid[1, -1])\n\n def simulate(self, intensity_grid=None, log_intensity=None):\n\n if intensity_grid is not None:\n self.update_grid(intensity_grid)\n if log_intensity is not None:\n self.update_val(log_intensity)\n\n sim_points = torch.tensor([])\n\n for pt in range(self.n_pts):\n ## draw points from poisson ##\n rate = torch.exp(self.log_intensity[pt]) * (self.delta_x ** self.in_dim)\n dist = Poisson(rate)\n n_draw = int(dist.sample().item())\n\n samples = torch.zeros(n_draw, self.in_dim)\n ## sample their locations ##\n for dim in range(self.in_dim):\n samples[:, dim] = self.delta_x * torch.rand(n_draw)\n samples[:, dim] += self.intensity_grid[pt, dim] + self.delta_x/2\n\n ## append to sim_points ##\n sim_points = torch.cat((sim_points, samples))\n\n return sim_points\n\n def update_grid(self, grid):\n self.intensity_grid = grid\n\n def update_val(self, val):\n self.log_intensity.data = val\n\n def update_obs(self, obs):\n self.observations = obs\n\n def compute_obs_distance(self, observations=None):\n n = observations.size(0)\n m = self.intensity_grid.size(0)\n d = observations.size(1)\n\n xx = observations.unsqueeze(1).expand(n, m, d)\n yy = self.intensity_grid.unsqueeze(0).expand(n, m, d)\n\n dist = torch.pow(xx - yy, 2).sum(2)\n return dist\n\n def likelihood(self, observations=None):\n\n if observations is not None:\n self.update_obs(observations)\n\n dist = Poisson(self.delta_x.pow(self.in_dim) * self.log_intensity.exp())\n\n if type(observations) is list:\n ## if we're storing multiple draws ##\n lh = 0\n for obs in observations:\n obs_dist = self.compute_obs_distance(obs)\n samples_from = obs_dist.min(1)[1]\n\n counts_per_bin = torch.zeros(self.intensity_grid.size(0))\n for smp in samples_from:\n counts_per_bin[smp] += 1\n\n lh += dist.log_prob(counts_per_bin).sum()\n return lh\n else:\n ## storing a single draw\n obs_dist = self.compute_obs_distance(observations)\n samples_from = obs_dist.min(1)[1]\n\n counts_per_bin = torch.zeros(self.intensity_grid.size(0))\n for smp in samples_from:\n counts_per_bin[smp] += 1\n\n lh = dist.log_prob(counts_per_bin).sum()\n return lh\n\n def compute_grad(self, observations=None):\n if observations is not None:\n self.update_obs(observations)\n lh = self.likelihood(observations)\n lh.backward()\n return self.log_intensity.grad\n\n def compute_hessian(self, observations=None):\n if observations is not None:\n self.update_obs(observations)\n lh = self.likelihood(observations)\n grad = autograd.grad(lh, self.log_intensity, create_graph=True)[0]\n grad = autograd.grad(grad.sum(), self.log_intensity)[0]\n return torch.diag(grad)\n","sub_path":"cox-process/poisson_process.py","file_name":"poisson_process.py","file_ext":"py","file_size_in_byte":3947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"390693989","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: C:\\Users\\HDi\\Google Drive\\ProgramCodes\\PythonCodes\\gaeio\\src\\gui\\importhorizonfile.py\n# Compiled at: 2020-04-25 15:07:54\n# Size of source mod 2**32: 16534 bytes\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nimport numpy as np, sys, os\nsys.path.append(os.path.dirname(__file__)[:-4][:-4][:-6])\nfrom gaeio.src.basic.data import data as basic_data\nfrom gaeio.src.horizon.inputoutput import inputoutput as horizon_io\nfrom gaeio.src.horizon.analysis import analysis as horizon_ays\nfrom gaeio.src.vis.messager import messager as vis_msg\nQtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)\nQtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True)\n\nclass importhorizonfile(object):\n horizondata = {}\n rootpath = ''\n iconpath = os.path.dirname(__file__)\n dialog = None\n filelist = []\n\n def setupGUI(self, ImportHorionFile):\n ImportHorionFile.setObjectName('ImportHorionFile')\n ImportHorionFile.setFixedSize(600, 320)\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(os.path.join(self.iconpath, 'icons/copy.png')), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n ImportHorionFile.setWindowIcon(icon)\n self.lblfile = QtWidgets.QLabel(ImportHorionFile)\n self.lblfile.setObjectName('lblfile')\n self.lblfile.setGeometry(QtCore.QRect(10, 10, 110, 30))\n self.ldtfile = QtWidgets.QLineEdit(ImportHorionFile)\n self.ldtfile.setObjectName('ldtfile')\n self.ldtfile.setGeometry(QtCore.QRect(130, 10, 390, 30))\n self.btnfile = QtWidgets.QPushButton(ImportHorionFile)\n self.btnfile.setObjectName('btnfile')\n self.btnfile.setGeometry(QtCore.QRect(530, 10, 60, 30))\n self.lbltype = QtWidgets.QLabel(ImportHorionFile)\n self.lbltype.setObjectName('lbltype')\n self.lbltype.setGeometry(QtCore.QRect(30, 50, 100, 30))\n self.cbbtype = QtWidgets.QComboBox(ImportHorionFile)\n self.cbbtype.setObjectName('cbbtype')\n self.cbbtype.setGeometry(QtCore.QRect(130, 50, 460, 30))\n self.lblpara = QtWidgets.QLabel(ImportHorionFile)\n self.lblpara.setObjectName('lblpara')\n self.lblpara.setGeometry(QtCore.QRect(10, 100, 110, 30))\n self.lblinl = QtWidgets.QLabel(ImportHorionFile)\n self.lblinl.setObjectName('lblinl')\n self.lblinl.setGeometry(QtCore.QRect(20, 140, 100, 30))\n self.cbbinl = QtWidgets.QComboBox(ImportHorionFile)\n self.cbbinl.setObjectName('cbbinl')\n self.cbbinl.setGeometry(QtCore.QRect(130, 140, 60, 30))\n self.lblxl = QtWidgets.QLabel(ImportHorionFile)\n self.lblxl.setObjectName('lblxl')\n self.lblxl.setGeometry(QtCore.QRect(20, 180, 100, 30))\n self.cbbxl = QtWidgets.QComboBox(ImportHorionFile)\n self.cbbxl.setObjectName('cbbxl')\n self.cbbxl.setGeometry(QtCore.QRect(130, 180, 60, 30))\n self.lblz = QtWidgets.QLabel(ImportHorionFile)\n self.lblz.setObjectName('lbz')\n self.lblz.setGeometry(QtCore.QRect(20, 220, 100, 30))\n self.cbbz = QtWidgets.QComboBox(ImportHorionFile)\n self.cbbz.setObjectName('cbbz')\n self.cbbz.setGeometry(QtCore.QRect(130, 220, 60, 30))\n self.lblcomment = QtWidgets.QLabel(ImportHorionFile)\n self.lblcomment.setObjectName('lblcomment')\n self.lblcomment.setGeometry(QtCore.QRect(220, 140, 100, 30))\n self.cbbcomment = QtWidgets.QComboBox(ImportHorionFile)\n self.cbbcomment.setObjectName('cbbcomment')\n self.cbbcomment.setGeometry(QtCore.QRect(330, 140, 60, 30))\n self.lbldelimiter = QtWidgets.QLabel(ImportHorionFile)\n self.lbldelimiter.setObjectName('lbldelimiter')\n self.lbldelimiter.setGeometry(QtCore.QRect(220, 180, 100, 30))\n self.cbbdelimiter = QtWidgets.QComboBox(ImportHorionFile)\n self.cbbdelimiter.setObjectName('cbbdelimiter')\n self.cbbdelimiter.setGeometry(QtCore.QRect(330, 180, 60, 30))\n self.lblvalueundefined = QtWidgets.QLabel(ImportHorionFile)\n self.lblvalueundefined.setObjectName('lblvalueundefined')\n self.lblvalueundefined.setGeometry(QtCore.QRect(420, 140, 100, 30))\n self.ldtvalueundefined = QtWidgets.QLineEdit(ImportHorionFile)\n self.ldtvalueundefined.setObjectName('ldtvalueundefined')\n self.ldtvalueundefined.setGeometry(QtCore.QRect(530, 140, 60, 30))\n self.lblvaluefillup = QtWidgets.QLabel(ImportHorionFile)\n self.lblvaluefillup.setObjectName('lblvaluefillup')\n self.lblvaluefillup.setGeometry(QtCore.QRect(420, 180, 100, 30))\n self.ldtvaluefillup = QtWidgets.QLineEdit(ImportHorionFile)\n self.ldtvaluefillup.setObjectName('ldtvaluefillup')\n self.ldtvaluefillup.setGeometry(QtCore.QRect(530, 180, 60, 30))\n self.btnimport = QtWidgets.QPushButton(ImportHorionFile)\n self.btnimport.setObjectName('btnimport')\n self.btnimport.setGeometry(QtCore.QRect(220, 270, 160, 30))\n self.btnimport.setIcon(icon)\n self.msgbox = QtWidgets.QMessageBox(ImportHorionFile)\n self.msgbox.setObjectName('msgbox')\n _center_x = ImportHorionFile.geometry().center().x()\n _center_y = ImportHorionFile.geometry().center().y()\n self.msgbox.setGeometry(QtCore.QRect(_center_x - 150, _center_y - 50, 300, 100))\n self.retranslateGUI(ImportHorionFile)\n QtCore.QMetaObject.connectSlotsByName(ImportHorionFile)\n\n def retranslateGUI(self, ImportHorionFile):\n self.dialog = ImportHorionFile\n _translate = QtCore.QCoreApplication.translate\n ImportHorionFile.setWindowTitle(_translate('ImportHorionFile', 'Import Horizon from File'))\n self.lblfile.setText(_translate('ImportHorionFile', 'Select horizon files:'))\n self.lblfile.setAlignment(QtCore.Qt.AlignCenter)\n self.ldtfile.setText(_translate('ImportHorionFile', os.path.abspath(self.rootpath)))\n self.btnfile.setText(_translate('ImportHorionFile', 'Browse'))\n self.btnfile.clicked.connect(self.clickBtnFile)\n self.lbltype.setText(_translate('ImportHorionFile', '\\t Type:'))\n self.cbbtype.addItems(['Kingdom 3D interpretation lines (ASCII) (*.*)',\n 'Seisworks 3D interpretation (ASCII) (*.*)',\n 'Customized (ASCII) (*.*)'])\n self.cbbtype.currentIndexChanged.connect(self.changeCbbType)\n self.lblpara.setText(_translate('ImportHorionFile', 'Settings:'))\n self.lblinl.setText(_translate('ImportHorionFile', 'Inline column'))\n self.lblinl.setAlignment(QtCore.Qt.AlignRight)\n self.cbbinl.addItems([str(i + 1) for i in range(10)])\n self.cbbinl.setCurrentIndex(2)\n self.cbbinl.setEnabled(False)\n self.lblxl.setText(_translate('ImportHorionFile', 'Crossline column:'))\n self.lblxl.setAlignment(QtCore.Qt.AlignRight)\n self.cbbxl.addItems([str(i + 1) for i in range(10)])\n self.cbbxl.setCurrentIndex(3)\n self.cbbxl.setEnabled(False)\n self.lblz.setText(_translate('ImportHorionFile', 'Time/depth column:'))\n self.lblz.setAlignment(QtCore.Qt.AlignRight)\n self.cbbz.addItems([str(i + 1) for i in range(10)])\n self.cbbz.setCurrentIndex(4)\n self.cbbz.setEnabled(False)\n self.lblcomment.setText(_translate('ImportHorionFile', 'Header with '))\n self.lblcomment.setAlignment(QtCore.Qt.AlignRight)\n self.cbbcomment.addItems(['None', '#', '!'])\n self.cbbcomment.setCurrentIndex(0)\n self.cbbcomment.setEnabled(False)\n self.lbldelimiter.setText(_translate('ImportHorionFile', 'Delimiter: '))\n self.lbldelimiter.setAlignment(QtCore.Qt.AlignRight)\n self.cbbdelimiter.addItems(['Space', 'Comma'])\n self.cbbdelimiter.setCurrentIndex(0)\n self.cbbdelimiter.setEnabled(False)\n self.lblvalueundefined.setText(_translate('ImportHorionFile', 'Undefined value:'))\n self.lblvalueundefined.setAlignment(QtCore.Qt.AlignRight)\n self.ldtvalueundefined.setText(_translate('ImportHorionFile', '-999'))\n self.lblvaluefillup.setText(_translate('ImportHorionFile', 'Filling-up value:'))\n self.lblvaluefillup.setAlignment(QtCore.Qt.AlignRight)\n self.ldtvaluefillup.setText(_translate('ImportHorionFile', 'NaN'))\n self.btnimport.setText(_translate('ImportHorionFile', 'Import Horizon'))\n self.btnimport.clicked.connect(self.clickBtnImportHorionFile)\n\n def clickBtnFile(self):\n _dialog = QtWidgets.QFileDialog()\n _file = _dialog.getOpenFileNames(None, 'Select Horizon File(s)', (self.rootpath), filter='All files (*.*)')\n if len(_file[0]) > 0:\n self.filelist = _file[0]\n self.ldtfile.setText(str(_file[0]))\n\n def changeCbbType(self):\n if self.cbbtype.currentIndex() == 0:\n self.cbbinl.setCurrentIndex(2)\n self.cbbinl.setEnabled(False)\n self.cbbxl.setCurrentIndex(3)\n self.cbbxl.setEnabled(False)\n self.cbbz.setCurrentIndex(4)\n self.cbbz.setEnabled(False)\n self.cbbcomment.setCurrentIndex(0)\n self.cbbcomment.setEnabled(False)\n self.cbbdelimiter.setCurrentIndex(0)\n self.cbbdelimiter.setEnabled(False)\n else:\n if self.cbbtype.currentIndex() == 1:\n self.cbbinl.setCurrentIndex(0)\n self.cbbinl.setEnabled(False)\n self.cbbxl.setCurrentIndex(1)\n self.cbbxl.setEnabled(False)\n self.cbbz.setCurrentIndex(4)\n self.cbbz.setEnabled(False)\n self.cbbcomment.setCurrentIndex(0)\n self.cbbcomment.setEnabled(False)\n self.cbbdelimiter.setCurrentIndex(0)\n self.cbbdelimiter.setEnabled(False)\n if self.cbbtype.currentIndex() == 2:\n self.cbbinl.setCurrentIndex(4)\n self.cbbinl.setEnabled(True)\n self.cbbxl.setCurrentIndex(3)\n self.cbbxl.setEnabled(True)\n self.cbbz.setCurrentIndex(2)\n self.cbbz.setEnabled(True)\n self.cbbcomment.setCurrentIndex(1)\n self.cbbcomment.setEnabled(True)\n self.cbbdelimiter.setCurrentIndex(0)\n self.cbbdelimiter.setEnabled(True)\n\n def clickBtnImportHorionFile(self):\n self.refreshMsgBox()\n _nfile = len(self.filelist)\n if _nfile <= 0:\n vis_msg.print('ERROR in ImportHorizonFile: No file selected for import', type='error')\n QtWidgets.QMessageBox.critical(self.msgbox, 'Import Horizon from File', 'No file selected for import')\n return\n _undefined_value = basic_data.str2float(self.ldtvalueundefined.text())\n if _undefined_value is False:\n vis_msg.print('ERROR in ImportHorizonFile: Non-float undefined value', type='error')\n QtWidgets.QMessageBox.critical(self.msgbox, 'Import Horizon from File', 'Nom-float undefined value')\n return\n _fillup_value = basic_data.str2float(self.ldtvaluefillup.text())\n if _fillup_value is False:\n vis_msg.print('ERROR in ImportHorizonFile: Non-float filled-up value', type='error')\n QtWidgets.QMessageBox.critical(self.msgbox, 'Import Horizon from File', 'Nom-float filled-up value')\n return\n _pgsdlg = QtWidgets.QProgressDialog()\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(os.path.join(self.iconpath, 'icons/point.png')), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n _pgsdlg.setWindowIcon(icon)\n _pgsdlg.setWindowTitle('Import ' + str(_nfile) + ' Horizon files')\n _pgsdlg.setCancelButton(None)\n _pgsdlg.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)\n _pgsdlg.forceShow()\n _pgsdlg.setFixedWidth(400)\n _pgsdlg.setMaximum(_nfile)\n _horizondata = {}\n for i in range(_nfile):\n QtCore.QCoreApplication.instance().processEvents()\n _filename = self.filelist[i]\n print('ImportHorionFile: Import %d of %d horizon files: %s' % (i + 1, _nfile, _filename))\n _comment = None\n if self.cbbcomment.currentIndex() == 0:\n _comment = None\n if self.cbbcomment.currentIndex() == 1:\n _comment = '#'\n if self.cbbcomment.currentIndex() == 2:\n _comment = '!'\n _delimiter = None\n if self.cbbdelimiter.currentIndex() == 1:\n _delimiter = ','\n _filenamemain = os.path.splitext(os.path.basename(_filename))[0]\n _horizondata[_filenamemain] = horizon_io.readHorizonFromAscii(_filename, comment=_comment,\n delimiter=_delimiter,\n inlcol=(self.cbbinl.currentIndex()),\n xlcol=(self.cbbxl.currentIndex()),\n zcol=(self.cbbz.currentIndex()),\n filling_up_value=_fillup_value,\n undefined_value=_undefined_value)\n if 'Z' in _horizondata[_filenamemain]['HorizonData'].keys():\n _z = _horizondata[_filenamemain]['HorizonData']['Z']\n if np.min(_z[(~np.isnan(_z))]) >= 0:\n _horizondata[_filenamemain]['HorizonData']['Z'] *= -1.0\n _pgsdlg.setValue(i + 1)\n\n for key in _horizondata.keys():\n if key in self.horizondata.keys():\n if checkHorizonData(self.horizondata[key]):\n reply = QtWidgets.QMessageBox.question(self.msgbox, 'Import Horizon from File', key + ' already exists. Overwrite?', QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No)\n if reply == QtWidgets.QMessageBox.No:\n return\n self.horizondata[key] = _horizondata[key]\n\n QtWidgets.QMessageBox.information(self.msgbox, 'Import Horizon from File', str(_nfile) + ' file(s) imported successfully')\n\n def refreshMsgBox(self):\n _center_x = self.dialog.geometry().center().x()\n _center_y = self.dialog.geometry().center().y()\n self.msgbox.setGeometry(QtCore.QRect(_center_x - 150, _center_y - 50, 300, 100))\n\n\ndef checkHorizonData(horizon):\n return horizon_ays.checkHorizon(horizon)\n\n\nif __name__ == '__main__':\n app = QtWidgets.QApplication(sys.argv)\n ImportHorionFile = QtWidgets.QWidget()\n gui = importhorizonfile()\n gui.setupGUI(ImportHorionFile)\n ImportHorionFile.show()\n sys.exit(app.exec_())","sub_path":"pycfiles/gaeio-1.0.tar/importhorizonfile.cpython-36.py","file_name":"importhorizonfile.cpython-36.py","file_ext":"py","file_size_in_byte":14565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"545965949","text":"import copy\n\nwith open('input') as f:\n cases = [list(line.rstrip()) for line in f.readlines()]\n\ndef getOccupiedCount(seatMatrix, char=\"#\"):\n return sum([i.count(char) for i in seatMatrix])\n\ndef countVisiblyAdjacent(seatMatrix, i, j):\n visiblyAdjacentSeats, rows, columns = 0, len(seatMatrix), len(seatMatrix[0])\n\n for row_factor in [-1, 0, 1]:\n for column_factor in [-1, 0, 1]:\n if( not (row_factor == column_factor == 0)):\n k, l = i + row_factor, j + column_factor\n\n while ( k >= 0 and l >= 0 and k < rows and l < columns):\n if(seatMatrix[k][l] == \"L\"):\n break\n if(seatMatrix[k][l] == \"#\"):\n visiblyAdjacentSeats += 1\n break\n k += row_factor\n l += column_factor\n\n return visiblyAdjacentSeats\n\ndef performTransformations(seatMatrix, findSymbol, replaceSymbol, isValidAdjacentCount):\n boardCopy = copy.deepcopy(seatMatrix)\n for i in range(0, len(seatMatrix)):\n for j in range(0, len(seatMatrix[i])):\n adjacentSeats = countVisiblyAdjacent(boardCopy, i, j)\n if(boardCopy[i][j] == findSymbol and isValidAdjacentCount(adjacentSeats)):\n seatMatrix[i][j] = replaceSymbol\n\n return getOccupiedCount(seatMatrix) if boardCopy == seatMatrix else 0\n\nwhile True:\n count = performTransformations(cases, 'L', '#', (lambda adjacentSeats: adjacentSeats == 0)) or performTransformations(cases, '#', 'L', (lambda adjacentSeats: adjacentSeats >= 5))\n if(count):\n print(count)\n exit()\n","sub_path":"2020/11/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"477895653","text":"import os\n\nfrom PySide import QtGui\nfrom PySide import QtCore\n\nfrom libs.central_widget import CentralWidget\nfrom libs.statusbar import Statusbar\n\n\nclass Window(QtGui.QMainWindow):\n tab_key_pressed = QtCore.Signal()\n\n def __init__(self, static_dir):\n self._static_dir = static_dir\n\n super(Window, self).__init__()\n\n self._statusbar = Statusbar(self)\n\n self.initUI()\n\n def initUI(self):\n \"\"\"Initialize UI.\"\"\"\n # Central widget\n central_widget = CentralWidget(self)\n self.setCentralWidget(central_widget)\n\n # Status bar\n self._statusbar.show_message(\"Ready\")\n\n # Window\n self.resize(int(os.getenv(\"WINDOW_WIDTH\")), int(os.getenv(\"WINDOW_HEIGHT\")))\n self.center()\n self.setWindowTitle(os.getenv(\"WINDOW_TITLE\"))\n self.setWindowIcon(QtGui.QIcon(os.path.join(self._static_dir, \"images\", os.getenv(\"WINDOW_ICON\"))))\n\n def center(self):\n qr = self.frameGeometry()\n cp = QtGui.QDesktopWidget().availableGeometry().center()\n qr.moveCenter(cp)\n self.move(qr.topLeft())\n\n def keyPressEvent(self, e):\n \"\"\"Handler for keyboard key press event.\"\"\"\n # F12 - Exit\n if e.key() == QtCore.Qt.Key_F12:\n self.close()\n # Tab activate workarea\n elif e.key() == QtCore.Qt.Key_F8:\n self.tab_key_pressed.emit()\n # elif e.key() == QtCore.Qt.Key_Tab:\n # return True\n\n def closeEvent(self, event):\n reply = QtGui.QMessageBox.question(self,\n \"Quit\",\n \"Are you sure to quit?\",\n QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,\n QtGui.QMessageBox.No)\n\n if reply == QtGui.QMessageBox.Yes:\n event.accept()\n else:\n event.ignore()\n","sub_path":"libs/window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":1929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"565709782","text":"# This file is part of QuTiP: Quantum Toolbox in Python.\n#\n# Copyright (c) 2011 and later, The QuTiP Project.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# 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\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names\n# of its contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n###############################################################################\nimport numpy as np\nfrom qutip.lattice import *\nfrom qutip import (Qobj, tensor, basis, qeye, isherm, sigmax)\n# from numpy.testing import (assert_equal, assert_, assert_almost_equal,\n# run_module_suite)\nfrom numpy.testing import (assert_, run_module_suite)\n\n\nclass TestLattice:\n \"\"\"\n Tests for `qutip.lattice` class.\n \"\"\"\n def test_hamiltonian(self):\n \"\"\"\n lattice: Test the method Lattice1d.Hamiltonian().\n \"\"\"\n # num_cell = 1\n # Four different instances\n Periodic_Atom_Chain = Lattice1d(num_cell=1, boundary=\"periodic\")\n Aperiodic_Atom_Chain = Lattice1d(num_cell=1, boundary=\"aperiodic\")\n p_1223 = Lattice1d(num_cell=1, boundary=\"periodic\",\n cell_num_site=2, cell_site_dof=[2, 3])\n ap_1223 = Lattice1d(num_cell=1, boundary=\"aperiodic\",\n cell_num_site=2, cell_site_dof=[2, 3])\n\n # Their Hamiltonians\n pHamt1 = Periodic_Atom_Chain.Hamiltonian()\n apHamt1 = Aperiodic_Atom_Chain.Hamiltonian()\n pHamt1223 = p_1223.Hamiltonian()\n apHamt1223 = ap_1223.Hamiltonian()\n\n # Benchmark answers\n pHamt1_C = Qobj([[0.]], dims=[[1], [1]])\n apHamt1_C = Qobj([[0.]], dims=[[1], [1]])\n site1223 = np.diag(np.zeros(2-1)-1, 1) + np.diag(np.zeros(2-1)-1, -1)\n Rpap1223 = tensor(Qobj(site1223), qeye([2, 3]))\n pap1223 = Qobj(Rpap1223, dims=[[2, 2, 3], [2, 2, 3]])\n\n # Checks for num_cell = 1\n assert_(pHamt1 == pHamt1_C)\n assert_(apHamt1 == apHamt1_C)\n assert_(pHamt1223 == pap1223) # for num_cell=1, periodic and\n assert_(apHamt1223 == pap1223) # aperiodic B.C. have same Hamiltonian\n\n # num_cell = 2\n # Four different instances\n Periodic_Atom_Chain = Lattice1d(num_cell=2, boundary=\"periodic\")\n Aperiodic_Atom_Chain = Lattice1d(num_cell=2, boundary=\"aperiodic\")\n\n p_2222 = Lattice1d(num_cell=2, boundary=\"periodic\",\n cell_num_site=2, cell_site_dof=[2, 2])\n ap_2222 = Lattice1d(num_cell=2, boundary=\"aperiodic\",\n cell_num_site=2, cell_site_dof=[2, 2])\n\n # Their Hamiltonians\n pHamt2222 = p_2222.Hamiltonian()\n apHamt2222 = ap_2222.Hamiltonian()\n pHamt2 = Periodic_Atom_Chain.Hamiltonian()\n apHamt2 = Aperiodic_Atom_Chain.Hamiltonian()\n\n # Benchmark answers\n pHamt2_C = Qobj([[0., -1.],\n [-1., 0.]], dims=[[2], [2]])\n apHamt2_C = Qobj([[0., -1.],\n [-1., 0.]], dims=[[2], [2]])\n\n pap_2222 = np.zeros((16, 16), dtype=complex)\n pap_2222[0:4, 4:8] = -np.eye(4)\n pap_2222[4:8, 0:4] = -np.eye(4)\n pap_2222[4:8, 8:12] = -np.eye(4)\n pap_2222[8:12, 4:8] = -np.eye(4)\n pap_2222[8:12, 12:16] = -np.eye(4)\n pap_2222[12:16, 8:12] = -np.eye(4)\n pap_2222 = Qobj(pap_2222, dims=[[2, 2, 2, 2], [2, 2, 2, 2]])\n\n # Checks for num_cell = 2\n assert_(pHamt2 == pHamt2_C)\n assert_(apHamt2 == apHamt2_C)\n assert_(pHamt2222 == pap_2222) # for num_cell=2, periodic and\n assert_(apHamt2222 == pap_2222) # aperiodic B.C. have same Hamiltonian\n\n # num_cell = 3 # checking any num_cell >= 3 is pretty much equivalent\n Periodic_Atom_Chain = Lattice1d(num_cell=3, boundary=\"periodic\")\n Aperiodic_Atom_Chain = Lattice1d(num_cell=3, boundary=\"aperiodic\")\n p_3122 = Lattice1d(num_cell=3, boundary=\"periodic\",\n cell_num_site=1, cell_site_dof=[2, 2])\n ap_3122 = Lattice1d(num_cell=3, boundary=\"aperiodic\",\n cell_num_site=1, cell_site_dof=[2, 2])\n\n # Their Hamiltonians\n pHamt3 = Periodic_Atom_Chain.Hamiltonian()\n apHamt3 = Aperiodic_Atom_Chain.Hamiltonian()\n pHamt3122 = p_3122.Hamiltonian()\n apHamt3122 = ap_3122.Hamiltonian()\n\n # Benchmark answers\n pHamt3_C = Qobj([[0., -1., -1.],\n [-1., 0., -1.],\n [-1., -1., 0.]], dims=[[3], [3]])\n apHamt3_C = Qobj([[0., -1., 0.],\n [-1., 0., -1.],\n [0., -1., 0.]], dims=[[3], [3]])\n\n Hp_3122 = np.zeros((12, 12), dtype=complex)\n Hp_3122[0:8, 4:12] = Hp_3122[0:8, 4:12] - np.eye(8)\n Hp_3122[4:12, 0:8] = Hp_3122[4:12, 0:8] - np.eye(8)\n Hp_3122[0:4, 8:12] = Hp_3122[0:4, 8:12] - np.eye(4)\n Hp_3122[8:12, 0:4] = Hp_3122[8:12, 0:4] - np.eye(4)\n Hp_3122 = Qobj(Hp_3122, dims=[[3, 2, 2], [3, 2, 2]])\n\n Hap_3122 = np.zeros((12, 12), dtype=complex)\n Hap_3122[0:8, 4:12] = Hap_3122[0:8, 4:12] - np.eye(8)\n Hap_3122[4:12, 0:8] = Hap_3122[4:12, 0:8] - np.eye(8)\n Hap_3122 = Qobj(Hap_3122, dims=[[3, 2, 2], [3, 2, 2]])\n\n # Checks for num_cell = 3\n assert_(pHamt3 == pHamt3_C)\n assert_(apHamt3 == apHamt3_C)\n assert_(pHamt3122 == Hp_3122)\n assert_(apHamt3122 == Hap_3122)\n\n def test_cell_structures(self):\n \"\"\"\n lattice: Test the method Lattice1d.cell_structures().\n \"\"\"\n val_s = ['site0', 'site1']\n val_t = [' orb0', 'orb1']\n (H_cell_form, inter_cell_T_form, H_cell,\n inter_cell_T) = cell_structures(val_s, val_t)\n c_H_form = [['',\n '',\n '',\n ''],\n ['',\n '',\n '',\n ''],\n ['',\n '',\n '',\n ''],\n ['',\n '',\n '',\n '']]\n\n i_cell_T_form = [['',\n '',\n '',\n ''],\n ['',\n '',\n '',\n ''],\n ['',\n '',\n '',\n ''],\n ['',\n '',\n '',\n '']]\n c_H = np.zeros((4, 4), dtype=complex)\n i_cell_T = np.zeros((4, 4), dtype=complex)\n assert_(H_cell_form == c_H_form)\n assert_(inter_cell_T_form == i_cell_T_form)\n assert_((H_cell == c_H).all())\n assert_((inter_cell_T == i_cell_T).all())\n\n def test_basis(self):\n \"\"\"\n lattice: Test the method Lattice1d.basis().\n \"\"\"\n lattice_3242 = Lattice1d(num_cell=3, boundary=\"periodic\",\n cell_num_site=2, cell_site_dof=[4, 2])\n psi0 = lattice_3242.basis(1, 0, [2, 1])\n psi0dag_a = np.zeros((1, 48), dtype=complex)\n psi0dag_a[0, 21] = 1\n psi0dag = Qobj(psi0dag_a, dims=[[1, 1, 1, 1], [3, 2, 4, 2]])\n assert_(psi0 == psi0dag.dag())\n\n def test_distribute_operator(self):\n \"\"\"\n lattice: Test the method Lattice1d.distribute_operator().\n \"\"\"\n lattice_412 = Lattice1d(num_cell=4, boundary=\"periodic\",\n cell_num_site=1, cell_site_dof=[2])\n op = Qobj(np.array([[0, 1], [1, 0]]))\n op_all = lattice_412.distribute_operator(op)\n sv_op_all = tensor(qeye(4), sigmax())\n assert_(op_all == sv_op_all)\n\n def test_operator_at_cells(self):\n \"\"\"\n lattice: Test the method Lattice1d.operator_between_cells().\n \"\"\"\n p_2222 = Lattice1d(num_cell=2, boundary=\"periodic\",\n cell_num_site=2, cell_site_dof=[2, 2])\n op_0 = basis(2, 0) * basis(2, 1).dag()\n op_c = tensor(op_0, qeye([2, 2]))\n OP = p_2222.operator_between_cells(op_c, 1, 0)\n T = basis(2, 1) * basis(2, 0).dag()\n QP = tensor(T, op_c)\n assert_(OP == QP)\n\n def test_operator_between_cells(self):\n \"\"\"\n lattice: Test the method Lattice1d.operator_at_cells().\n \"\"\"\n lattice_412 = Lattice1d(num_cell=4, boundary=\"periodic\",\n cell_num_site=1, cell_site_dof=[2])\n op = Qobj(np.array([[0, 1], [1, 0]]))\n op_sp = lattice_412.operator_at_cells(op, cells=[1, 2])\n\n aop_sp = np.zeros((8, 8), dtype=complex)\n aop_sp[2:4, 2:4] = sigmax()\n aop_sp[4:6, 4:6] = sigmax()\n sv_op_sp = Qobj(aop_sp, dims=[[4, 2], [4, 2]])\n assert_(op_sp == sv_op_sp)\n\n def test_x(self):\n \"\"\"\n lattice: Test the method Lattice1d.x().\n \"\"\"\n lattice_3223 = Lattice1d(num_cell=3, boundary=\"periodic\",\n cell_num_site=2, cell_site_dof=[2, 3])\n R = lattice_3223.x()\n npR = R.full()\n # count the number of off-diagonal elements n_off which should be 0\n n_off = np.count_nonzero(npR - np.diag(np.diagonal(npR)))\n assert_(n_off == 0)\n assert_((np.diag(R) == np.kron(range(3), np.ones(12))).all())\n\n def test_k(self):\n \"\"\"\n lattice: Test the method Lattice1d.k().\n \"\"\"\n L = 7\n lattice_L123 = Lattice1d(num_cell=L, boundary=\"periodic\",\n cell_num_site=1, cell_site_dof=[2, 3])\n kq = lattice_L123.k()\n kop = np.zeros((L, L), dtype=complex)\n for row in range(L):\n for col in range(L):\n if row == col:\n kop[row, col] = (L-1)/2\n else:\n kop[row, col] = 1 / (np.exp(2j * np.pi * (row - col)/L)-1)\n\n kt = np.kron(kop * 2 * np.pi / L, np.eye(6))\n dim_H = [[2, 2, 3], [2, 2, 3]]\n kt = Qobj(kt, dims=dim_H)\n\n [k_q, Vq] = kq.eigenstates()\n [k_t, Vt] = kt.eigenstates()\n k_tC = k_t - 2*np.pi/L*((L-1)//2)\n # k_ts = [(i-(L-1)//2)*2*np.pi/L for i in range(L)]\n # k_w = np.kron((np.array(k_ts)).T, np.ones((1,6)))\n assert_((np.abs(k_tC - k_q) < 1E-13).all())\n\n def test_get_dispersion(self):\n \"\"\"\n lattice: Test the method Lattice1d.get_dispersion().\n \"\"\"\n Periodic_Atom_Chain = Lattice1d(num_cell=8, boundary=\"periodic\")\n [knxA, val_kns] = Periodic_Atom_Chain.get_dispersion()\n kB = np.array([[-3.14159265],\n [-2.35619449],\n [-1.57079633],\n [-0.78539816],\n [0.],\n [0.78539816],\n [1.57079633],\n [2.35619449]])\n valB = np.array([[2., 1.41421356, 0., -1.41421356, -2.,\n -1.41421356, 0., 1.41421356]])\n assert_(np.max(abs(knxA-kB)) < 1.0E-6)\n assert_(np.max(abs(val_kns-valB)) < 1.0E-6)\n\n # SSH model with num_cell = 4 and two orbitals, two spins\n # cell_site_dof = [2,2]\n t_intra = -0.5\n t_inter = -0.6\n H_cell = tensor(\n Qobj(np.array([[0, t_intra], [t_intra, 0]])), qeye([2, 2]))\n inter_cell_T = tensor(\n Qobj(np.array([[0, 0], [t_inter, 0]])), qeye([2, 2]))\n\n SSH_comp = Lattice1d(num_cell=6, boundary=\"periodic\",\n cell_num_site=2, cell_site_dof=[2, 2],\n Hamiltonian_of_cell=H_cell, inter_hop=inter_cell_T)\n [kScomp, vcomp] = SSH_comp.get_dispersion()\n kS = np.array([[-3.14159265],\n [-2.0943951],\n [-1.04719755],\n [0.],\n [1.04719755],\n [2.0943951]])\n Oband = np.array([-0.1, -0.55677644, -0.9539392, -1.1,\n -0.9539392, -0.55677644])\n vS = np.array([Oband, Oband, Oband, Oband, -Oband, -Oband, -Oband,\n -Oband])\n assert_(np.max(abs(kScomp-kS)) < 1.0E-6)\n assert_(np.max(abs(vcomp-vS)) < 1.0E-6)\n\n def test_cell_periodic_parts(self):\n \"\"\"\n lattice: Test the method Lattice1d.array_of_unk().\n \"\"\"\n # Coupled Resonator Optical Waveguide(CROW) Example(PhysRevB.99.224201)\n J = 2\n eta = np.pi/4\n H_cell = Qobj(np.array([[0, J*np.sin(eta)], [J*np.sin(eta), 0]]))\n inter_cell_T0 = (J/2) * Qobj(np.array(\n [[np.exp(eta * 1j), 0], [0, np.exp(-eta*1j)]]))\n inter_cell_T1 = (J/2) * Qobj(np.array([[0, 1], [1, 0]]))\n\n inter_cell_T = [inter_cell_T0, inter_cell_T1]\n\n CROW_lattice = Lattice1d(num_cell=4, boundary=\"periodic\",\n cell_num_site=1, cell_site_dof=[2],\n Hamiltonian_of_cell=H_cell,\n inter_hop=inter_cell_T)\n (kxA, val_kns) = CROW_lattice.get_dispersion()\n (knxA, vec_kns) = CROW_lattice.cell_periodic_parts()\n (knxA, qH_ks) = CROW_lattice.bulk_Hamiltonians()\n for i in range(4):\n for j in range(2):\n if val_kns[j][i] == 0:\n E_V = Qobj(vec_kns[i, j, :])\n eE_V = qH_ks[i] * E_V\n assert_(np.max(abs(eE_V)) < 1.0E-12)\n else:\n E_V = Qobj(vec_kns[i, j, :])\n eE_V = qH_ks[i] * E_V\n qE_V = np.divide(eE_V, E_V)\n oE = val_kns[j][i] * np.ones((2, 1))\n assert_(np.max(abs(oE-qE_V)) < 1.0E-12)\n\n def test_bulk_Hamiltonians(self):\n \"\"\"\n lattice: Test the method Lattice1d.bulk_Hamiltonian_array().\n \"\"\"\n # Coupled Resonator Optical Waveguide(CROW) Example(PhysRevB.99.224201)\n J = 2\n eta = np.pi/2\n H_cell = Qobj(np.array([[0, J*np.sin(eta)], [J*np.sin(eta), 0]]))\n inter_cell_T0 = (J/2)*Qobj(np.array([[np.exp(eta * 1j), 0],\n [0, np.exp(-eta*1j)]]))\n inter_cell_T1 = (J/2)*Qobj(np.array([[0, 1], [1, 0]]))\n inter_cell_T = [inter_cell_T0, inter_cell_T1]\n\n CROW_lattice = Lattice1d(num_cell=4, boundary=\"periodic\",\n cell_num_site=1, cell_site_dof=[2],\n Hamiltonian_of_cell=H_cell,\n inter_hop=inter_cell_T)\n (knxA, qH_ks) = CROW_lattice.bulk_Hamiltonians()\n Hk0 = np.array([[0.+0.j, 0.+0.j],\n [0.+0.j, 0.+0.j]])\n Hk1 = np.array([[2.+0.j, 2.+0.j],\n [2.+0.j, -2.+0.j]])\n Hk2 = np.array([[0.+0.j, 4.+0.j],\n [4.+0.j, 0.+0.j]])\n Hk3 = np.array([[-2.+0.j, 2.+0.j],\n [2.+0.j, 2.+0.j]])\n qHks = np.array([None for i in range(4)])\n qHks[0] = Qobj(Hk0)\n qHks[1] = Qobj(Hk1)\n qHks[2] = Qobj(Hk2)\n qHks[3] = Qobj(Hk3)\n for i in range(4):\n np.testing.assert_array_almost_equal(qH_ks[i], qHks[i], decimal=8)\n\n def test_bloch_wave_functions(self):\n \"\"\"\n lattice: Test the method Lattice1d.bloch_wave_functions().\n \"\"\"\n # Coupled Resonator Optical Waveguide(CROW) Example(PhysRevB.99.224201)\n J = 2\n eta = np.pi/2\n H_cell = Qobj(np.array([[0, J*np.sin(eta)], [J*np.sin(eta), 0]]))\n inter_cell_T0 = (J/2)*Qobj(np.array([[np.exp(eta * 1j), 0], [0,\n np.exp(-eta*1j)]]))\n inter_cell_T1 = (J/2)*Qobj(np.array([[0, 1], [1, 0]]))\n\n inter_cell_T = [inter_cell_T0, inter_cell_T1]\n\n CROW_lattice = Lattice1d(num_cell=4, boundary=\"periodic\",\n cell_num_site=1, cell_site_dof=[2],\n Hamiltonian_of_cell=H_cell,\n inter_hop=inter_cell_T)\n CROW_Haml = CROW_lattice.Hamiltonian()\n\n H_CROW = Qobj(np.array([[0.+0.j, 2.+0.j, 0.+1.j, 1.+0.j, 0.+0.j, 0.+0.j, 0.-1.j, 1.+0.j],\n [2.+0.j, 0.+0.j, 1.+0.j, 0.-1.j, 0.+0.j, 0.+0.j, 1.+0.j, 0.+1.j],\n [0.-1.j, 1.+0.j, 0.+0.j, 2.+0.j, 0.+1.j, 1.+0.j, 0.+0.j, 0.+0.j],\n [1.+0.j, 0.+1.j, 2.+0.j, 0.+0.j, 1.+0.j, 0.-1.j, 0.+0.j, 0.+0.j],\n [0.+0.j, 0.+0.j, 0.-1.j, 1.+0.j, 0.+0.j, 2.+0.j, 0.+1.j, 1.+0.j],\n [0.+0.j, 0.+0.j, 1.+0.j, 0.+1.j, 2.+0.j, 0.+0.j, 1.+0.j, 0.-1.j],\n [0.+1.j, 1.+0.j, 0.+0.j, 0.+0.j, 0.-1.j, 1.+0.j, 0.+0.j, 2.+0.j],\n [1.+0.j, 0.-1.j, 0.+0.j, 0.+0.j, 1.+0.j, 0.+1.j, 2.+0.j, 0.+0.j]]),\n dims=[[4, 2], [4, 2]])\n # Check for CROW with num_cell = 4\n assert_(np.max(abs(CROW_Haml-H_CROW)) < 1.0E-6) # 1.0E-8 worked too\n eigen_states = CROW_lattice.bloch_wave_functions()\n for i in range(8):\n if eigen_states[i][0] == 0:\n E_V = eigen_states[i][1]\n eE_V = CROW_Haml * E_V\n assert_(np.max(abs(eE_V)) < 1.0E-10)\n else:\n E_V = eigen_states[i][1]\n eE_V = CROW_Haml * E_V\n qE_V = np.divide(eE_V, E_V)\n oE = eigen_states[i][0] * np.ones((8, 1))\n assert_(np.max(abs(oE-qE_V)) < 1.0E-10)\n\n def test_CROW(self):\n \"\"\"\n lattice: Test the methods of Lattice1d in a CROW model.\n \"\"\"\n # Coupled Resonator Optical Waveguide(CROW) Example(PhysRevB.99.224201)\n J = 2\n eta = np.pi/4\n H_cell = Qobj(np.array([[0, J * np.sin(eta)], [J * np.sin(eta), 0]]))\n inter_cell_T0 = (J/2)*Qobj(np.array([[np.exp(eta * 1j), 0],\n [0, np.exp(-eta*1j)]]))\n inter_cell_T1 = (J/2)*Qobj(np.array([[0, 1], [1, 0]]))\n\n inter_cell_T = [inter_cell_T0, inter_cell_T1]\n\n CROW_lattice = Lattice1d(num_cell=4, boundary=\"periodic\",\n cell_num_site=1, cell_site_dof=[2],\n Hamiltonian_of_cell=H_cell,\n inter_hop=inter_cell_T)\n CROW_Haml = CROW_lattice.Hamiltonian()\n\n # Benchmark answers\n H_CROW = Qobj([[0.+0.j, 1.41421356+0.j, 0.70710678+0.70710678j, 1.+0.j,\n 0.+0.j, 0.+0.j, 0.70710678-0.70710678j, 1.+0.j],\n [1.41421356+0.j, 0.+0.j, 1.+0.j, 0.70710678-0.70710678j,\n 0.+0.j, 0.+0.j, 1.+0.j, 0.70710678+0.70710678j],\n [0.70710678-0.70710678j, 1.+0.j, 0.+0.j, 1.41421356+0.j,\n 0.70710678+0.70710678j, 1.+0.j, 0.+0.j, 0.+0.j],\n [1.+0.j, 0.70710678+0.70710678j, 1.41421356+0.j, 0.+0.j,\n 1.+0.j, 0.70710678-0.70710678j, 0.+0.j, 0.+0.j],\n [0.+0.j, 0.+0.j, 0.70710678-0.70710678j, 1.+0.j,\n 0.+0.j, 1.41421356+0.j, 0.70710678+0.70710678j, 1.+0.j],\n [0.+0.j, 0.+0.j, 1.+0.j, 0.70710678+0.70710678j,\n 1.41421356+0.j, 0.+0.j, 1.+0.j, 0.70710678-0.70710678j],\n [0.70710678+0.70710678j, 1.+0.j, 0.+0.j, 0.+0.j,\n 0.70710678-0.70710678j, 1.+0.j, 0.+0.j, 1.41421356+0.j],\n [1.+0.j, 0.70710678-0.70710678j, 0.+0.j, 0.+0.j,\n 1.+0.j, 0.70710678+0.70710678j, 1.41421356+0.j, 0.+0.j]],\n dims=[[4, 2], [4, 2]])\n\n # Check for CROW with num_cell = 4\n assert_(np.max(abs(CROW_Haml-H_CROW)) < 1.0E-6) # 1.0E-8 worked too\n\n (kxA, val_kns) = CROW_lattice.get_dispersion()\n kCR = np.array([[-3.14159265],\n [-1.57079633],\n [0.],\n [1.57079633]])\n vCR = np.array([[-2. , -2. , -2. , -2.],\n [-0.82842712, 2. , 4.82842712 , 2.]])\n assert_(np.max(abs(kxA-kCR)) < 1.0E-6)\n assert_(np.max(abs(val_kns-vCR)) < 1.0E-6)\n\n eigen_states = CROW_lattice.bloch_wave_functions()\n for i in range(8):\n E_V = eigen_states[i][1]\n eE_V = CROW_Haml * E_V\n qE_V = np.divide(eE_V, E_V)\n oE = eigen_states[i][0] * np.ones((8, 1))\n assert_(np.max(abs(oE-qE_V)) < 1.0E-10)\n (knxA, qH_ks) = CROW_lattice.bulk_Hamiltonians()\n (knxA, vec_kns) = CROW_lattice.cell_periodic_parts()\n\n Hk0 = np.array([[-1.41421356+0.j, -0.58578644+0.j],\n [-0.58578644+0.j, -1.41421356+0.j]])\n Hk1 = np.array([[1.41421356+0.j, 1.41421356+0.j],\n [1.41421356+0.j, -1.41421356+0.j]])\n Hk2 = np.array([[1.41421356+0.j, 3.41421356+0.j],\n [3.41421356+0.j, 1.41421356+0.j]])\n Hk3 = np.array([[-1.41421356+0.j, 1.41421356+0.j],\n [1.41421356+0.j, 1.41421356+0.j]])\n qHks = np.array([None for i in range(4)])\n qHks[0] = Qobj(Hk0)\n qHks[1] = Qobj(Hk1)\n qHks[2] = Qobj(Hk2)\n qHks[3] = Qobj(Hk3)\n for i in range(4):\n np.testing.assert_array_almost_equal(qH_ks[i], qHks[i], decimal=8)\n for i in range(4):\n for j in range(2):\n E_V = Qobj(vec_kns[i, j, :])\n eE_V = qH_ks[i] * E_V\n qE_V = np.divide(eE_V, E_V)\n oE = val_kns[j][i]*np.ones((2, 1))\n assert_(np.max(abs(oE-qE_V)) < 1.0E-12)\n\n # A test on CROW lattice dispersion with a random number of cells and\n # random values of eta\n J = 1\n num_cell = np.random.randint(2, 60)\n eta = 2*np.pi*np.random.random()\n\n H_cell = Qobj(np.array([[0, J * np.sin(eta)], [J * np.sin(eta), 0]]))\n inter_cell_T0 = (J/2) * Qobj(np.array([[np.exp(eta * 1j), 0],\n [0, np.exp(-eta*1j)]]))\n inter_cell_T1 = (J/2) * Qobj(np.array([[0, 1], [1, 0]]))\n inter_cell_T = [inter_cell_T0, inter_cell_T1]\n\n CROW_Random = Lattice1d(num_cell=num_cell, boundary=\"periodic\",\n cell_num_site=1, cell_site_dof=[2],\n Hamiltonian_of_cell=H_cell,\n inter_hop=inter_cell_T)\n a = 1 # The unit cell length is always considered 1\n kn_start = 0\n kn_end = 2*np.pi/a\n Ana_val_kns = np.zeros((2, num_cell), dtype=float)\n knxA = np.zeros((num_cell, 1), dtype=float)\n\n for ks in range(num_cell):\n knx = kn_start + (ks*(kn_end-kn_start)/num_cell)\n if knx >= np.pi:\n knxA[ks, 0] = knx - 2 * np.pi\n else:\n knxA[ks, 0] = knx\n knxA = np.roll(knxA, np.floor_divide(num_cell, 2))\n\n for ks in range(num_cell):\n knx = knxA[ks, 0]\n # Ana_val_kns are the analytical bands\n val0 = np.cos(knx) * np.cos(eta) + np.sqrt(2 * np.sin(eta) ** 2\n + (np.cos(knx) * np.cos(eta)) ** 2\n + 2 * np.sin(eta) * np.cos(knx))\n val1 = np.cos(knx) * np.cos(eta) - np.sqrt(2 * np.sin(eta) ** 2\n + (np.cos(knx) * np.cos(eta)) ** 2\n + 2 * np.sin(eta) * np.cos(knx))\n vals = [val0, val1]\n Ana_val_kns[0, ks] = np.min(vals)\n Ana_val_kns[1, ks] = np.max(vals)\n\n (kxA, val_kns) = CROW_Random.get_dispersion()\n assert_(np.max(abs(kxA-knxA)) < 1.0E-8)\n assert_(np.max(abs(val_kns-Ana_val_kns)) < 1.0E-8)\n\n def test_SSH(self):\n \"\"\"\n lattice: Test the methods of Lattice1d in a SSH model.\n \"\"\"\n # SSH model with num_cell = 4 and two orbitals, two spins\n # cell_site_dof = [2,2]\n t_intra = -0.5\n t_inter = -0.6\n H_cell = Qobj(np.array([[0, t_intra], [t_intra, 0]]))\n inter_cell_T = Qobj(np.array([[0, 0], [t_inter, 0]]))\n\n SSH_lattice = Lattice1d(num_cell=5, boundary=\"periodic\",\n cell_num_site=2, cell_site_dof=[1],\n Hamiltonian_of_cell=H_cell,\n inter_hop=inter_cell_T) \n Ham_Sc = SSH_lattice.Hamiltonian()\n\n Hin = Qobj([[0, -0.5], [-0.5, 0]])\n Ht = Qobj([[0, 0], [-0.6, 0]])\n D = qeye(5)\n T = np.diag(np.zeros(4)+1, 1)\n Tdag = np.diag(np.zeros(4)+1, -1)\n Tdag[0][4] = 1\n T[4][0] = 1\n T = Qobj(T)\n Tdag = Qobj(Tdag)\n H_Sc = tensor(D, Hin) + tensor(T, Ht) + tensor(Tdag, Ht.dag())\n # check for SSH model with num_cell = 5 \n assert_(Ham_Sc == H_Sc)\n\n (kxA,val_ks) = SSH_lattice.get_dispersion()\n kSSH = np.array([[-2.51327412],\n [-1.25663706],\n [ 0. ],\n [ 1.25663706],\n [ 2.51327412]])\n vSSH = np.array([[-0.35297281, -0.89185772, -1.1, -0.89185772, -0.35297281],\n [ 0.35297281, 0.89185772, 1.1, 0.89185772, 0.35297281]])\n assert_(np.max(abs(kxA-kSSH)) < 1.0E-6)\n assert_(np.max(abs(val_ks-vSSH)) < 1.0E-6)\n\n # A test on SSH lattice dispersion with a random number of cells and\n # random values of t_inter and t_intra\n num_cell = np.random.randint(2, 60)\n t_intra = -np.random.random()\n t_inter = -np.random.random()\n H_cell = Qobj(np.array([[0, t_intra], [t_intra, 0]]))\n inter_cell_T = Qobj(np.array([[0, 0], [t_inter, 0]]))\n SSH_Random = Lattice1d(num_cell=num_cell, boundary=\"periodic\",\n cell_num_site=2, cell_site_dof=[1],\n Hamiltonian_of_cell=H_cell,\n inter_hop=inter_cell_T)\n a = 1 # The unit cell length is always considered 1\n kn_start = 0\n kn_end = 2*np.pi/a\n Ana_val_kns = np.zeros((2, num_cell), dtype=float)\n knxA = np.zeros((num_cell, 1), dtype=float)\n\n for ks in range(num_cell):\n knx = kn_start + (ks * (kn_end-kn_start)/num_cell)\n if knx >= np.pi:\n knxA[ks, 0] = knx - 2 * np.pi\n else:\n knxA[ks, 0] = knx\n knxA = np.roll(knxA, np.floor_divide(num_cell, 2))\n\n for ks in range(num_cell):\n knx = knxA[ks, 0]\n # Ana_val_kns are the analytical bands\n Ana_val_kns[0, ks] = -np.sqrt(t_intra ** 2 + t_inter ** 2\n + 2 * t_intra * t_inter * np.cos(knx))\n Ana_val_kns[1, ks] = np.sqrt(t_intra ** 2 + t_inter ** 2\n + 2 * t_intra * t_inter * np.cos(knx))\n (kxA, val_kns) = SSH_Random.get_dispersion()\n assert_(np.max(abs(val_kns-Ana_val_kns)) < 1.0E-13)\n\nif __name__ == \"__main__\":\n run_module_suite()\n","sub_path":"qutip/tests/test_lattice.py","file_name":"test_lattice.py","file_ext":"py","file_size_in_byte":29484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"611545164","text":"'''PlayerSkeletonA.py\nThe beginnings of an agent that might someday play Baroque Chess.\n\n'''\n\nimport BC_state_etc as BC\nimport piece_movement as PM\nimport winTester as WT\nfrom random import randint\nimport zobrist as Z\n\nWHITE_PIECES = 0\nBLACK_PIECES = 0\nNORTH = 0; SOUTH = 1; WEST = 2; EAST = 3; NW = 4; NE = 5; SW = 6; SE = 7\nDIRECTIONS = [(-1,0), (1, 0), (0, -1), (0, 1), (-1, -1), (-1, 1), (1, -1), (1, 1)]\nPIECES = {0:'-',2:'p',3:'P',4:'c',5:'C',6:'l',7:'L',8:'i',9:'I',\n 10:'w',11:'W',12:'k',13:'K',14:'f',15:'F'}\nALPHA_BETA_CUTOFFS = 0\nSTATES_EXPANDED = 0\nSTATIC_EVALS_PERFORMED = 0\n\nZOBRIST_INDEXES = {'p':0, 'P':1, 'c':2, 'C':3, 'l':4, 'L':5, 'i':6, 'I':7,\n 'w':8, 'W':9, 'k':10, 'K':11, 'f':12, 'F':13, }\nZOBRIST_NUMBERS = []\nZHASH = None\n\nTRANSPOSITION_TABLE = []\nTABLE_SIZE = 0\n\nclass Hash_Entry:\n def __init__(self, key, eval=None, type=None, ply=None, best_move=None):\n self.key = key\n self.eval = eval\n self.type = type\n self.ply = ply\n self.best_move = best_move\n\ndef makeMove(currentState, currentRemark, timelimit):\n global ALPHA_BETA_CUTOFFS\n ALPHA_BETA_CUTOFFS = 0\n # Compute the new state for a move.\n # This is a placeholder that just copies the current state.\n hash = Z.zhash(currentState.board)\n #print(hash)\n current_state = BC.BC_state(currentState.board, currentState.whose_move, hash)\n #print(current_state.hash)\n newState = BC.BC_state(currentState.board)\n\n board = newState.board\n # Fix up whose turn it will be.\n newState.whose_move = 1 - currentState.whose_move\n\n # Construct a representation of the move that goes from the\n # currentState to the newState.\n # Here is a placeholder in the right format but with made-up\n # numbers:\n score, move = iterative_deepening_alpha_beta(current_state, current_state.whose_move, 3)\n new_state = PM.move(move[0], move[1], current_state, move[2])\n #print(move)\n move = move[0:2]\n #print(score)\n #print(newState)\n # Make up a new remark\n newRemark = \"I'll think harder in some future game. Here's my move\"\n print(ALPHA_BETA_CUTOFFS)\n print(score)\n print(STATES_EXPANDED)\n print(STATIC_EVALS_PERFORMED)\n return [[move, new_state], newRemark]\n\ndef nickname():\n return \"Newman\"\n\ndef introduce():\n return \"I'm Newman Barry, a newbie Baroque Chess agent.\"\n\ndef prepare(player2Nickname):\n global ZOBRIST_NUMBERS; global TRANSPOSITION_TABLE; global TABLE_SIZE\n print(\"hello\")\n TRANPOSITION_TABLE = [None] * 1000000\n TABLE_SIZE = len(TRANSPOSITION_TABLE)\n Z.init_zhash()\n print(\"ok\")\n pass\n\n\ndef iterative_deepening_alpha_beta(state, whoseMove, ply):\n alpha = -100000\n beta = 100000\n best_move = None\n for i in range(1, ply):\n score, move = minimax(state, whoseMove, i, alpha, beta)\n if whoseMove == 1:\n if score > alpha:\n alpha = score\n best_move = move\n else:\n if score < beta:\n beta = score\n best_move = move\n #whoseMove = best_move.whose_move\n return score, best_move\n\ndef minimax(state, whoseMove, plyLeft, alpha, beta):\n global ALPHA_BETA_CUTOFFS; global STATES_EXPANDED\n\n # if plyLeft == 0 or if the state results in a win return its evaluation\n if plyLeft == 0 or WT.winTester(state) != \"No win\":\n return (static_eval(state), state)\n\n # check hashtable for state information and see if the agent can return stored values instead of searching\n index = state.hash % TABLE_LENGTH\n hash_entry = ZHASH_TABLE[index]\n if hash_entry != None and hash_entry.key == state.hash and hash_entry.ply >= plyLeft:\n if hash_entry.type == 'Exact':\n return hash_entry.eval, hash_entry.best_move\n if hash_entry.type == 'Beta Eval':\n if hash_entry.eval >= beta:\n return hash_entry.eval, hash_entry.best_move\n if hash_entry.type == 'Alpha Eval':\n if hash_entry.eval <= alpha:\n return hash_entry.eval, hash_entry.best_move\n\n if plyLeft > 1:\n ZHASH_TABLE[index] = hash_entry(state.hash)\n # recursively go through the successor states\n best_move = None\n for move in successors(state, whoseMove):\n STATES_EXPANDED += 1\n s = PM.move(move[0], move[1], state, move[2])\n new_value, newS = minimax(s, s.whose_move, plyLeft - 1, alpha, beta)\n if (whoseMove == 1 and new_value > alpha) \\\n or (whoseMove == 0 and new_value < beta):\n if whoseMove == 1:\n alpha = newVal\n is_exact = True\n else:\n is_exact = True\n beta = newVal\n best_move = move\n\n # prune off remaining children as the best move has already been found\n if beta <= alpha:\n ALPHA_BETA_CUTOFFS += 1\n if plyLeft > 1:\n ZHASH_TABLE[index].eval = new_value\n ZHASH_TABLE[index].ply = plyLeft\n ZHASH_TABLE[index].type = 'Beta Eval'\n ZHASH_TABLE[index].best_move = best_move\n break\n\n # this state has fully evaluated all its children\n is_exact = True\n score = alpha\n if whoseMove == 0:\n score = beta\n return score, best_move\n\ndef successors(state, whoseMove):\n board = state.board\n successors = []\n if WT.winTester(state) != \"No win\":\n return successors\n for r in range(8):\n for c in range(8):\n piece = board[r][c]\n if piece != 0 and piece % 2 == whoseMove:\n if not PM.is_frozen((r,c), board, whoseMove):\n #print(piece)\n limit = 8\n if PIECES[piece] in ['p', 'P']:\n limit = 4\n for i in range(limit):\n get_moves((r,c), state, i, whoseMove, successors)\n #print(len(successors))\n #print(\"\\n\")\n return successors\n\ndef get_moves(location, state, dir, whoseMove, successors):\n #successors = []\n dest = PM.get_next_space(location, dir)\n piece = state.board[location[0]][location[1]]\n enemy = 1 - whoseMove\n while dest is not None:\n dest_piece = state.board[dest[0]][dest[1]]\n if dest_piece != 0 and dest_piece % 2 == whoseMove: break\n if PIECES[piece] not in ['i', 'I', 'l', 'L', 'k','K']:\n if dest_piece != 0 and dest_piece % 2 == enemy: break\n if PM.can_move(location, dest, state.board, dir):\n #print(location)\n #print(dest)\n #print(\"\\n\")\n move = (location, dest, dir)\n successors.append(move)\n #new_state = PM.move(location, dest, state, dir)\n #successors.append(new_state)\n if piece in ['k', 'K']: break\n dest = PM.get_next_space(dest, dir)\n #print(dest)\n #print(\"\\n\")\n return successors\n\ndef static_eval(state):\n global STATIC_EVALS_PERFORMED\n STATIC_EVALS_PERFORMED += 1\n if PIECES[state.board[2][7]] =='P':\n return 1000\n else:\n return -100\n #copy = BC.BC_state(board)\n board = state.board\n possible_win = WT.winTester(state)\n if possible_win != \"No win\":\n if possible_win == \"Win for WHITE\":\n return 1000\n else:\n return -1000\n return evaluate_piece_strength(board, 1) + evaluate_piece_strength(board, 0)\\\n + round(0.25 * (mobility(board, 1) - mobility(board, 0)))\\\n + round(0.25 * center_control(board, 1) - center_control(board, 0))\\\n + (king_safety(board, 1) - king_safety(board, 0))\n\ndef mobility(board, side):\n enemy = 1 - side\n moves = 0\n #copy = BC.BC_state(board, side)\n #print(copy)\n for r in range(8):\n for c in range(8):\n piece = board[r][c]\n if PIECES[piece] != '-' and piece % 2 == side:\n limit = 8\n if PIECES[piece] in ['p','P']:\n limit = 4\n for i in range(limit):\n dest = PM.get_next_space((r,c), i)\n while dest is not None:\n dest_piece = board[dest[0]][dest[1]]\n if PIECES[dest_piece] != '-':\n if dest_piece % 2 == side: break\n if PIECES[piece] not in ['i','I','l','L','k','K']:\n if dest_piece % 2 == enemy: break\n if PM.can_move((r,c), dest, board, i):\n moves += 1\n if PIECES[piece] in ['k','K']: break\n dest = PM.get_next_space(dest, i)\n #print(\"\\n\")\n #print(moves)\n #print(copy)\n return moves\n\n\ndef evaluate_piece_strength(board, side):\n strength = 0\n for r in range(8):\n for c in range(8):\n piece = board[r][c]\n if piece != 0 and piece % 2 == side:\n strength += piece_weights(PIECES[piece], side)\n return strength\n\ndef center_control(board, side):\n spaces = 0\n line1 = PM.get_line((3,0), (3,7), board, 3)\n line2 = PM.get_line((4,0), (4,7), board, 3)\n for i in range(3, 5):\n for j in range(8):\n if board[i][j] != 0 and board[i][j] % 2 == side:\n spaces += 5\n return spaces\n\ndef king_safety(board, side):\n score = 0\n king = 12\n if side == 1:\n king = 13\n enemy = 1 - side\n king_location = PM.get_piece_location(king, board)\n if PM.is_king_in_check(board, king_location, side):\n return 100\n else:\n for i in range(8):\n next = PM.get_next_space(king_location, i)\n if next == None: continue\n if board[next[0]][next[1]] == 0:\n score -= 2\n elif board[next[0]][next[1]] % 2 == enemy:\n score -= 10\n else:\n score += 2\n return score\n\n\n\ndef piece_weights(piece, side):\n multiplier = [-1, 1]\n mult = multiplier[side]\n if piece in ['p''P']:\n return 1 * mult\n if piece in ['w','W']:\n return 3 * mult\n if piece in ['l','L']:\n return 5 * mult\n if piece in ['c', 'C', 'f','F']:\n return 7 * mult\n if piece in ['i', 'I']:\n return 9 * mult\n else:\n return 0\n\ndef initZhash():\n global ZOBRIST_NUMBERS\n for i in range(8):\n for j in range(8):\n for p in range(14):\n zobristnum[i][j][p] = \\\n randint(0, \\\n 4294967296)\ndef zHash(board):\n global ZOBRIST_NUMBERS\n hash = 0\n for r in range(8):\n for c in range(8):\n piece = PIECES[board[r][c]]\n if piece != '-':\n index = ZOBRIST_INDEXES[piece]\n hash ^= ZOBRIST_NUMBERS[r][c][index]\n return hash\n\ndef update_zhash_piece_movement(start, dest, piece, hash):\n piece = PIECES[piece]\n index = ZOBRIST_INDEXES[piece]\n hash ^= ZOBRIST_NUMBERS[start[0]][start[1]][index]\n hash ^= ZOBRIST_NUMBERS[dest[0]][dest[1]][index]\n return hash\n\ndef update_zhash_remove_piece(location, piece, hash):\n piece = PIECES[piece]\n index = ZOBRIST_INDEXES[piece]\n hash ^= ZOBRIST_NUMBERS[location[0]][location[1]][index]\n return hash\n\n","sub_path":"agent3.py","file_name":"agent3.py","file_ext":"py","file_size_in_byte":11268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"249961356","text":"#!/usr/bin/env python3\n\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nfrom pathlib import Path\n\nfrom data import Config, ExerciseInfo\n\n# Allow high-performance tests to be skipped\nALLOW_SKIP = ['alphametics', 'largest-series-product']\n\n\ndef check_assignment(exercise: ExerciseInfo, quiet=False) -> int:\n # Returns the exit code of the tests\n workdir = Path(tempfile.mkdtemp(exercise.slug))\n solution_file = exercise.solution_stub.name\n try:\n test_file_out = workdir / exercise.test_file.name\n if exercise.slug in ALLOW_SKIP:\n shutil.copyfile(exercise.test_file, test_file_out)\n else:\n with exercise.test_file.open('r') as src_file:\n lines = [line for line in src_file.readlines()\n if not line.strip().startswith('@unittest.skip')]\n with test_file_out.open('w') as dst_file:\n dst_file.writelines(lines)\n shutil.copyfile(exercise.exemplar_file, workdir / solution_file)\n kwargs = {}\n if quiet:\n kwargs['stdout'] = subprocess.DEVNULL\n kwargs['stderr'] = subprocess.DEVNULL\n return subprocess.run([sys.executable, '-m', 'pytest', test_file_out], **kwargs).returncode\n finally:\n shutil.rmtree(workdir)\n\n\ndef main():\n config = Config.load()\n exercises = config.exercises.all()\n if len(sys.argv) >= 2:\n # test specific exercises\n exercises = [\n e for e in exercises if e.slug in sys.argv[1:]\n ]\n\n failures = []\n for exercise in exercises:\n print('# ', exercise.slug)\n if not exercise.test_file:\n print('FAIL: File with test cases not found')\n failures.append('{} (FileNotFound)'.format(exercise.slug))\n else:\n if check_assignment(exercise):\n failures.append('{} (TestFailed)'.format(exercise.slug))\n print('')\n\n print('TestEnvironment:', sys.executable.capitalize(), '\\n\\n')\n\n if failures:\n print('FAILURES: ', ', '.join(failures))\n raise SystemExit(1)\n else:\n print('SUCCESS!')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"bin/test_exercises.py","file_name":"test_exercises.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"35088353","text":"import datetime\nimport quandl\nimport pandas as pd\nimport numpy as np\nimport pandas_datareader as pdr\nimport fix_yahoo_finance as yf\n\n\n#aapl = quandl.get(\"WIKI/AAPL\", start_date=\"2006-10-01\",\n# end_date=\"2012-01-01\")\n\n\naapl = yf.download('AAPL',\n start=datetime.datetime(2006, 10, 1),\n end=datetime.datetime(2012, 1, 1))\n\n\n# inspect columns\nprint(aapl.columns)\n\n\n# Assign 'Adj Close' to 'daily_close'\ndaily_close = aapl[['Adj Close']]\n\n\n# Daily returns\ndaily_pct_change = daily_close.pct_change()\n\n\n# Replace NA values with 0\ndaily_pct_change.fillna(0, inplace=True)\n\n# Inspect daily returns\nprint(daily_pct_change)\n\n\n# Daily log returns\ndaily_log_returns = np.log(daily_close.pct_change()+1)\n\nprint('daily log returns')\nprint(daily_log_returns)\n\n\n###\n# Monthly and Quarterly Returns\n##\n\nprint('Monthly Returns')\n# Resample 'aapl' to business months, take last observation as value\nmonthly = aapl.resample('BM').apply(lambda x: x[-1])\n\n# Calculate the monthly percentage change\nmonthly.pct_change()\n\n\n# Resample 'aapl' to quarters, take the mean as value per quarter\nquarter = aapl.resample(\"4M\").mean()\n\n# Calculate the quarterly percentage change\nquarter.pct_change()","sub_path":"returns.py","file_name":"returns.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"59555571","text":"import random\nfrom pathlib import Path\nfrom typing import Union\n\nimport ujson as json\nfrom botoy import FriendMsg, GroupMsg, MsgTypes, S\nfrom botoy import async_decorators as deco\n\ncurFileDir = Path(__file__).parent # 当前文件路径\n\nwith open(curFileDir / \"onset.json\", \"r\", encoding=\"utf-8\") as f:\n data: list = json.load(f)[\"data\"]\n\n\n@deco.ignore_botself\n@deco.these_msgtypes(MsgTypes.TextMsg)\n@deco.startswith(\"发病\")\nasync def main(ctx: Union[GroupMsg, FriendMsg]):\n name = ctx.Content[2:].strip()\n if name.isspace() or len(name) == 0 or \"[ATALL()]\" in name:\n await S.atext(\"要对谁发病捏?\")\n return\n content: str = random.choice(data)[\"content\"]\n await S.atext(content.replace(\"{{user.name}}\", name))\n\n\nreceive_group_msg = receive_friend_msg = main\n","sub_path":"plugins/bot_onset/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"399912004","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def reverseList(self, head: ListNode) -> ListNode:\n #Time - O(n) ; n is length of linkedlist\n #Space - O(1)\n if head is None or head.next is None: #handling edge cases.\n return head\n #Intiate variables cur, prev, next to store the 3 nodes temporarily which we are working on currently.\n cur = head.next\n prev = head\n prev.next = None\n next = cur.next\n while not next is None:\n cur.next = prev #reversing the link\n #Then slide the variables one one position right.\n prev = cur\n cur = next\n next = next.next\n cur.next = prev #Finally after traversing the linkedlist, reverse the last link\n return cur","sub_path":"week4/ReverseLinkedlist.py","file_name":"ReverseLinkedlist.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"586796803","text":"class Node(object):\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\n# 前序 递归\ndef pre_order_recur(root):\n if not root:\n return\n print(root.val)\n pre_order_recur(root.left)\n pre_order_recur(root.right)\n\n\n# 中序 递归\ndef in_order_recur(root):\n if not root:\n return\n in_order_recur(root.left)\n print(root.val)\n in_order_recur(root.right)\n\n\n# 后序 递归\ndef post_order_recur(root):\n if not root:\n return\n post_order_recur(root.left)\n post_order_recur(root.right)\n print(root.val)\n\n\n# 前序 非递归\ndef pre_order_none_recur(root):\n if not root:\n return\n stack = [root]\n while stack:\n cur = stack.pop()\n print(cur.val)\n if cur.right:\n stack.append(cur.right)\n if cur.left:\n stack.append(cur.left)\n\n\n# 中序 非递归\ndef in_order_none_recur(root):\n if not root:\n return\n stack = []\n while stack or root:\n if root:\n stack.append(root)\n root = root.left\n else:\n root = stack.pop()\n print(root.val)\n root = root.right\n\n\n# 后序 非递归\ndef post_order_none_recur(root):\n if not root:\n return\n stack = []\n mark_node = None\n while stack or root:\n if root:\n stack.append(root)\n root = root.left\n elif stack[-1].right != mark_node:\n root = stack[-1].right\n mark_node = None\n else:\n mark_node = stack.pop()\n print(mark_node.val)\n\n\nif __name__ == '__main__':\n root = Node(1, Node(2, Node(4), Node(5, Node(7))), Node(3, Node(6)))\n print('前序递归的结果:'), pre_order_recur(root)\n print('前序非递归的结果:'), pre_order_none_recur(root)\n print('中序递归的结果:'), in_order_recur(root)\n print('中序非递归的结果:'), in_order_none_recur(root)\n print('后序递归的结果:'), post_order_recur(root)\n print('后序非递归的结果:'), post_order_none_recur(root)\n","sub_path":"study/suanfa/2tree.py","file_name":"2tree.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"281724558","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.conf import settings\nfrom management import views\n\nurlpatterns = patterns('',\n url(r'^admin/', include(admin.site.urls)),\n url(r'^home/', views.home, name='home'),\n url(r'^cart/', views.cart, name='cart'),\n url(r'^clear_cart/',views.clear_cart, name='clear_cart'),\n url(r'^history/order_list/$', views.order_list,name='order_list'),\n url(r'^history/', views.history, name='history'),\n url(r'^about/', views.about, name='about'),\n url(r'^$', views.index, name='index'),\n url(r'^signup/$', views.signup,name='signup'),\n url(r'^order/$', views.order,name='order'),\n url(r'^login/$', views.login, name='login'),\n url(r'^logout/$', views.logout, name='logout'),\n url(r'^setpassword/$', views.setpassword, name='set_password'),\n url(r'^add/$', views.add, name='add_instrument'),\n url(r'^add_to_cart/$', views.add_to_cart, name='add_to_cart'),\n url(r'^delete_from_cart/$', views.delete_from_cart, name='delete_from_cart'),\n url(r'^view/$', views.view, name='view_instrument'),\n url(r'^view/detail/$', views.detail, name='view_detail'),\n url(r'^image/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_PATH}),\n)\n","sub_path":"weborder/weborder/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"253113393","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport MySQLdb\n\n# 打开数据库连接\ndb = MySQLdb.connect(\"localhost\",\"testuser\",\"test123\",\"TESTDB\" )\n\n# 使用cursor()方法获取操作游标 \ncursor = db.cursor()\n\nsql = \"DELETE FROM EMPLOYEE WHERE AGE > '%d'\"%(20)\ntry:\n cursor.execute()\n db.commit()\nexcept:\n db.rollback()\n\ndb.close()\n","sub_path":"python/py MySQL4.py","file_name":"py MySQL4.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"44380985","text":"#!/usr/bin/python3\n'''\n This module contains a Python script that takes in a string and sends\n a search request to the Star Wars API\n'''\n\n\nif __name__ == '__main__':\n import requests\n from sys import argv\n\n search = argv[1]\n url = 'https://swapi.co/api/people/' + '?' + 'search={}'.format(search)\n\n r = requests.get(url)\n r_json = r.json()\n\n count = r_json['count']\n peeps = r_json['results']\n print(\"Number of results: {}\".format(count))\n for peep in peeps:\n print('{}'.format(peep['name']))\n \n\n","sub_path":"0x11-python-network_1/9-starwars.py","file_name":"9-starwars.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"496346620","text":"from capreolus.extractor.bagofwords import BagOfWords\nfrom capreolus.extractor.embedtext import EmbedText\nfrom capreolus.reranker.reranker import Reranker\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass DSSM_class(nn.Module):\n def __init__(self, stoi, p):\n super(DSSM_class, self).__init__()\n self.p = p\n nvocab = len(stoi)\n nhiddens = [nvocab] + list(map(int, p[\"nhiddens\"].split()))\n print(nhiddens)\n\n self.ffw = nn.Sequential()\n for i in range(len(nhiddens) - 1):\n self.ffw.add_module(\"linear%d\" % i, nn.Linear(nhiddens[i], nhiddens[i + 1]))\n self.ffw.add_module(\"activate%d\" % i, nn.ReLU())\n self.ffw.add_module(\"dropout%i\" % i, nn.Dropout(0.5))\n\n self.output_layer = nn.Sigmoid()\n\n def forward(self, sentence, query):\n query = self.ffw(query)\n sentence = self.ffw(sentence)\n\n query_norm = query.norm(dim=-1)[:, None] + 1e-7\n sentence_norm = sentence.norm(dim=-1)[:, None] + 1e-7\n\n query = query / query_norm\n sentence = sentence / sentence_norm\n\n cos_x = (query * sentence).sum(dim=-1, keepdim=True)\n\n score = self.output_layer(cos_x)\n return score\n\n\ndtype = torch.FloatTensor\n\n\n@Reranker.register\nclass DSSM(Reranker):\n description = \"\"\"Po-Sen Huang, Xiaodong He, Jianfeng Gao, Li Deng, Alex Acero, and Larry Heck. 2013. Learning deep structured semantic models for web search using clickthrough data. In CIKM'13.\"\"\"\n EXTRACTORS = [BagOfWords]\n\n @staticmethod\n def config():\n # hidden layer dimentions, should be a list of space-separated number in a string, e.g. '56 128 32', the i-th value represents the output dim of the i-th hidden layer\n nhiddens = \"56\"\n lr = 0.0001\n return locals().copy() # ignored by sacred\n\n @staticmethod\n def required_params():\n # Used for validation. Returns a set of params required by the class defined in get_model_class()\n return {\"nhiddens\", \"nvocab\", \"maxdoclen\", \"maxqlen\"}\n\n @classmethod\n def get_model_class(cls):\n return DSSM_class\n\n def build(self):\n self.model = DSSM_class(self.embeddings, self.config)\n return self.model\n\n def score(self, data):\n query_idf = data[\"query_idf\"].to(self.device)\n query_sentence = data[\"query\"].to(self.device)\n pos_sentence, neg_sentence = data[\"posdoc\"].to(self.device), data[\"negdoc\"].to(self.device)\n\n return [self.model(pos_sentence, query_sentence).view(-1), self.model(neg_sentence, query_sentence).view(-1)]\n\n def test(self, query_sentence, query_idf, pos_sentence, *args, **kwargs):\n query_sentence = query_sentence.to(self.device)\n pos_sentence = pos_sentence.to(self.device)\n\n return self.model(pos_sentence, query_sentence).view(-1)\n\n def zero_grad(self, *args, **kwargs):\n self.model.zero_grad(*args, **kwargs)\n","sub_path":"capreolus/reranker/DSSM.py","file_name":"DSSM.py","file_ext":"py","file_size_in_byte":2946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"494955470","text":"import pyglm.utils.fastinv\nreload(pyglm.utils.fastinv)\nfrom pyglm.utils.fastinv import *\n\ndef test_submatrix_class():\n N = 10\n X = np.random.randn(1000,N)\n A = X.T.dot(X)\n\n mat = BigInvertibleMatrix(A)\n\n # Get a random submatrix\n for itr in xrange(10):\n inds = np.where(np.random.rand(N) < 0.5)[0]\n # inds = np.arange(itr+1).astype(np.int)\n Asub = A[np.ix_(inds, inds)]\n\n pinds, pinv, pdet = mat.compute_submatrix_inverse(inds)\n Ainv_true = np.linalg.inv(Asub)\n Adet_true = np.linalg.slogdet(Asub)[1]\n\n assert np.allclose(pinv, Ainv_true, atol=1e-8)\n assert np.allclose(pdet, Adet_true, atol=1e-8)\n\n # Update\n mat.update(pinds, pinv, pdet)\n\ndef test_block_inverse_add_row():\n N = 4\n X = np.random.randn(100,N)\n A = X.T.dot(X)\n # A = np.random.randn(4,4)\n # A = A.dot(A.T)\n # A += 4*np.eye(4)\n Ainv = np.linalg.inv(A)\n\n # Get a subset of A and add rows\n end = 3\n Bm = A[:end,end:]\n Cm = Bm.T\n Dm = A[end:,end:]\n\n Pt,Qt,Rt,St = block_inverse_add_rows(Ainv[:end,:end], Bm, Cm, Dm, symm=True)\n assert np.allclose(Ainv[:end,:end], Pt, atol=1e-3)\n assert np.allclose(Ainv[:end,end:], Qt, atol=1e-3)\n assert np.allclose(Ainv[end:,:end], Rt, atol=1e-3)\n assert np.allclose(Ainv[end:,end:], St, atol=1e-3)\n\ndef test_block_inverse_remove_row():\n N = 4\n X = np.random.randn(100,N)\n A = X.T.dot(X)\n # A = np.random.randn(4,4)\n # A = A.dot(A.T)\n # A += 4*np.eye(4)\n Ainv = np.linalg.inv(A)\n\n # Get a subset of A and add rows\n for end in xrange(1,4):\n Am = A[:end,:end]\n Pmt = np.linalg.inv(Am)\n\n Pmt_tilde = block_inverse_remove_rows(Ainv, end, symm=True)\n assert np.allclose(Pmt, Pmt_tilde, atol=1e-3)\n\n\nif __name__ == \"__main__\":\n # test_block_inverse_add_row()\n # test_block_inverse_remove_row()\n test_submatrix_class()","sub_path":"test/test_matrix_inverse.py","file_name":"test_matrix_inverse.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"395293977","text":"import sys\nimport os\nimport unittest\nimport logging\n\nfrom server.Game import Game\nfrom server.BaseClass import BaseClass\nfrom server.UnoException import *\nimport time\n\nclass TestGame(unittest.TestCase):\n def setUp(self):\n self.com = MockCom(self)\n self.game = Game(self.com, 3, 4, 30, 30, True)\n \n self.game.dealer = MockDealer(self)\n self.game.setup_new_game()\n self.game.dealer = MockDealer(self)\n self.dealer = self.game.dealer\n\n def tearDown(self):\n pass\n\n def test_chat(self):\n pass\n\n def test_join(self):\n #try to pass in a shitty name\n self.com.exeEvt(\"join\", 1, \"|shit\")\n self.assertTrue(self.com.invalid[\"called\"])\n self.assertEqual(self.com.invalid[\"p\"][1], \"|shit\")\n self.com.reset_p()\n\n\n self.com.exeEvt(\"join\", 3, \"player1\")\n\n self.com.exeEvt(\"join\", 4, \"player2\")\n\n self.assertEqual(len(self.game.clients), 2)\n\n #now add 3rd player, check if it starts to count down\n self.com.exeEvt(\"join\", 5, \"player3\")\n self.assertEqual(self.game.status, 1)\n\n started_time = self.game.count_time\n\n #now add 4th players, check if it resets the count down\n self.com.exeEvt(\"join\", 10, \"player4\")\n self.assertNotEqual(self.game.count_time, started_time)\n started_time = self.game.count_time\n\n #now add 5th players, check if it politely ask the player to wait\n #and not reset the count down\n self.com.exeEvt(\"join\", 11, \"player5\")\n self.assertEqual(self.game.count_time, started_time)\n self.assertTrue(self.com.wait[\"called\"])\n self.assertEqual(self.com.wait[\"p\"][0], 11)\n self.assertEqual(self.com.wait[\"p\"][1], \"player5\")\n self.com.reset_p()\n\n #now try to put more player than the queue size\n #supposed to kick them out\n self.game.maxQueue = 4\n self.com.exeEvt(\"join\", \"player6\", 14)\n self.assertTrue(self.com.kick[\"called\"])\n self.assertEqual(self.com.kick[\"p\"][0], 14)\n\n def test_check_time(self):\n\n self.game.check_time()\n\n self.com.exeEvt(\"join\", 3, \"player1\")\n self.com.exeEvt(\"join\", 4, \"player2\")\n self.com.exeEvt(\"join\", 5, \"player3\")\n\n self.game.cd_join = 0\n self.game.check_time()\n self.assertTrue(self.dealer.sg_c[\"called\"])\n self.assertEqual(self.dealer.sg_c[\"p\"][0], 3)\n\n self.assertTrue(self.com.start[\"called\"])\n self.assertEqual(self.com.start[\"p\"][0], \"player1,player2,player3\")\n\n\nclass MockCom(BaseClass):\n def __init__(self, a):\n self.a = a\n BaseClass.__init__(self)\n self.reset_p()\n\n def reset_p(self):\n self.wait = {\"called\": False, \"p\": []}\n self.chat = {\"called\": False, \"p\": []}\n self.kick = {\"called\": False, \"p\": []}\n self.invalid = {\"called\": False, \"p\": []}\n self.accept = {\"called\": False, \"p\": []}\n self.start = {\"called\": False, \"p\": []}\n\n\n def bc_chat(self):\n pass\n\n def s_kick(self, sockId):\n self.kick[\"called\"] = True\n self.kick[\"p\"] = [sockId]\n\n\n def s_invalid(self, sockId, msg):\n self.invalid[\"called\"] = True\n self.invalid[\"p\"] = [sockId, msg]\n\n def s_accept(self, sockId, msg):\n pass\n\n def s_wait(self, sockId, msg):\n self.wait[\"called\"] = True\n self.wait[\"p\"] = [sockId, msg]\n\n def bc_won(self, sockId):\n self.won[\"called\"] = True\n self.won[\"p\"] = [sockId]\n\n def bc_start(self, msg):\n self.start[\"called\"] = True\n self.start[\"p\"] = [msg]\n\n\nclass MockDealer(BaseClass):\n def __init__(self, a):\n self.a = a\n BaseClass.__init__(self)\n self.playing = False\n self.reset_p()\n \n def reset_p(self):\n #sg_c: start_game_called\n self.sg_c = {\"called\": False, \"p\": []}\n\n def start_game(self, n):\n self.sg_c[\"called\"] = True\n self.sg_c[\"p\"] = [n]\n\n\nif __name__ == \"__main__\": \n unittest.main()\n","sub_path":"tests/server/test_game.py","file_name":"test_game.py","file_ext":"py","file_size_in_byte":4209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"348512049","text":"import tellopy\nimport cv2\nimport numpy as np\nimport queue\nimport platform\nimport subprocess\nimport time\nimport vision\nimport traceback\nimport enum\nimport logging\n\n# Make the drone land after 20 seconds in case it went rogue\nEXPERIMENT_TIMEOUT = 60*3\n\ndef orderselectui():\n selections = []\n regions = {\n 'red': ((20,60), (20+150, 60+150)),\n 'green': ((190,60), (190+150, 60+150)),\n 'blue': ((360,60), (360+150, 60+150)),\n 'yellow': ((530,60), (530+150, 60+150)),\n }\n def select(event, x, y, flags, param):\n if event == cv2.EVENT_LBUTTONDOWN:\n for sel, ((sx, sy), (ex, ey)) in regions.items():\n if sel in selections:\n continue\n if sx <= x <= ex and sy <= y <= ey:\n selections.append(sel)\n return\n\n def draw():\n display = np.ones((230, 700, 3), dtype=np.uint8)*255\n cv2.putText(display, f\"Select colors in popping order\", (40,40), cv2.FONT_HERSHEY_COMPLEX, 1, (255,0,255))\n cv2.rectangle(display, *regions['red'], (0,0,255),-1)\n cv2.rectangle(display, *regions['green'], (0,255,0),-1)\n cv2.rectangle(display, *regions['blue'], (255,0,0),-1)\n cv2.rectangle(display, *regions['yellow'], (0,255,255),-1)\n for i, sel in enumerate(selections):\n cv2.rectangle(display, *regions[sel], (0,0,0), 3)\n pt = regions[sel][0]\n pt = (pt[0] + 70, pt[1] + 70)\n cv2.putText(display, f\"{i+1}\", pt, cv2.FONT_HERSHEY_COMPLEX, 1, (0,0,0))\n cv2.imshow('Display', display)\n key = cv2.waitKey(50)\n if key == 27:\n raise Exception(\"Not all order selections made\")\n\n cv2.namedWindow(\"Display\")\n cv2.setMouseCallback(\"Display\", select)\n while len(selections) < 4:\n draw()\n return selections\n\n\ndef statusmessageui(message):\n display = np.ones((230, 700, 3), dtype=np.uint8)*255\n cv2.putText(display, message, (40,40), cv2.FONT_HERSHEY_COMPLEX, 1, (255,0,255))\n cv2.imshow('Display', display)\n cv2.waitKey(1)\n\n\ndef handlaunchui(drone):\n global v, q\n display = np.ones((230, 700, 3), dtype=np.uint8)*255\n cv2.putText(display, \"Place the drone in the palm on your hand, then\", (40,40), cv2.FONT_HERSHEY_COMPLEX, 1, (255,0,255))\n cv2.putText(display, \"press SPACEBAR when ready.\", (40,80), cv2.FONT_HERSHEY_COMPLEX, 1, (255,0,255))\n cv2.putText(display, \"After the propellers start,\", (40,120), cv2.FONT_HERSHEY_COMPLEX, 1, (255,0,255))\n cv2.putText(display, \"toss the drone up.\", (40,160), cv2.FONT_HERSHEY_COMPLEX, 1, (255,0,255))\n cv2.imshow('UI', display)\n while True:\n key = cv2.waitKey(1)\n if key == 32:\n drone.throw_and_go()\n display = np.ones((230, 700, 3), dtype=np.uint8)*255\n cv2.putText(display, \"After the propellers start,\", (40,40), cv2.FONT_HERSHEY_COMPLEX, 1, (255,0,255))\n cv2.putText(display, \"toss the drone up.\", (40,80), cv2.FONT_HERSHEY_COMPLEX, 1, (255,0,255))\n cv2.putText(display, f\"Do this within 5 seconds!\", (40,120), cv2.FONT_HERSHEY_COMPLEX, 1, (255,0,255))\n cv2.imshow('UI', display)\n cv2.waitKey(1)\n dronesleep(5)\n cv2.destroyWindow('UI')\n break\n elif key == 27:\n raise Exception(\"Early quit\")\n\n droneclear(waitkey=False)\n\n\nclass FinalAttackState(enum.Enum):\n THRUST = 1\n REVERSE = 2\n CONFIRM = 3\n\n\nstatus = None\nDEFAULT_RESTING_HEIGHT = 6\nv = None\nq = None\n\ndef droneclear(**kwargs):\n global v, q\n if q.full():\n q.get()\n v.check_new_frame(q, str(status), **kwargs)\n\ndef dronesleep(t, **kwargs):\n global v, q\n expiry = time.time() + t\n while time.time() < expiry:\n v.check_new_frame(q, str(status), **kwargs)\n droneclear()\n\ndef droneloop():\n global v, q\n logging.basicConfig(filename=f\"{time.time()}.txt\", filemode='w',\n level=logging.DEBUG, format='%(asctime)s [%(levelname)s] %(name)s: %(message)s')\n logger = logging.getLogger(__name__)\n\n resting_height = DEFAULT_RESTING_HEIGHT\n\n # Get the configuration for this match\n remainingBalloons = orderselectui()\n \n statusmessageui(\"Waiting for WiFi network switch...\")\n # Wait for the user to switch WiFi networks\n while ping('192.168.10.1') == False:\n print('Drone is offline, retrying...')\n print('Connected!')\n\n statusmessageui(\"Connecting to drone...\")\n\n def handler(event, sender, data, **args):\n global status\n drone = sender\n if event is drone.EVENT_FLIGHT_DATA:\n status = data\n\n # Connect to Tello\n drone = tellopy.Tello()\n\n try:\n drone.subscribe(drone.EVENT_FLIGHT_DATA, handler)\n\n drone.connect()\n drone.wait_for_connection(60.0)\n\n logger.info(\"Connected to drone\")\n statusmessageui(\"Video feed starting...\")\n\n v = vision.Vision(record=True)\n q = queue.Queue(maxsize=1)\n v.open_input(drone.get_video_stream())\n\n # Wait for video to stabilize\n dronesleep(10)\n logger.info(\"Vision presumed stable\")\n\n handlaunchui(drone)\n logger.info(\"Hand launch completed\")\n\n last_xrot = 0\n final_state = None\n final_target = None\n final_timer = 0\n start_time = time.time()\n search_start = None\n\n # Main control loop\n while len(remainingBalloons) > 0:\n target = remainingBalloons[0]\n\n # Get vision sol'n\n while q.empty():\n v.check_new_frame(q, str(status))\n data = q.get()\n\n # Check for early exit\n if data['type'] == 'quit':\n logger.info(\"User initiated shutdown by ESC\")\n break\n\n logger.info(\"Vision solutions: \"\n + \",\".join({c for c in {'red','green','blue','yellow'} if data[c] is not None}))\n\n # Check for final attack state\n if final_state is not None:\n logger.info(f\"In final attack state {final_state}\")\n resting_height = DEFAULT_RESTING_HEIGHT\n if final_state == FinalAttackState.THRUST:\n if time.time() < final_timer + 6:\n # move forward slowly for 6 seconds\n drone.forward(8)\n else:\n # next state transition\n drone.forward(0)\n final_state = FinalAttackState.REVERSE\n final_timer = time.time()\n\n elif final_state == FinalAttackState.REVERSE:\n if time.time() < final_timer + 1:\n # back up quickly for 1 second\n drone.backward(20)\n else:\n # next state transition\n drone.backward(0)\n final_state = FinalAttackState.CONFIRM\n final_timer = time.time()\n\n elif final_state == FinalAttackState.CONFIRM:\n # check vision to make sure we popped it\n if data[final_target] is None:\n # we did\n remainingBalloons.pop(0)\n # if this list gets to len 0, then it will land next loop iter\n else:\n # damn, guess we gotta go for it again\n pass\n final_state = None\n\n continue\n\n # If we only have 20 seconds left, pop whatever we can find\n if data[target] is None and (time.time() - start_time) > 160:\n for c in {'red', 'green', 'blue', 'yellow'}:\n if data[c] is not None:\n target = c\n break\n\n # Check for search state\n if data[target] is None:\n if search_start is None:\n search_start = time.time()\n duration = time.time() - search_start\n if duration > 15:\n resting_height -= 2\n search_start = time.time()\n logger.info(f\"Current target {target} not in sight, resting height {resting_height}', searching for {duration}s\")\n drone.right(0)\n drone.forward(6)\n # Spin clockwise slowly (or in the direction of last seen balloon\n rate = 35\n if last_xrot < 0:\n drone.counter_clockwise(rate)\n else:\n drone.clockwise(rate)\n # Ascend to \"10\"\n if status.height < resting_height:\n drone.up(20)\n elif status.height > resting_height:\n drone.down(20)\n else:\n drone.up(0)\n continue\n\n search_start = None\n\n # Align with balloon\n xrot, height, distance = data[target]\n rot_ontarget = False\n height_ontarget = False\n\n logger.info(f\"Tracking target {target}: xrot={xrot}deg height={height}cm, dist={distance}cm\")\n\n max_xrot = 4\n if distance < 50:\n max_xrot = 8\n\n # Rotate to face the balloon if needed\n if xrot < max_xrot * -1:\n drone.counter_clockwise(20)\n elif xrot > max_xrot:\n drone.clockwise(20)\n else:\n drone.clockwise(0)\n rot_ontarget = True\n\n elevSpeeed = 15\n if distance < 100:\n elevSpeeed = 25\n\n # change elevation to match balloon if needed\n if height < -17: # increase this to favor attacking from bottom\n drone.down(elevSpeeed)\n elif height > 17: # decrease this to favor attacking from top\n drone.up(elevSpeeed)\n else:\n drone.up(0)\n height_ontarget = True\n\n # head in for the kill\n if distance > 100:\n logger.info(\"Moving forward, 1st stage\")\n drone.forward(20)\n elif distance > 50 and rot_ontarget and height_ontarget:\n logger.info(\"Moving forward, locked on\")\n drone.forward(20)\n elif rot_ontarget and height_ontarget:\n print('\\a')\n logger.info(\"Taking the shot\")\n # final kill for 6 seconds\n final_state = FinalAttackState.THRUST\n final_timer = time.time()\n final_target = target\n else:\n logger.info(\"Still aligning with target\")\n drone.forward(0)\n\n last_xrot = xrot\n \n logger.info(\"Landing drone\")\n cv2.destroyAllWindows()\n drone.right(0)\n drone.forward(0)\n drone.up(0)\n drone.clockwise(0)\n drone.land()\n time.sleep(5)\n except Exception as ex:\n traceback.print_exc()\n finally:\n drone.quit()\n\n logger.info(\"Connection closed\")\n\n\ndef ping(host):\n \"\"\"\n Returns True if host (str) responds to a ping request.\n Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.\n \"\"\"\n\n # Option for the number of packets as a function of\n param = '-n' if platform.system().lower()=='windows' else '-c'\n\n # Building the command. Ex: \"ping -c 1 google.com\"\n command = ['ping', param, '1', host]\n\n return subprocess.call(command) == 0\n\n\nif __name__ == \"__main__\":\n droneloop()\n","sub_path":"control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":11709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"254086185","text":"# TODO LIST:\n# -- Dijkstra's Algorithm for pathfinding?\n# -- Look at more than 1 cell deep to see if we can capture territory earlier?\n# -- How to identify which direction to focus growth? Looking at production map at beginning to see.\n# -- Attack patterns? What's the best strategy for attacking / retreating / reinforcing?\n# -- Varying production multiplier by distance to border?\n\n# Version 1: Basic bot implementation - Modifications from random bot: To be added\n# Version 2: \n# -- Moved hlt file to single file. \n# -- consolidate_strength: Completely rewritten. Searches all border tiles and then sees if we can consolidate. Ranked by production strength, then sees if we can consolidate.\n# -- find_nearest_enemy_direction: Calculate ALL distances, and pick the shortest with lowest production if there is a tie. Otherwise, pick randomly.\n# -- heuristic: look at not just the cell but adjacent cells to determine the value of capturing the cell.\n# -- smallest strength cells move first. \n# Version 3: Uploaded incorrectly\n# Version 4:\n# -- move_to_target: old implementation might move into uncontrolled territory. Not good. New implementation moves only though adjacent owned territory, if possible. If multiple\n# routes exist, then it takes the direction with the lowest production.\n# -- consolidate_strength: Split into two subroutines. One which is the old multi-attacker into a cell, the other looks outwards to gather strength to attack a cell.\n# -- Idea: Can we expand multi-attacking into a cell to also look and see if we can capture a cell by moving units INTO adjacent cells??\n# Version 5: Rewrote heuristic function. Tries not to overvalue expanding into cells bordering enemy territory too much.\n# Version 6: ??\n# Version 7: Rewrote move to border function. Now squares will try to move towards higher production cells instead of the nearest border.\n# -- Complete code overhaul. Remove GameMap class, add Square class.\n\n###########\n# Imports #\n###########\nimport math\nfrom itertools import chain\nimport sys\nimport logging\nimport numpy\nimport random\n\n\n#############\n# Variables #\n#############\n\nbotname = \"shummie v7.7\"\nproduction_decay = 0.50\nproduction_influence_max_distance = 5\nbuildup_multiplier = 5\nstrength_buffer = 0\n\n \n\n \n \n#################\n# GameMap Class #\n#################\n\nclass GameMap:\n def __init__(self):\n \n self.initialize_game()\n\n def initialize_game(self):\n # This should only be called once, and at the beginning of the game\n self.my_id = int(get_string())\n map_size_string = get_string()\n production_map_string = get_string()\n \n self.width, self.height = tuple(map(int, map_size_string.split()))\n self.frame = 0\n \n self.production_map = numpy.array(list(map(int, production_map_string.split()))).reshape((self.height, self.width)).transpose()\n\n self.get_frame()\n \n # Initialize all the maps that this stores\n \n self.projected_owner_map = numpy.ones((self.width, self.height)) * -1\n self.projected_strength_map = numpy.ones((self.width, self.height)) * -1\n\n self.starting_player_count = numpy.amax(self.owner_map) # Note, for range you'd need to increase the range by 1\n \n self.next_uncapped_strength_map = numpy.zeros((self.starting_player_count + 1, self.width, self.height))\n \n # Send the botname\n send_string(botname)\n \n\n\n \n def get_frame(self, map_string = None):\n # Updates the map information from the latest frame provided by the game environment\n if map_string is None:\n map_string = get_string()\n split_string = map_string.split()\n \n # The state of the map (including owner and strength values, but excluding production values) is sent in the following way:\n # One integer, COUNTER, representing the number of tiles with the same owner consecutively.\n # One integer, OWNER, representing the owner of the tiles COUNTER encodes.\n # The above repeats until the COUNTER total is equal to the area of the map. \n # It fills in the map from row 1 to row HEIGHT and within a row from column 1 to column WIDTH. \n # Please be aware that the top row is the first row, as Halite uses screen-type coordinates.\n owners = list()\n while len(owners) < self.width * self.height:\n counter = int(split_string.pop(0))\n owner = int(split_string.pop(0))\n owners.extend([owner] * counter)\n assert len(owners) == self.width * self.height\n \n self.owner_map = numpy.array(owners).reshape((self.height, self.width)).transpose()\n \n # This is then followed by WIDTH * HEIGHT integers, representing the strength values of the tiles in the map. \n # It fills in the map in the same way owner values fill in the map. \n assert len(split_string) == self.width * self.height\n str_list = list(map(int, split_string))\n \n self.strength_map = numpy.array(str_list).reshape((self.height, self.width)).transpose()\n \n # Create all squares for the GameMap\n self.squares = numpy.empty((self.width, self.height), dtype = numpy.object)\n #self.squares = [[None for y in range(self.height)] for x in range(self.width)]\n for x in range(self.width):\n for y in range(self.height):\n self.squares[x, y] = Square(self, x, y, self.owner_map[x, y], self.strength_map[x, y], self.production_map[x, y])\n \n # Reset the move_map\n self.move_map = numpy.ones((self.width, self.height)) * -1 # Could possibly expand this in the future to consider enemy moves...\n if self.frame > 1:\n self.next_uncapped_strength_map = numpy.zeros((self.starting_player_count + 1, self.width, self.height))\n \n self.frame += 1\n \n def __iter__(self):\n # Allows direct iteration over all squares\n return chain.from_iterable(self.squares)\n \n\n \n def is_npc_border(self, square):\n # Looks at a square and sees if it's an NPC border square\n # Defined as a square which is owned by 0 and has a neighbor of my_id\n if square.owner != 0: return False\n for n in self.neighbors(square):\n if n.owner == self.my_id:\n return True\n return False\n \n def get_distance(self, sq1, sq2):\n dx = abs(sq1.x - sq2.x)\n dy = abs(sq1.y - sq2.y)\n if dx > self.width / 2:\n dx = self.width - dx\n if dy > self.height / 2:\n dy = self.height - dy\n return dx + dy\n \n def get_target(self, square, direction):\n # This function might be unnecessary?\n dx, dy = ((0, -1), (1, 0), (0, 1), (-1, 0), (0, 0))[direction]\n return self.squares[(square.x + dx) % self.width][(square.y + dy) % self.height]\n\n def get_coord(self, sourcex, sourcey, dx, dy):\n return ((sourcex + dx) % self.width, (sourcey + dy) % self.height)\n \n def make_move(self, square, direction):\n # Queues up the move to be made.\n # First, store the move in the move_map for easy reference\n self.move_map[square.x, square.y] = direction\n # Update square to new direction\n square.make_move(direction)\n \n def send_frame(self):\n # Goes through each square and get the list of moves.\n move_list = []\n for sq in chain.from_iterable(self.squares):\n if sq.owner == self.my_id:\n if sq.move == -1:\n # In the event we didn't actually assign a move, make sure it's coded to STILL\n sq.move = 4\n move_list.append(sq)\n \n send_string(' '.join(str(square.x) + ' ' + str(square.y) + ' ' + str(translate_cardinal(square.move)) for square in move_list))\n \n def calculate_uncapped_next_strength(self):\n # Given the move_map, calculate the uncapped strength in each cell.\n for x in range(self.width):\n for y in range(self.height):\n owner = self.owner_map[x, y]\n # 4. Add strength to pieces which choose to remain where they are.\n # Treat all cells that have a move value of -1 or 4 to be increasing in strength.\n # In practice, this is not true for enemy pieces, but for now, let's make this assumption\n if self.move_map[x, y] == 4 or self.move_map[x, y] == -1:\n self.next_uncapped_strength_map[owner, x, y] += self.strength_map[x, y] + self.production_map[x, y] if owner > 0 else 0\n # 5. Simultaneously move (and combine if necessary) all player's pieces.\n else: \n direction = self.move_map[x, y]\n dx, dy = ((0, -1), (1, 0), (0, 1), (-1, 0))[int(direction)]\n self.next_uncapped_strength_map[owner, (x + dx) % self.width, (y + dy) % self.height] += self.strength_map[x, y]\n\n def create_production_influence_map(self):\n # Lots of tweaking to do...\n # Start with a basic prod/strength evaluation for npc cells\n for x in range(self.width):\n for y in range(self.height): \n prod_value = self.production_map[x, y]\n if self.owner_map[y, x] == 0:\n str_value = max(1, self.strength_map[x, y])\n else:\n # If we want to do something differently with strengths in enemy territories, we can alter it here.\n str_value = max(1, self.strength_map[x, y]) # This will cause cells to avoid border cells...\n\n value = prod_value / str_value\n combos = ((dx, dy) for dy in range(-production_influence_max_distance, production_influence_max_distance+1) for dx in range(-production_influence_max_distance, production_influence_max_distance+1) if abs(dx) + abs(dy) <= production_influence_max_distance)\n for c in combos:\n distance = abs(c[0]) + abs(c[1])\n decay_factor = math.exp(-production_decay * distance)\n self.influence_production_map[self.owner_map[x, y], (x + c[0]) % self.width, (y + c[1]) % self.height] += value * decay_factor\n\n def get_best_move(self, square):\n # For a given square, find the \"best\" move we can\n border = False\n \n targets = []\n for d in (NORTH, EAST, SOUTH, WEST):\n target = game_map.get_target(square, d)\n if target.owner != self.my_id:\n border = True\n val = heuristic(target, square)\n targets.append((target, val))\n\n targets.sort(key = lambda x: x[1], reverse = True) # Sorts targets from high to low\n \n # We have a list of all adjacent cells. If targets is not None, let's see what we can do\n if len(targets) > 0:\n # Go through the list and see if we can attack one\n for t in targets:\n if t[0].strength < square.strength:\n return square.move_to_target(t[0], False)\n \n # if we don't have enough strength to make it worth moving yet, stay still\n if square.strength < (square.production * buildup_multiplier):\n # Don't actually set a cell to STILL unless we want it to stay still\n return True\n # If we aren't at a border, move towards the closest one\n elif not border:\n return self.go_to_border(square)\n # Else, we're at a border, don't have the strength to attack another cell, and have less than the buildup multipler. Let other functions handle movement\n else:\n return True\n \n def go_to_border(self, square):\n # Going to do a simple search for the closest border then determine which of the 4 directions we should go\n target = (None, 0)\n max_distance = min(game_map.width, game_map.height) / 2\n for d in (NORTH, EAST, SOUTH, WEST):\n distance = 1\n location = self.get_target(square, d)\n while location.owner == self.my_id and distance < max_distance:\n distance += 1\n location = self.get_target(location, d)\n border_value = location.influence_production_npc()\n #scaled_value = border_value / distance\n scaled_value = border_value \n if scaled_value > target[1]:\n target = (location, scaled_value)\n if target[0] != None:\n square.move_to_target(target[0], True)\n else:\n # If all cardinal directions are owned, is it possible to actually not move?\n # Move randomly then?\n #self.make_move(square, random.choice(range(1)))\n self.make_move(square, NORTH)\n\n\n def prevent_overstrength(self):\n # Tries to prevent wasting strength by having multiple cells move into the same square\n # Calculate the next turn's projected strengths based on moves so far.\n self.calculate_uncapped_next_strength()\n \n # Check the list of cells that will be capped\n cells_over = []\n for x in range(self.width):\n for y in range(self.height):\n if self.owner_map[x, y] == self.my_id: # We only care about our own cells\n if self.next_uncapped_strength_map[self.my_id, x, y] > (255 + strength_buffer):\n cells_over.append(self.squares[x, y])\n \n # cells_over contains a list of squares which will be over the strength cap\n cells_over_count = len(cells_over) # We'll be popping squares out so keep the initial count so we can return it later\n while len(cells_over) > 0:\n square = cells_over.pop(0) \n \n # Case 1: There should never be a reason we are staying still and being too strong. In the event this happens... what?\n # Case 2: We are not moving, let's move this square into a square moving into us\n if (square.move == -1 or square.move == STILL):\n # Try to move into another square which is moving into us\n if len(square.moving_here) > 0:\n square.move_to_target(random.choice(square.moving_here), True)\n else:\n # We are moving but the squares that are moving into here are going to collide.\n # See if we can reroute one of them perpendicular to where they are going, going the opposite direction is likely guaranteed to be counter productive\n if len(square.moving_here) > 1:\n square_to_move = random.choice(square.moving_here)\n option1dx, option1dy = get_offset((square_to_move.move + 1) % 4)\n option2dx, option2dy = get_offset((square_to_move.move + 3) % 4)\n \n # Move to the square that would cause the smallest loss in strength\n option1 = square_to_move.strength + self.next_uncapped_strength_map[self.my_id, (square_to_move.x + option1dx) % self.width, (square_to_move.y + option1dy) % self.height]\n option2 = square_to_move.strength + self.next_uncapped_strength_map[self.my_id, (square_to_move.x + option2dx) % self.width, (square_to_move.y + option2dy) % self.height]\n option0 = self.next_uncapped_strength_map[self.my_id, square.x, square.y]\n\n if option1 == min(option1, option2, option0):\n self.make_move(square_to_move, (square_to_move.move + 1) % 4)\n elif option2 == min(option1, option2, option0):\n self.make_move(square_to_move, (square_to_move.move + 3) % 4)\n else:\n # Do nothing\n continue\n \n return cells_over_count\n\n \n def attack_border_multiple_pieces(self):\n # Looks to see if there are any border cells which can be attacked right now by multiple pieces at the same time.\n # Looks only at cells whose move value is -1 and are bordering a neighboring cell.\n border_squares = []\n for square in chain.from_iterable(self.squares):\n if square.is_npc_border():\n border_squares.append((square, heuristic(square)))\n \n border_squares.sort(key = lambda x: x[1], reverse = True)\n \n for border_square in border_squares:\n # For each border square, starting with the most valuable, attempt to capture it.\n friendly_neighbors = [x for x in border_square[0].neighbors() if x.owner == self.my_id]\n available_strength = 0\n # TODO: There's a more pythonic way to do this instead of the loop below. \n for f in friendly_neighbors:\n if f.move == -1:\n available_strength += f.strength\n \n if available_strength > border_square[0].strength:\n attacking_strength = 0\n for f in friendly_neighbors:\n if f.move == -1 and attacking_strength <= border_square[0].strength:\n attacking_strength += f.strength\n f.move_to_target(border_square[0], False)\n \n def consolidate_strength(self, cells_out = 1):\n # Looks at border cells and sees if there is an opportunity to look N neighbors out to consolidate strength to capture a territory.\n border_squares = []\n for square in chain.from_iterable(self.squares):\n if square.is_npc_border():\n border_squares.append((square, heuristic(square)))\n \n border_squares.sort(key = lambda x: x[1], reverse = True) # Sorts by all border cells which will not be taken next turn by the heuristic above. \n\n distance = 1\n while distance <= cells_out:\n self.consolidate_n_out(border_squares, distance)\n distance += 1\n \n def consolidate_n_out(self, border_squares_list, cells_out):\n # For each border_square, we want to look at each friendly neighbor and see if we can take over this square in cells_out turns from now.\n \n for border_square_tuple in border_squares_list:\n border_square = border_square_tuple[0]\n # Get a list of all friendly neighbors to this square: These are the TARGET squares to move to.\n friendly_neighbors = [x for x in border_square.neighbors() if x.owner == self.my_id]\n \n for f in friendly_neighbors:\n # How much strength do we need and can we get it cells_out away?\n needed_strength = border_square.strength + 1\n \n moving_cells = False\n \n # Check friendly neighboring cells.\n for distance_out in range(1, cells_out + 1):\n neighbor_strength = 0\n # Are we currently moving? If not, we can add this to the strength\n if f.move == -1:\n # While we can check if f.move == STILL, it's likely that it's STILL for a reason and we don't want to cause conflicts.\n neighbor_strength += (f.strength + (f.production * distance_out))\n f_neighbors = [x for x in f.neighbors(distance_out) if x.owner == self.my_id]\n # This returns a list of ALL neighbors between 1 and distance_out inclusive.\n f_neighbors_minus_one = []\n if distance_out > 1:\n f_neighbors_minus_one = [x for x in f.neighbors(distance_out - 1) if x.owner == self.my_id]\n f_neighbors_at_cells_out = list(set(f_neighbors) - set(f_neighbors_minus_one))\n # Ok, now we have a list of all cells AT distance_out and all cells LESS than distance_out\n # Why is this necessary? We only want to MOVE cells at distance_out and let all squares LESS than distance_out produce\n \n # Ok, first, check needed strength for all squares LESS than distance_out\n for f_n in f_neighbors_minus_one:\n if f_n.move == -1:\n neighbor_strength += f_n.strength + f_n.production * self.get_distance(f_n, f)\n # Now, check if moving neighbors will produce enough strength.\n needed_strength_at_cells_out = needed_strength - neighbor_strength\n for f_n in f_neighbors_at_cells_out:\n if f_n.move == -1:\n neighbor_strength += f_n.strength\n # Do we have enough strength?\n if neighbor_strength > needed_strength:\n # Yes! Let's move the outside squares towards f_n.\n f_neighbors_at_cells_out.sort(key = lambda x: x.strength, reverse = True)\n for f_n in f_neighbors_at_cells_out:\n if f_n.move == -1 and needed_strength_at_cells_out > 0:\n f_n.move_to_target(f, True) \n # There may be edge cases where we can't actually move to a square, or that it takes more turns than expected. Might need to make a new function that looks at distance through friendly squares\n needed_strength_at_cells_out -= f_n.strength\n moving_cells = True\n if f.move == -1:\n self.make_move(f, STILL)\n # Stop looking any further out\n break\n \n if moving_cells:\n # We've found something to attack this border square eventually, let's move to the next.\n break\n \n \n################\n# Square class # \n################\n\nclass Square:\n def __init__(self, game_map, x, y, owner, strength, production):\n self.game_map = game_map\n self.x = x\n self.y = y\n self.owner = owner\n self.strength = strength\n self.production = production\n self.move = -1\n self.target = None\n self.moving_here = []\n self._is_border = None\n self._is_npc_border = None\n self._influence_production_npc = None\n \n\n def make_move(self, direction):\n # This should ONLY be called through the GameMap make_move function. Calling this function directly may screw things up\n # Update this square's move\n # Have we set this square's move already?\n dx, dy = get_offset(direction)\n \n if self.move != -1:\n # Yes, let's reset information\n self.target.moving_here.remove(self)\n \n self.move = direction\n self.target = self.game_map.get_target(self, direction)\n self.target.moving_here.append(self)\n \n def neighbors(self, n = 1, include_self = False):\n # Returns a list containing all neighbors within n squares, excluding self unless include_self = True\n assert isinstance(include_self, bool)\n assert isinstance(n, int) and n > 0\n if n == 1:\n combos = ((0, -1), (1, 0), (0, 1), (-1, 0), (0, 0)) # N, E, S, W, STILL\n else:\n combos = ((dx, dy) for dy in range(-n, n+1) for dx in range(-n, n+1) if abs(dx) + abs(dy) <= n)\n return (self.game_map.squares[(self.x + dx) % self.game_map.width][(self.y + dy) % self.game_map.height] for dx, dy in combos if include_self or dx or dy)\n \n def is_border(self):\n # looks at a square and sees if it's a border.\n # Looks at all neighbors and see if the owner != my_id\n # Have we done this calculation already? It shouldn't change within a frame\n if self._is_border == None:\n for n in self.neighbors():\n if n.owner != self.game_map.my_id:\n self._is_border = True\n return True\n self._is_border = False\n return self._is_border\n \n def is_npc_border(self):\n # Looks at a square and sees if it's an NPC border square\n # Defined as a square which is owned by 0 and has a neighbor of my_id\n # Have we done this calculation already? It shouldn't change within a frame\n if self._is_npc_border == None:\n if self.owner != 0:\n self._is_npc_border = False\n return False\n for n in self.neighbors():\n if n.owner == self.game_map.my_id:\n self._is_npc_border = True\n return True\n self._is_npc_border = False\n return False\n return self._is_npc_border\n \n def move_to_target(self, destination, through_friendly):\n dist_w = (self.x - destination.x) % self.game_map.width\n dist_e = (destination.x - self.x) % self.game_map.width\n dist_n = (self.y - destination.y) % self.game_map.height\n dist_s = (destination.y - self.y) % self.game_map.height\n\n if dist_w == 0 and dist_n == 0:\n return self.game_map.make_move(self, STILL)\n \n # Prioritize in the following order:\n # 1: Move through OWN territory\n # 2: Move CLOSER to the destination\n # 3: Move through LOWER production square\n possible_moves = [] \n\n possible_moves.append((NORTH, self.game_map.owner_map[(self.x + 0) % self.game_map.width, (self.y - 1) % self.game_map.height] == self.game_map.my_id, dist_n if dist_n > 0 else 999, self.game_map.production_map[(self.x + 0) % self.game_map.width, (self.y - 1) % self.game_map.height]))\n possible_moves.append((SOUTH, self.game_map.owner_map[(self.x + 0) % self.game_map.width, (self.y + 1) % self.game_map.height] == self.game_map.my_id, dist_s if dist_s > 0 else 999, self.game_map.production_map[(self.x + 0) % self.game_map.width, (self.y + 1) % self.game_map.height]))\n possible_moves.append((EAST, self.game_map.owner_map[(self.x + 1) % self.game_map.width, (self.y + 0) % self.game_map.height] == self.game_map.my_id, dist_e if dist_e > 0 else 999, self.game_map.production_map[(self.x + 1) % self.game_map.width, (self.y + 0) % self.game_map.height]))\n possible_moves.append((WEST, self.game_map.owner_map[(self.x - 1) % self.game_map.width, (self.y + 0) % self.game_map.height] == self.game_map.my_id, dist_w if dist_w > 0 else 999, self.game_map.production_map[(self.x - 1) % self.game_map.width, (self.y + 0) % self.game_map.height]))\n\n # Sort. Note sorts need to happen in reverse order of priority.\n random.shuffle(possible_moves) # Shuffle so we don't bias direction.\n possible_moves.sort(key = lambda x: x[3]) # Sort production, smaller is better\n possible_moves.sort(key = lambda x: x[2]) # Sort distance, smaller is better\n if through_friendly:\n possible_moves.sort(key = lambda x: x[1], reverse = True) # Sort owner, True = 1, False = 0\n #logging.debug(str(possible_moves))\n # The smallest move is the one we'll take.\n self.game_map.make_move(self, possible_moves[0][0]) \n \n def influence_production_npc(self):\n # So that we don't have to calculate the entire map every tick, and to prevent recalcs, calculate and store into the square so we can reference it whenever we want\n # Lots of tweaking to do.\n if self._influence_production_npc == None:\n self._influence_production_npc = 0\n if self.owner == 0:\n # I think for any purpose we would use here, if we own the territory, we don't actually care about this value\n return self._influence_production_npc\n \n neighbors = self.neighbors(production_influence_max_distance, True)\n \n for n in neighbors:\n distance = self.game_map.get_distance(self, n)\n prod_n = n.production\n if n.owner == 0:\n str_value = max(1, n.strength)\n elif n.owner == self.game_map.my_id:\n # Do not assign any influence for cells we own\n prod_n = 0\n str_value = 1 # This doesn't matter i think since value will just equal 0\n else:\n # If we want to do something differently with strengths in enemy terrotiry, we can alter it here.\n str_value = max(1, n.strength)\n \n decay_factor = math.exp(-production_decay * distance)\n value = prod_n / str_value\n \n self._influence_production_npc += value * decay_factor\n \n return self._influence_production_npc\n \n \n####################\n# Helper Functions #\n####################\n\ndef get_offset(direction):\n return ((0, -1), (1, 0), (0, 1), (-1, 0), (0, 0))[direction]\n \ndef distance_between(x1, y1, x2, y2):\n dx = abs(x1 - x2)\n dy = abs(y1 - y2)\n if dx > game_map.width / 2:\n dx = game_map.width - dx\n if dy > game_map.height / 2:\n dy = game_map.height - dy\n return dx + dy\n \ndef opposite_direction(direction):\n return (direction + 2) % 4 if direction != STILL else STILL\n\n########################\n# Core logic functions # \n########################\n\ndef heuristic(cell, source = None):\n\n # Currently, don't assign any value to moving into a friendly cell. This should be done through a different call.\n if cell.owner == game_map.my_id:\n return 0\n \n # If other cells are moving into this square, we don't want to duplicate effort. Especially if there are no enemy cells around\n other_cells_moving_into_cell = cell.moving_here\n cell_neighbors = cell.neighbors()\n\n bordered_by_hostile = False\n \n for c in cell_neighbors:\n if c.owner != 0:\n bordered_by_hostile = True\n \n if len(other_cells_moving_into_cell) > 0 and not bordered_by_hostile:\n # Someone else is capturing this neutral territory already.\n return 0\n \n # Calculate how much attack damage we would do by moving into here (assumes everyone else stays still)\n total_damage = 0\n \n # Calculate the strength of other cells moving into here\n total_attack_strength = 0\n for c in other_cells_moving_into_cell:\n if c.owner == game_map.my_id:\n total_attack_strength += c.strength\n \n directions = [NORTH, EAST, SOUTH, WEST]\n for d in directions:\n target = game_map.get_target(cell, d)\n if target.owner != 0 and target.owner != game_map.my_id:\n damage = max(target.strength - total_attack_strength, 0)\n if source != None:\n damage = min(source.strength, damage)\n total_damage += damage\n\n value = 0 \n neighbor_values = []\n if cell.owner == 0:\n #value = max(1, cell.strength) / cell.production # Number of turns to recover. LOWER is better.\n production_value = cell.production / max(cell.strength, 1)\n for c in cell_neighbors:\n if c.owner == 0:\n neighbor_values.append(c.production / max(c.strength, 1))\n value = production_value + 0.1 * sum(neighbor_values)\n \n # This should be changed, but we'll keep it at this for now:\n \n return value + total_damage # Total damage is going to totally overpower value...\n\n\n\n\n#############\n# Game Loop #\n#############\ndef game_loop():\n \n game_map.get_frame()\n #game_map.create_production_influence_map()\n logging.debug(\"\\nFrame: \" + str(game_map.frame))\n # Have each individual square decide on their own movement\n square_move_list = []\n for square in game_map:\n if square.owner == game_map.my_id: \n square_move_list.append(square)\n # Have smaller strength pieces move first. Mainly since otherwise especially for attacking, large pieces bounce back and forth when we want them to attack instead.\n square_move_list.sort(key = lambda x: x.strength) \n #percent_owned = len(square_move_list) / (game_map.width * game_map.height)\n\n for square in square_move_list:\n game_map.get_best_move(square)\n # Project the state of the board assuming for now that enemy pieces do not move \n #game_map.create_projection() \n # Do stuff\n\n #game_map.attack_border_multiple_pieces()\n #consolidate_strength()\n #if game_map.frame < 10:\n # consolidate_strength(3)\n #elif game_map.frame < 20:\n # consolidate_strength(2)\n #elif game_map.frame < 40:\n #game_map.consolidate_strength(1)\n \n over_count = game_map.width * game_map.height\n \n #new_over_count = game_map.prevent_overstrength()\n \n #while new_over_count < over_count:\n # over_count = new_over_count\n # new_over_count = game_map.prevent_overstrength()\n \n game_map.send_frame()\n\n\n\n\n#####################################################################################################################\n# Functions for communicating with the Halite game environment (formerly contained in separate module networking.py #\n#####################################################################################################################\n\ndef translate_cardinal(direction):\n # Cardinal index used by the framework is:\n # NORTH = 0, EAST = 1, SOUTH = 2, WEST = 3, STILL = 4\n # Cardinal index used by the game is:\n # STILL = 0, NORTH = 1, EAST = 2, SOUTH = 3, WEST = 4\n return int((direction + 1) % 5)\n\ndef send_string(to_be_sent):\n sys.stdout.write(to_be_sent + \"\\n\")\n sys.stdout.flush()\n\ndef get_string():\n return sys.stdin.readline().rstrip('\\n')\n\n\n######################\n# Game run-time code #\n######################\n\nlogging.basicConfig(filename='logging.log',level=logging.DEBUG)\n# logging.debug('your message here')\nNORTH, EAST, SOUTH, WEST, STILL = range(5)\n\n\ngame_map = GameMap()\n\nwhile True:\n game_loop()\n \n \n \n \n \n \n \n ","sub_path":"docker/shummie/Bots/shummiev7-7.py","file_name":"shummiev7-7.py","file_ext":"py","file_size_in_byte":34308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"483933818","text":"# -*- coding: utf-8 -*-\nfrom django.core.management.base import BaseCommand, CommandError\nfrom tvb.models import Forum81Item\n\nimport requests\nimport re\nfrom datetime import date\n\nclass Command(BaseCommand):\n args = ' '\n help = 'Download an from the thread.'\n\n def handle(self, *args, **options):\n if len(args) != 2:\n self.stdout.write(\"Specify 2 arguments: \")\n quit()\n\n thread = args[0]\n episode = int(args[1])\n\n originalUrl = 'http://www.tvboxnow.com/%s' % thread\n loginUrl = 'http://www.tvboxnow.com/logging.php?action=login&loginsubmit=yes'\n\n session = requests.Session()\n postdata = {'password':'abc123', 'username':'lordgul'}\n res = session.post(loginUrl, data=postdata, headers={'referer':originalUrl})\n res = session.get(originalUrl, headers={'referer':loginUrl})\n res.encoding = 'utf-8'\n #print >>open(newsThread+'.debug', 'w'), res.text.encode('utf-8')\n lines = res.text.encode('utf-8').split('\\n')\n for line in lines:\n #if today in line:\n if re.search('%d\\.torrent' % episode, line):\n if re.search('DIVX', line):\n continue\n m = re.search('a href=\\\"(.*?)\\\"', line)\n if m:\n attach = m.group(1)\n break\n\n #attach = \"attachment.php?aid=3044607&k=7110c105d6f63d6fde2249ce295d0234&t=1424300372&fid=497&sid=e986eAA1gE2VIt23Bf3grtN%2BzV1QW6PpNUT0AN9WWcgzXxk\"\n\n res = session.get('http://www.tvboxnow.com/%s' % attach,\n headers={'referer':originalUrl})\n res.encoding = 'utf-8'\n #print >>open('attach.debug', 'w'), res.text.encode('utf-8')\n lines = res.text.encode('utf-8').split('\\n')\n for line in lines:\n if 'window.location.href' in line:\n m = re.search('window.location.href =\\'(.*?)\\'', line)\n if m:\n attach2 = m.group(1)\n break\n\n #attach2 = \"attachment.php?aid=3044607&k=6d08894a1401dbcaed228810df69b923&t=1424300529&ck=75275fec&sid=eb69a4mAPMfsfN7MXQKrYCzaoNwJX4IE%2BiONdlm98dg3%2F%2BU\"\n\n\n misc = res.url\n res = session.get('http://www.tvboxnow.com/%s' % attach2,\n headers={'referer':misc}, stream=True)\n with open(\"%s-%d.torrent\" % (thread, episode), \"wb\") as f:\n for chunk in res.iter_content():\n f.write(chunk)\n\n","sub_path":"frontend/tvb/management/commands/getepisode.py","file_name":"getepisode.py","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"53615097","text":"import asyncio\nfrom apscheduler.schedulers.asyncio import AsyncIOScheduler\nimport discord\nimport feedparser\n\n\n # channel = self.get_channel(232917647250030592)\n\nclass Crisis:\n \"\"\"Parses krisinformationen.se for new crisis in Sweden\"\"\"\n def __init__(self, bot):\n self.bot = bot\n self.scheduler = AsyncIOScheduler()\n self.scheduler.add_job(self.at_time, 'cron', minute=40)\n self.scheduler.start()\n self.path = \"/root/discord-bot/\"\n self.id_log = self.path + \"data/crisis.log\"\n\n def check_log(self, entry):\n \"\"\"Checks if string exists in the log file\"\"\"\n with open(self.id_log, \"r+\") as file:\n for line in file:\n if entry in line.split():\n return True\n return False\n\n def string_to_log(self, entry):\n \"\"\"Adds the string to the log file\"\"\"\n with open(self.id_log, \"a\") as file:\n file.write(entry + \"\\n\")\n\n async def at_time(self):\n \"\"\"Parses krisinformationen and sends the informationen to the discord channel\"\"\"\n channel = self.bot.get_channel(232917647250030592)\n feed = feedparser.parse(\"http://api.krisinformation.se/v1/feed?format=xml\")\n suffix = \"en?format=xml\"\n for entry in feed.entries:\n if entry.id.endswith(suffix):\n break\n else:\n if not self.check_log(entry.id):\n text = entry.title + \"\\n\" + entry.summary # + \"\\n\" + entry.link\n self.string_to_log(entry.id)\n await channel.send(\"```\" + text + \"```\")\n\ndef setup(bot):\n bot.add_cog(Crisis(bot))\n","sub_path":"cogs/crisis.py","file_name":"crisis.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"482234139","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"HSCPAnalysis\")\n\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\nprocess.load(\"Configuration.StandardSequences.Geometry_cff\")\nprocess.load(\"Configuration.StandardSequences.MagneticField_AutoFromDBCurrent_cff\")\nprocess.load(\"Configuration.StandardSequences.FrontierConditions_GlobalTag_cff\")\n\nprocess.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) )\n\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(1000) )\n\nprocess.GlobalTag.globaltag = 'GR_P_V14::All'\n\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(\n '/store/data/Run2011B/MET/USER/EXOHSCP-PromptSkim-v1/0000/F6FA7586-9B02-E111-B438-001A92810AEC.root'\n# '/store/data/Run2011A/SingleMu/USER/EXOHSCP-05Aug2011-v1/0000/FC150FF5-0FC5-E011-913E-002618943876.root',\n# '/store/data/Run2011A/SingleMu/USER/EXOHSCP-05Aug2011-v1/0000/FA8B74F8-0FC5-E011-9EE5-001A928116B4.root',\n# '/store/data/Run2011A/SingleMu/USER/EXOHSCP-05Aug2011-v1/0000/FA432D78-CEC5-E011-B4F3-00261894394F.root'\n )\n)\nprocess.source.inputCommands = cms.untracked.vstring(\"keep *\", \"drop *_MEtoEDMConverter_*_*\")\n\n\n\n########################################################################\nprocess.load('SUSYBSMAnalysis.Skimming.EXOHSCP_cff')\nprocess.load(\"SUSYBSMAnalysis.HSCP.HSCParticleProducerFromSkim_cff\") #IF RUNNING ON HSCP SKIM\nprocess.load(\"SUSYBSMAnalysis.HSCP.HSCPTreeBuilder_cff\")\n\n######################################################################## INCREASING HSCP TRIGGER TRESHOLD FOR OLD DATA\n\nprocess.HSCPHLTFilter = cms.EDFilter(\"HSCPHLTFilter\",\n TriggerProcess = cms.string(\"HLT\"),\n RemoveDuplicates = cms.bool(False),\n MuonTrigger1Mask = cms.int32(1), #Activated\n PFMetTriggerMask = cms.int32(0), #Deactivated\n)\n\n######################################################################## SPECIAL CASE FOR DATA\n\nprocess.GlobalTag.toGet = cms.VPSet(\n cms.PSet( record = cms.string('SiStripDeDxMip_3D_Rcd'),\n tag = cms.string('Data7TeV_Deco_3D_Rcd_38X'),\n connect = cms.untracked.string(\"sqlite_file:Data7TeV_Deco_SiStripDeDxMip_3D_Rcd.db\")),\n)\n\nprocess.load(\"RecoLocalMuon.DTSegment.dt4DSegments_MTPatternReco4D_LinearDriftFromDBLoose_cfi\")\nprocess.dt4DSegments.Reco4DAlgoConfig.Reco2DAlgoConfig.AlphaMaxPhi = 1.0\nprocess.dt4DSegments.Reco4DAlgoConfig.Reco2DAlgoConfig.AlphaMaxTheta = 0.9\nprocess.dt4DSegments.Reco4DAlgoConfig.Reco2DAlgoConfig.segmCleanerMode = 2\nprocess.dt4DSegments.Reco4DAlgoConfig.Reco2DAlgoConfig.MaxChi2 = 1.0\nprocess.dt4DSegmentsMT = process.dt4DSegments.clone()\nprocess.dt4DSegmentsMT.Reco4DAlgoConfig.recAlgoConfig.stepTwoFromDigi = True\nprocess.dt4DSegmentsMT.Reco4DAlgoConfig.Reco2DAlgoConfig.recAlgoConfig.stepTwoFromDigi = True\n\nprocess.muontiming.TimingFillerParameters.DTTimingParameters.MatchParameters.DTsegments = \"dt4DSegmentsMT\"\nprocess.muontiming.TimingFillerParameters.DTTimingParameters.HitsMin = 3\nprocess.muontiming.TimingFillerParameters.DTTimingParameters.RequireBothProjections = False\nprocess.muontiming.TimingFillerParameters.DTTimingParameters.DropTheta = True\nprocess.muontiming.TimingFillerParameters.DTTimingParameters.DoWireCorr = True\nprocess.muontiming.TimingFillerParameters.DTTimingParameters.MatchParameters.DTradius = 1.0\n\n\n########################################################################\nprocess.nEventsBefEDM = cms.EDProducer(\"EventCountProducer\")\n########################################################################\n\nprocess.Out = cms.OutputModule(\"PoolOutputModule\",\n outputCommands = cms.untracked.vstring(\n \"drop *\",\n 'keep EventAux_*_*_*',\n 'keep LumiSummary_*_*_*',\n 'keep edmMergeableCounter_*_*_*',\n \"keep *_genParticles_*_*\",\n \"keep GenEventInfoProduct_generator_*_*\",\n \"keep *_offlinePrimaryVertices_*_*\",\n #\"keep *_cscSegments_*_*\",\n #\"keep *_rpcRecHits_*_*\",\n #\"keep *_dt4DSegments_*_*\",\n \"keep SiStripClusteredmNewDetSetVector_generalTracksSkim_*_*\",\n \"keep SiPixelClusteredmNewDetSetVector_generalTracksSkim_*_*\",\n #\"keep *_reducedHSCPhbhereco_*_*\", #\n #\"keep *_reducedHSCPEcalRecHitsEB_*_*\", #\n #\"keep *_reducedHSCPEcalRecHitsEE_*_*\", #\n \"keep *_TrackRefitter_*_*\",\n \"drop TrajectorysToOnerecoTracksAssociation_TrackRefitter__\",\n \"keep *_standAloneMuons_*_*\",\n \"drop recoTracks_standAloneMuons__*\",\n \"keep *_globalMuons_*_*\", #\n \"keep *_muonsSkim_*_*\",\n \"keep edmTriggerResults_TriggerResults_*_*\",\n \"keep recoPFJets_ak5PFJets__*\", #\n \"keep recoPFMETs_pfMet__*\", #\n \"keep *_HSCParticleProducer_*_*\",\n \"keep *_HSCPIsolation01__*\",\n \"keep *_HSCPIsolation03__*\",\n \"keep *_HSCPIsolation05__*\",\n \"keep *_dedx*_*_HSCPAnalysis\",\n \"keep *_muontiming_*_HSCPAnalysis\",\n \"keep triggerTriggerEvent_hltTriggerSummaryAOD_*_*\",\n ),\n fileName = cms.untracked.string('HSCP.root'),\n SelectEvents = cms.untracked.PSet(\n SelectEvents = cms.vstring('p1')\n ),\n)\n\nfrom CondCore.DBCommon.CondDBSetup_cfi import CondDBSetup \nprocess.tTrigDB = cms.ESSource(\"PoolDBESSource\",\n CondDBSetup,\n timetype = cms.string('runnumber'),\n toGet = cms.VPSet(cms.PSet(\n record = cms.string('DTTtrigRcd'),\n tag = cms.string('DTTtrig_offline_prep_V03'),\n label = cms.untracked.string('')\n )),\n connect = cms.string('frontier://FrontierPrep/CMS_COND_DT'),\n authenticationMethod = cms.untracked.uint32(0)\n )\n#process.tTrigDB.DBParameters.authenticationPath = '/afs/cern.ch/cms/DB/conddb'\nprocess.es_prefer_tTrigDB = cms.ESPrefer('PoolDBESSource','tTrigDB')\n\nprocess.vDriftDB = cms.ESSource(\"PoolDBESSource\",\n CondDBSetup,\n timetype = cms.string('runnumber'),\n toGet = cms.VPSet(cms.PSet(\n record = cms.string('DTMtimeRcd'),\n tag = cms.string('DTVdrift_offline_prep_V03'),\n label = cms.untracked.string('')\n )),\n connect = cms.string('frontier://FrontierPrep/CMS_COND_DT'),\n authenticationMethod = cms.untracked.uint32(0)\n )\n#process.vDriftDB.DBParameters.authenticationPath = '/afs/cern.ch/cms/DB/conddb'\nprocess.es_prefer_vDriftDB = cms.ESPrefer('PoolDBESSource','vDriftDB')\n\n########################################################################\n\n\n#LOOK AT SD PASSED PATH IN ORDER to avoid as much as possible duplicated events (make the merging of .root file faster)\nprocess.p1 = cms.Path(process.nEventsBefEDM * process.HSCPHLTFilter * process.dt4DSegmentsMT * process.HSCParticleProducerSeq)\n#process.p1 = cms.Path(process.HSCParticleProducerSeq)\nprocess.endPath1 = cms.EndPath(process.Out)\nprocess.schedule = cms.Schedule( process.p1, process.endPath1)\n\n\n","sub_path":"SUSYBSMAnalysis/HSCP/test/BuildHSCParticles/Data/HSCParticleProducer_cfg.py","file_name":"HSCParticleProducer_cfg.py","file_ext":"py","file_size_in_byte":7449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"47646192","text":"from __future__ import print_function\nfrom ortools.sat.python import cp_model\n\n\ndef main():\n # Instantiate a cp model.\n node_cpu = [2, 3, 5, 1]\n\n task_cpu = [2, 3, 2, 2, 1]\n\n num_nodes = len(node_cpu)\n num_tasks = len(task_cpu)\n\n all_nodes = range(num_nodes)\n all_tasks = range(num_tasks)\n\n model = cp_model.CpModel()\n # Variables\n x = []\n for i in all_nodes:\n t = []\n for j in all_tasks:\n t.append(model.NewBoolVar('x[%i,%i]' % (i, j)))\n x.append(t)\n\n # Constraints\n\n # Each task is assigned to exactly one worker.\n [model.Add(sum(x[i][j] for i in all_nodes) == 1) for j in all_tasks]\n\n # Each node is not overcommitted\n for i in all_nodes:\n model.Add(sum(task_cpu[j] * x[i][j]\n for j in all_tasks) <= node_cpu[i])\n\n # Objective: overall idle resources\n idle_cpu = model.NewIntVar(\n 0, sum(node_cpu[i] for i in all_nodes), 'idle_cpu')\n model.Add(idle_cpu == sum(node_cpu[i] for i in all_nodes) - sum(x[i][j] * task_cpu[j]\n for j in all_tasks for i in all_nodes))\n model.Maximize(idle_cpu)\n\n solver = cp_model.CpSolver()\n status = solver.Solve(model)\n\n if status == cp_model.OPTIMAL:\n print('Total idle resources = %i' % solver.ObjectiveValue())\n print()\n for i in all_nodes:\n print('Worker ', i, ':')\n for j in all_tasks:\n if solver.Value(x[i][j]) == 1:\n print('- task ', j)\n print()\n\n print()\n\n print(solver.ResponseStats())\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"misc/ortools/ortools-test.py","file_name":"ortools-test.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"302094707","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# share_file.py\n# \n# Copyright 2012 Emil \n# \n\nfile_types = frozenset(['good', 'bad', 'empty'])\n\nclass ShareFile:\n \n def __init__(self, content):\n \n assert content in file_types\n \n self.content = content\n \n return\n\n","sub_path":"share_file.py","file_name":"share_file.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"335788772","text":"import zipfile\r\nimport os\r\nimport shutil\r\n\r\nAPCSPATH = \"C:\\\\Users\\\\mlgpr\\\\Desktop\\\\APCS\"\r\n\r\ndef zipfolder(foldername):\r\n shutil.make_archive(\"temp\",\"zip\",APCSPATH+\"\\\\\"+foldername)\r\n\r\ndef getFolder():\r\n folders = [name for name in os.listdir(APCSPATH)]\r\n count = 1\r\n for folder in folders:\r\n print(f\"{count}: {folder}\")\r\n count+=1\r\n return folders[int(input(\"Enter selection :: \"))-1]\r\n\r\ndef delTemp():\r\n os.remove(\"temp.zip\")\r\n\r\nusrfolder = getFolder()\r\nzipfolder(usrfolder)\r\n","sub_path":"attachLabAutomation/attachlabs.py","file_name":"attachlabs.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"542836994","text":"number = 24\n\ndef solution(N):\n # write your code in Python 3.6\n i, result = 1, 0\n while (i * i < N):\n if (N % i == 0):\n result += 2\n i += 1\n if (i * i == N):\n result += 1\n return result\n\nprint(solution(number))","sub_path":"Lesson 10.1.py","file_name":"Lesson 10.1.py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"500782386","text":"# -*- coding: utf-8 -*- #\n# Copyright 2015 Google LLC. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Triggers execution of a Google Cloud Function.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nimport json\n\nfrom googlecloudsdk.api_lib.functions import util\nfrom googlecloudsdk.calliope import base\nfrom googlecloudsdk.calliope import exceptions\nfrom googlecloudsdk.command_lib.functions import flags\n\nimport six\n\n\nclass Call(base.Command):\n \"\"\"Trigger execution of a Google Cloud Function.\n\n ## EXAMPLES\n\n To call a function, giving it 'Hello World!' in the message field of its event\n argument (depending on your environment you might need to escape\n characters in `--data` flag value differently), run:\n\n $ {command} helloWorld --data='{\"message\": \"Hello World!\"}'\n\n \"\"\"\n\n @staticmethod\n def Args(parser):\n \"\"\"Register flags for this command.\"\"\"\n flags.AddFunctionResourceArg(parser, 'to execute')\n parser.add_argument(\n '--data',\n help='JSON string with data that will be passed to the function.')\n\n @util.CatchHTTPErrorRaiseHTTPException\n def Run(self, args):\n \"\"\"This is what gets called when the user runs this command.\n\n Args:\n args: an argparse namespace. All the arguments that were provided to this\n command invocation.\n\n Returns:\n Function call results (error or result with execution id)\n \"\"\"\n if args.data:\n try:\n json.loads(args.data)\n except ValueError as e:\n raise exceptions.InvalidArgumentException(\n '--data', 'Is not a valid JSON: ' + six.text_type(e))\n client = util.GetApiClientInstance()\n function_ref = args.CONCEPTS.name.Parse()\n # Do not retry calling function - most likely user want to know that the\n # call failed and debug.\n client.projects_locations_functions.client.num_retries = 0\n messages = client.MESSAGES_MODULE\n return client.projects_locations_functions.Call(\n messages.CloudfunctionsProjectsLocationsFunctionsCallRequest(\n name=function_ref.RelativeName(),\n callFunctionRequest=messages.CallFunctionRequest(data=args.data)))\n","sub_path":"google-cloud-sdk/lib/surface/functions/call.py","file_name":"call.py","file_ext":"py","file_size_in_byte":2714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"122873468","text":"import numpy as np\nimport pickle\n\ndata_path = '../data/profile_snapshots.dat'\noutput_dir = '../plots/theory/'\n\n\ndef average_replicas(data):\n het_global_averaged = np.zeros(data[1].shape[0])\n het_local_averaged = np.zeros(data[1].shape[0])\n replicas = 0\n for key in data.keys():\n het_global, het_local = calculate_heterozygosities(data[key])\n het_global_averaged += het_global\n het_local_averaged += het_local\n replicas += 1\n\n first_key = list(data.keys())[0]\n time, _, _ = separate_data(data[first_key])\n return time, het_global_averaged / replicas, het_local_averaged / replicas\n\n\ndef calculate_heterozygosities(profile):\n t_array, n1_array, n2_array = separate_data(profile)\n het_global = het_global_average(n1_array, n2_array)\n f_array = calculate_f(n1_array, n2_array)\n het_local = het_local_average(f_array, n1_array + n2_array)\n return het_global, het_local\n\ndef separate_data(profile):\n t_list = []\n n1_list = []\n n2_list = []\n for snapshot in profile:\n t_list.append(snapshot[0])\n n1_list.append([])\n n2_list.append([])\n\n for i in range(1, len(snapshot), 2):\n n1_list[-1].append(snapshot[i])\n n2_list[-1].append(snapshot[i + 1])\n return np.array(t_list), np.array(n1_list), np.array(n2_list)\n\ndef calculate_f(n1_array, n2_array):\n n_array = n1_array + n2_array\n f_array = np.zeros(n_array.shape)\n non_zero = np.where(n_array > 0)\n f_array[non_zero] = n1_array[non_zero] / n_array[non_zero]\n return f_array\n\ndef het_global_average(n1_array, n2_array):\n n1_total = np.sum(n1_array, axis=1)\n n_total = np.sum(n1_array + n2_array, axis=1)\n f_global = n1_total / n_total\n return 2 * f_global * (1 - f_global)\n\ndef het_local_average(f_array, n_array):\n f_average = []\n for i, n in enumerate(n_array):\n f_average.append(np.mean(f_array[i][np.where(n > 0)[0]]))\n f_average = np.array(f_average)\n return 2 * f_average * (1 - f_average)\n\nif __name__ == '__main__':\n with open(data_path, 'rb') as f_in:\n data = pickle.load(f_in)\n calculate_heterozygosities(data[1])\n time, het_global_averaged, het_local_averaged = average_replicas(data)\n het_averaged = {'time':time, 'global':het_global_averaged, 'local':het_local_averaged}\n\n with open('../data/het_average.dat', 'wb') as f_out:\n pickle.dump(het_averaged, f_out)\n","sub_path":"scripts/average_heterozygosities.py","file_name":"average_heterozygosities.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"536987127","text":"\n\ndef quicksort(list):\n if len(list) < 2:\n return list\n tmp = list[0]\n less = [x for x in list[1:] if x <= tmp]\n more = [x for x in list[1:] if x > tmp]\n return quicksort(less) + [tmp] + quicksort(more)\n\nquicksort([6,5,4,2,1])","sub_path":"algorithm/my_quicksort_0615.py","file_name":"my_quicksort_0615.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"106122882","text":"class Solution:\n def findKthPositive(self, arr: List[int], k: int) -> int:\n missingNumbersLength, lastMissedNumber = 0, 0\n number, i = 1, 0\n while missingNumbersLength < k:\n if i < len(arr) and number == arr[i]:\n number += 1\n i += 1\n else:\n lastMissedNumber = number\n missingNumbersLength += 1\n number += 1\n return lastMissedNumber","sub_path":"LeetCode/Kth Missing Positive Number.py","file_name":"Kth Missing Positive Number.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"517045916","text":"#!/usr/bin/env python3\n\n\"\"\"\nApple EFI Split\nApple EFI IM4P Splitter\nCopyright (C) 2018-2019 Plato Mavropoulos\n\"\"\"\n\nprint('Apple EFI IM4P Splitter v1.3')\n\nimport os\nimport re\nimport sys\n\nim4p = re.compile(br'\\x16\\x04\\x49\\x4D\\x34\\x50\\x16\\x04') # Apple IM4P\nifd = re.compile(br'\\x5A\\xA5\\xF0\\x0F.{172}\\xFF{16}', re.DOTALL) # Intel Flash Descriptor\n\n# Get input catalog file paths\nif len(sys.argv) >= 3 and sys.argv[1] == '-skip' :\n\t# Called via Apple_EFI_Package\n\tapple_im4p = sys.argv[2:]\n\tskip_pause = True\nelif len(sys.argv) >= 2 :\n\t# Drag & Drop or CLI\n\tapple_im4p = sys.argv[1:]\n\tskip_pause = False\nelse :\n\t# Folder path\n\tapple_im4p = []\n\tskip_pause = False\n\tin_path = input('\\nEnter the full folder path: ')\n\tprint('\\nWorking...')\n\tfor root, dirs, files in os.walk(in_path):\n\t\tfor name in files :\n\t\t\tapple_im4p.append(os.path.join(root, name))\n\nfor input_file in apple_im4p :\n\tfile_path = os.path.abspath(input_file)\n\tfile_name = os.path.basename(input_file)\n\tfile_dir = os.path.dirname(file_path)\n\tfile_ext = os.path.splitext(file_path)[1]\n\t\n\tprint('\\nFile: %s%s' % (file_name, file_ext))\n\t\n\t# Must be IM4P file because its size is 0x0 dependent\n\tif file_ext not in ('.im4p','.IM4P') :\n\t\tprint('\\n Error: Could not find IM4P file extension at %s!' % file_name)\n\t\tcontinue\n\t\n\twith open(input_file, 'rb') as in_file : buffer = in_file.read()\n\t\n\tis_im4p = im4p.search(buffer) # Detect IM4P pattern\n\t\n\tif not is_im4p :\n\t\tprint('\\n Error: Could not find IM4P pattern at %s!' % file_name)\n\t\tcontinue\n\t\n\tim4p_size = int.from_bytes(buffer[2:is_im4p.start()], 'big') # Variable, from 0x2 - IM4P\n\tim4p_type = buffer[is_im4p.end():is_im4p.end() + 0x4].decode('utf-8') # mefi\n\t\n\tif im4p_type != 'mefi' :\n\t\tprint('\\n Error: Could not find \"mefi\" IM4P Type at %s!' % file_name)\n\t\tcontinue\n\t\n\tpayload_start = is_im4p.start() + buffer[is_im4p.start() - 0x1]\n\tpayload_size = int.from_bytes(buffer[is_im4p.end() + 0x9:is_im4p.end() + 0xD], 'big')\n\t\n\tifd_count = list(ifd.finditer(buffer)) # Count the Intel FD(s) to determine each SPI size and offset\n\t\n\t# After IM4P mefi (0x15), multi SPI payloads have _MEFIBIN (0x100, difficult to reverse without varying samples)\n\tspi_start = payload_start + 0x100 if buffer[payload_start:payload_start + 0x8] == b'_MEFIBIN' else payload_start\n\t\n\tspi_size = int(len(buffer[spi_start:]) / len(ifd_count)) # Each SPI should be of the same size (1st PRD, 2nd PRE)\n\t\n\t# Parse all Intel FD and extract each SPI image\n\tfor fd in range(len(ifd_count)) :\n\t\tfile_path_new = os.path.join(file_dir, '%s_%d.fd' % (file_name[:-5], fd + 1))\n\t\t\n\t\twith open(file_path_new, 'wb') as spi_image : spi_image.write(buffer[spi_start:spi_start + spi_size])\n\t\t\n\t\tspi_start += spi_size\n\t\t\n\tprint('\\n Split IM4P file into %d SPI/BIOS image(s)!' % len(ifd_count))\n\t\t\nif not skip_pause : input('\\nDone!')","sub_path":"Apple EFI IM4P Splitter/Apple_EFI_Split.py","file_name":"Apple_EFI_Split.py","file_ext":"py","file_size_in_byte":2816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"7063617","text":"# Simple Robot Program\nimport logging\nimport os\n\nfrom RobotMenu import RobotMenu\nfrom Movement import Movement\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\ndirectory = '/home/pi/logs'\n\nif not os.path.exists(directory):\n os.makedirs(directory)\n\nhandler = logging.FileHandler(directory + '/TurtleThoughts.log')\nhandler.setLevel(logging.INFO)\n\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nhandler.setFormatter(formatter)\n\nlogger.addHandler(handler)\n\nlogger.info('Started Run Robot')\n\nm = Movement(logger)\nr = RobotMenu(logger, m)\n\nr.execute()\n\nfrom Movement import Movement\nfrom DanceRoutines import DanceRoutines\nimport logging\n\nlogging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)\nlogger = logging.getLogger('basic')\n\n\nm = Movement('test')\nd = DanceRoutines(m, logger)","sub_path":"RunRobot.py","file_name":"RunRobot.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"498022149","text":"from django.urls import path\nfrom . import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path('', views.index),\n path('conversation', views.conversation),\n path('conversation/index', views.conversation),\n path('conversation/draft', views.drafts),\n path('conversation/sent', views.sent),\n path('conversation/trash', views.trash),\n path('conversation/create', views.creat_mail),\n path('user_role', views.user_roles),\n path('user_role/index', views.user_roles),\n path('user_role/add', views.add_role),\n path('user_role/delete/', views.delete_role),\n path('user_role/edit/', views.edit_role),\n path('user_role/update_role/', views.update_role),\n path('dashboard', views.dashboard),\n path('logout', views.logout),\n path('users/index', views.users),\n path('users', views.users),\n path('users/view/', views.view_user),\n path('users/edit/', views.edit_user),\n path('users/delete/', views.delete_user),\n path('users/add', views.add_user),\n path('api_settings', views.api_settings),\n path('api_settings/index', views.api_settings),\n path('api_settings/add', views.add_api),\n path('api_settings/edit/', views.edit_api),\n path('api_settings/delete/', views.delete_api),\n path('system_setting', views.system_setting),\n path('system_setting/index', views.system_setting),\n path('system_setting/edit/', views.system_setting_edit),\n path('tweets_gathering', views.tweets_gathering),\n path('twitter_users', views.twitter_users),\n path('twitter_users/view', views.view_profile),\n path('analysis', views.analysis),\n path('analysis_view', views.analysis_view),\n path('categorization', views.categorization),\n path('category_analysis', views.category_analysis),\n path('fake_users', views.faked_account)\n # path('tweets_gathering')\n ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"fyp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"545730529","text":"# This is the final version of the server program for the front unit\nfrom socket import *\nfrom errno import *\n\n# for decoding and displaying the image\nimport base64\nfrom PIL import Image, ImageTk\nimport tkinter\n\nfrom time import *\n\nimport signal\nimport sys\nimport subprocess\n\nimport RPi.GPIO as GPIO\n\n# ------------------\n# Defining Variables\n# ------------------\n\n# Set variables\nnoConnect = True # Boolean for stating connection of a client\nhasLost = False # Boolean for packet loss\nfrontLEDs = 0\nsettleSleep = 0.5\nmeasurementSleep = 0.00001\nMSS = 9999 # Max Segment Size\npicture = \"/home/pi/Capstone_Networking/test_decode.jpg\"\nlogo = \"/home/pi/Capstone_Networking/logo.jpg\"\nencode_string = []\ncheck_pt = 0 # where packets need to be checked for loss\ncp_value = 1 # SS/cp_value = num of packets sent per check\npacketsRec = [0] * MSS # stores packets that have been received\n\n# Dictionaries for Flag Values\ndictRec = {'0':\"INIT_SYN\",'1':\"INIT_SYNACK\",'2':\"INIT_ACK\",'3':\"FULL_DATA_SYN\",'4':\"FULL_DATA_ACK\",'5':\"SYNC_SYN\",'6':\"SYNC_ACK\",'7':\"DATA_SYN\",'8':\"DATA_ACK\",'9':\"DATA_CAM\",'A':\"DATA_SEN\",'B':\"MODE_SYN\",'C':\"MODE_ACK\", 'D':\"DCNT\"}\n\ndictSend = {\"INIT_SYN\":'0',\"INIT_SYNACK\":'1',\"INIT_ACK\":'2',\"FULL_DATA_SYN\":'3',\"FULL_DATA_ACK\":'4',\"SYNC_SYN\":'5',\"SYNC_ACK\":'6',\"DATA_SYN\":'7',\"DATA_ACK\":'8',\"DATA_CAM\":'9',\"DATA_SEN\":'A',\"MODE_SYN\":'B',\"MODE_ACK\":'C',\"DCNT\":'D'}\n\n# GPIO pins (BCM) and their purpose\nGPIO.setmode(GPIO.BCM)\nGPIO_MODE_SEL = 16\nGPIO_TRIGGER = 23\nGPIO_ECHO = 20\nGPIO_LEDS_RIGHT = 21\nGPIO_LEDS_LEFT = 27\nGPIO_LED_SEL0 = 2\nGPIO_LED_SEL1 = 14\nGPIO_LED_SEL2 = 4 #MSB\nGPIO_LED_EN = 17\nGPIO_LED_STAT = 11\nGPIO_SAFE_SD = 3\nGPIO_LBO = 26\n\n# Set pins as output and input\nGPIO.setup(GPIO_MODE_SEL,GPIO.IN)\nGPIO.setup(GPIO_TRIGGER,GPIO.OUT)\nGPIO.setup(GPIO_ECHO,GPIO.IN)\nGPIO.setup(GPIO_LEDS_RIGHT,GPIO.OUT)\nGPIO.setup(GPIO_LEDS_LEFT,GPIO.OUT)\nGPIO.setup(GPIO_LED_SEL0,GPIO.OUT)\nGPIO.setup(GPIO_LED_SEL1,GPIO.OUT)\nGPIO.setup(GPIO_LED_SEL2,GPIO.OUT)\nGPIO.setup(GPIO_LED_EN,GPIO.OUT)\nGPIO.setup(GPIO_LED_STAT, GPIO.OUT)\n\nGPIO.setup(GPIO_SAFE_SD, GPIO.IN, pull_up_down = GPIO.PUD_UP)\nGPIO.add_event_detect(GPIO_SAFE_SD, GPIO.FALLING)\n\nGPIO.setup(GPIO_LBO, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)\nGPIO.add_event_detect(GPIO_LBO, GPIO.RISING)\n\nGPIO.output(GPIO_TRIGGER,False)\nGPIO.output(GPIO_LEDS_RIGHT, False)\nGPIO.output(GPIO_LEDS_LEFT, False)\nGPIO.output(GPIO_LED_SEL0, False)\nGPIO.output(GPIO_LED_SEL1, False)\nGPIO.output(GPIO_LED_SEL2, False)\nGPIO.output(GPIO_LED_EN, False)\nGPIO.output(GPIO_LED_STAT, False)\n\n# ------------------\n# Defining Functions\n# ------------------\n\n# -----------------------------------------------\n# decode_string decodes the image from the client\n# -----------------------------------------------\ndef decode_string(image_64_encode):\n global encode_string\n encode_string = []\n image_64_decode = base64.decodestring(image_64_encode)\n with open(picture,'wb') as image_result:\n image_result.write(image_64_decode)\n update_image()\n\n# ----------------------------------------------\n# update_image: updates the image being displayed\n# ----------------------------------------------\ndef update_image():\n global camImg\n camImg = ImageTk.PhotoImage(Image.open(picture))\n label.config(image = camImg)\n label.pack()\n\n# ---------------------------------------------------------------------------\n# check_point: sends to client a data_ack indicating if there was packet loss\n# ---------------------------------------------------------------------------\ndef check_point(SegmentSize):\n global check_pt\n global packetsRec\n\n packet_dropped = -1\n for i in range (check_pt,(check_pt + (SegmentSize//cp_value))):\n if packetsRec[i] == 0:\n packet_dropped = i\n break\n\n # Sending DATA_ACK\n message = dictSend[\"DATA_ACK\"] + \",0001,0001,CAM!\" + str(packet_dropped)\n\n serverSocket.sendto(message.encode(),clientAddress)\n\n return packet_dropped\n\n# --------------------------------------------\n# splitData is used to split data based on '!'\n# --------------------------------------------\ndef splitData(data):\n data_decoded = data.decode()\n newData = data_decoded.split('!')\n data1 = newData[0]\n data2 = newData[1]\n\n return data1, data2\n\n# ------------------------------------------------\n# MeasureLidar takes measurement to nearest object\n# in front of the rider. Returns the distance to\n# that object\n# ------------------------------------------------\ndef MeasureLidar():\n # This function measures a distance\n GPIO.output(GPIO_TRIGGER, True)\n # Wait 10us\n sleep(measurementSleep)\n GPIO.output(GPIO_TRIGGER, False)\n start = time()\n\n while GPIO.input(GPIO_ECHO) == 0:\n start = time()\n\n while GPIO.input(GPIO_ECHO) == 1:\n stop = time()\n\n stop = time()\n\n elapsed = stop - start # every 10 microseconds = 1 cm\n distance = elapsed * (10 ** 5) # in cm\n distance = distance * 0.0328084 # in feet\n\n return distance\n\n# -----------------------------------------\n# UpdateLidar takes 'n' measurements and\n# sets the value for the number of LEDs to\n# be turned on.\n# -----------------------------------------\ndef UpdateLidar():\n global frontLEDs\n\n n = 3 # num of measurements taken\n\n listDist = []\n for i in range(0,n):\n listDist.append(MeasureLidar())\n\n last = listDist.pop()\n for d in listDist:\n\n if d < 12 and last < 12:\n frontLEDs = 8\n break\n elif d >= 12 and d < 24 and last >= 12 and last < 24:\n frontLEDs = 7\n break\n elif d >= 24 and d < 36 and last >= 24 and last < 36:\n frontLEDs = 6\n break\n elif d >= 36 and d < 48 and last >= 36 and last < 48:\n frontLEDs = 5\n break\n elif d >= 48 and d < 60 and last >= 48 and last < 60:\n frontLEDs = 4\n break\n elif d >= 60 and d < 72 and last >= 60 and last < 72:\n frontLEDs = 3\n break\n elif d >= 72 and d < 80 and last >= 72 and last < 80:\n frontLEDs = 2\n break\n elif d >= 80 and d < 100 and last >= 80 and last < 100:\n frontLEDs = 1\n break\n\ndef disconnect():\n print(\"Front Unit Shutting Down\")\n GPIO.cleanup()\n serverSocket.close()\n subprocess.call(['shutdown','-h','now'], shell=False)\n sys.exit(0)\n\n# ---------------\n# Main Script\n# ---------------\n\n# Allow for time for setting up GPIO\nsleep(settleSleep)\n\n# Setting up socket\nserver_port = 12000\nserverSocket = socket(AF_INET,SOCK_DGRAM)\nserverSocket.bind(('',server_port))\n\n# Setting up gui for displaying image\nw = tkinter.Tk()\nim = Image.open(logo)\ncamImg = ImageTk.PhotoImage(im)\nlabel = tkinter.Label(w,image=camImg)\nlabel.pack()\nw.update()\n\n# Setting the mode of the system\nloop_count = 0\ncolor = False\nwhile loop_count < 15:\n color = not color\n sleep(.1)\n loop_count = loop_count + 1\n\nif GPIO.input(GPIO_MODE_SEL):\n sys_mode = \"FB\"\nelse:\n sys_mode = \"BS\"\n\nloop_count = 0\nwhile loop_count < 150:\n if sys_mode == \"BS\":\n GPIO.output(GPIO_LED_STAT, False)\n sleep(.01)\n GPIO.output(GPIO_LED_STAT, True)\n sleep(.01)\n else:\n GPIO.output(GPIO_LED_STAT, True)\n sleep(.02)\n loop_count = loop_count + 1\n\nloop_count = 0\ncolor = False\nserverSocket.setblocking(False) # to allow for the loop to process\n# Initial Handshaking loop\nwhile noConnect:\n sleep(0.1)\n color = not color\n GPIO.output(GPIO_LED_STAT, color)\n try:\n message_rec = True\n response, clientAddress = serverSocket.recvfrom(2048)\n except error as e:\n if e.errno is 107 or e.errno is 11:\n message_rec = False\n if message_rec:\n\n splitPacket = response.split(b',')\n\n if dictRec[splitPacket[0].decode()] == \"INIT_SYN\":\n # send back INIT_SYNACK\n message = dictSend[\"INIT_SYNACK\"] + \",0001,0001,VOID\"\n\n serverSocket.sendto(message.encode(),clientAddress)\n elif dictRec[splitPacket[0].decode()] == \"INIT_ACK\":\n # Send back MODE_SYN\n message = dictSend[\"MODE_SYN\"] + \",0001,0001,\" + sys_mode\n serverSocket.sendto(message.encode(),clientAddress)\n\n noConnect = False\n message = \"Connected\"\n serverSocket.setblocking(True)\n # Wait for MODE_ACK, DATA = \"MODE\"\n response, clientAddress = serverSocket.recvfrom(2048)\n\n # send back FULL_DATA_ACK, DATA = \"MODE!VOID\"\n message = dictSend[\"FULL_DATA_ACK\"] + \",0001,0001,\" + sys_mode + \"!VOID\"\n serverSocket.sendto(message.encode(),clientAddress)\n\n elif dictRec[splitPacket[0].decode()] == \"DCNT\":\n disconnect()\n\nGPIO.setup(GPIO_LED_STAT, GPIO.IN)\nled_flag = False\n\n# begin loop\nwhile True:\n if led_flag:\n GPIO.setup(GPIO_LED_STAT, GPIO.OUT)\n GPIO.output(GPIO_LED_STAT, True)\n else:\n GPIO.setup(GPIO_LED_STAT, GPIO.IN)\n response, clientAddress = serverSocket.recvfrom(2048)\n splitPacket = response.split(b',')\n print(dictRec[splitPacket[0].decode()])\n\n if GPIO.event_detected(GPIO_SAFE_SD) or GPIO.event_detected(GPIO_LBO):\n message = dictSend[\"DCNT\"] + \",0001,0001,VOID\"\n serverSocket.sendto(message.encode(),clientAddress)\n disconnect()\n\n if dictRec[splitPacket[0].decode()] == \"FULL_DATA_SYN\":\n\n sys_mode,data_type = splitData(splitPacket[3])\n\n if data_type == \"CAM\":\n led_flag = not led_flag\n #reset values\n check_pt = 0\n packetsRec = [0] * MSS\n\n full_string = b''\n i = 0\n\n while(i < len(encode_string)):\n full_string = full_string + encode_string[i]\n i = i + 1\n\n decode_string(full_string)\n\n message = dictSend[\"FULL_DATA_ACK\"] + \",0001,0001,\" + sys_mode + \"!CAM\"\n serverSocket.sendto(message.encode(),clientAddress)\n elif data_type == \"SEN\":\n message = dictSend[\"FULL_DATA_ACK\"] + \",0001,0001,\" + sys_mode + \"!SEN\"\n serverSocket.sendto(message.encode(),clientAddress)\n\n elif dictRec[splitPacket[0].decode()] == \"SYNC_SYN\":\n\n data_type,SS = splitData(splitPacket[3])\n SegmentSize = int(SS)\n\n message = dictSend[\"SYNC_ACK\"] + \",0001,0001,\" + data_type + '!' + SS\n serverSocket.sendto(message.encode(), clientAddress)\n\n elif dictRec[splitPacket[0].decode()] == \"DATA_SYN\":\n\n data_type,other_data = splitData(splitPacket[3])\n\n if data_type == \"CAM\":\n #check for packet loss\n\n SegmentSize = int(other_data)\n\n packet_dropped = check_point(SegmentSize)\n\n if (packet_dropped == -1):\n hasLost = False\n check_pt = check_pt + (SegmentSize//cp_value)\n else:\n hasLost = True\n elif data_type == \"SEN\":\n message = dictSend[\"DATA_ACK\"] + \",0001,0001,SEN!VOID\"\n serverSocket.sendto(message.encode(), clientAddress)\n\n elif dictRec[splitPacket[0].decode()] == \"DATA_CAM\":\n\n SegmentSize = int(splitPacket[1])\n SegmentNum = int(splitPacket[2])\n\n packetsRec[SegmentNum] = 1\n\n # Append the encoded image data\n if (SegmentNum == len(encode_string) or hasLost == False):\n encode_string.append(splitPacket[3])\n else:\n encode_string[SegmentNum] = splitPacket[3]\n\n elif dictRec[splitPacket[0].decode()] == \"DATA_SEN\":\n # handle the sensor data\n LS,RS = splitData(splitPacket[3])\n\n UpdateLidar()\n\n if frontLEDs == 0:\n GPIO.output(GPIO_LED_SEL0, False)\n GPIO.output(GPIO_LED_SEL1, False)\n GPIO.output(GPIO_LED_SEL2, False)\n GPIO.output(GPIO_LED_EN, False)\n elif frontLEDs == 1:\n GPIO.output(GPIO_LED_SEL0, False)\n GPIO.output(GPIO_LED_SEL1, False)\n GPIO.output(GPIO_LED_SEL2, False)\n GPIO.output(GPIO_LED_EN, True)\n elif frontLEDs == 2:\n GPIO.output(GPIO_LED_SEL0, True)\n GPIO.output(GPIO_LED_SEL1, False)\n GPIO.output(GPIO_LED_SEL2, False)\n GPIO.output(GPIO_LED_EN, True)\n elif frontLEDs == 3:\n GPIO.output(GPIO_LED_SEL0, False)\n GPIO.output(GPIO_LED_SEL1, True)\n GPIO.output(GPIO_LED_SEL2, False)\n GPIO.output(GPIO_LED_EN, True)\n elif frontLEDs == 4:\n GPIO.output(GPIO_LED_SEL0, True)\n GPIO.output(GPIO_LED_SEL1, True)\n GPIO.output(GPIO_LED_SEL2, False)\n GPIO.output(GPIO_LED_EN, True)\n elif frontLEDs == 5:\n GPIO.output(GPIO_LED_SEL0, False)\n GPIO.output(GPIO_LED_SEL1, False)\n GPIO.output(GPIO_LED_SEL2, True)\n GPIO.output(GPIO_LED_EN, True)\n elif frontLEDs == 6:\n GPIO.output(GPIO_LED_SEL0, True)\n GPIO.output(GPIO_LED_SEL1, False)\n GPIO.output(GPIO_LED_SEL2, True)\n GPIO.output(GPIO_LED_EN, True)\n elif frontLEDs == 7:\n GPIO.output(GPIO_LED_SEL0, False)\n GPIO.output(GPIO_LED_SEL1, True)\n GPIO.output(GPIO_LED_SEL2, True)\n GPIO.output(GPIO_LED_EN, True)\n elif frontLEDs == 8:\n GPIO.output(GPIO_LED_SEL0, True)\n GPIO.output(GPIO_LED_SEL1, True)\n GPIO.output(GPIO_LED_SEL2, True)\n GPIO.output(GPIO_LED_EN, True)\n\n if RS == \"Y\":\n GPIO.output(GPIO_LEDS_RIGHT,True)\n else:\n GPIO.output(GPIO_LEDS_RIGHT,False)\n if LS == \"Y\":\n GPIO.output(GPIO_LEDS_LEFT,True)\n else:\n GPIO.output(GPIO_LEDS_LEFT,False)\n\n elif dictRec[splitPacket[0].decode()] == \"DCNT\":\n # Handle Disconnect from Client\n print(\"Handle DCNT\")\n disconnect()\n\n w.update()\n w.update_idletasks()\n","sub_path":"RP_Server.py","file_name":"RP_Server.py","file_ext":"py","file_size_in_byte":13976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"39547030","text":"# -----------------------------------------------------------------------------\n#\n# Copyright (C) 2021 CERN & Newcastle University for the benefit of the\n# BioDynaMo collaboration. 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#\n# See the LICENSE file distributed with this work for details.\n# See the NOTICE file distributed with this work for additional information\n# regarding copyright ownership.\n#\n# -----------------------------------------------------------------------------\n\nimport os, platform\nimport subprocess as sp\nfrom print_command import Print\nfrom build_command import BuildCommand\nfrom util import GetBinaryName\n\n\n## The BioDynaMo CLI command to run a simulation\n##\n## @param sim_name The simulation name\n##\ndef RunCommand(args, debug=False):\n sim_name = GetBinaryName()\n args_str = \" \".join(args)\n cmd = \"./build/\" + sim_name\n if platform.system() == \"Darwin\":\n launcher = os.environ[\"BDMSYS\"] + \"/bin/launcher.sh\"\n else:\n launcher = \"\"\n\n try:\n BuildCommand()\n Print.new_step(\"Run \" + sim_name + \" \" + args_str)\n if debug:\n sp.check_output(\n [launcher + \" \" + cmd, \"&>\", \"debug/runtime_output.log\"])\n else:\n print(\n sp.check_output([launcher + \" \" + cmd, args_str],\n stderr=sp.STDOUT,\n shell=True).decode(\"utf-8\"))\n Print.success(\"Finished successfully\")\n except sp.CalledProcessError as err:\n print(err.output.decode(\"utf-8\"))\n Print.error(\"Error during execution of {0}\".format(cmd))\n","sub_path":"cli/run_command.py","file_name":"run_command.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"535875661","text":"import urllib2\r\nimport xlrd\r\nimport json\r\nimport pandas as pd\r\nfrom datetime import datetime, timedelta, date\r\nimport calendar\r\nimport pprint\r\n\r\n#_JSON RESPONSE_\r\ndef clean_attribute_value(raw_value):\r\n # Sample raw_value = [u'Email not registered.']\r\n # Count the raw_value length, remove the first three and last two char to extract the message only\r\n return str(raw_value)[3:len(str(raw_value)) - 2]\r\n\r\ndef get_specific_nested_attribute_value(response, parent_attribute, child_attribute):\r\n return clean_attribute_value(json.loads(response)[parent_attribute][child_attribute])\r\n\r\ndef get_specific_data_attribute_value(response, attribute):\r\n return json.loads(response)['data'][attribute]\r\n\r\ndef store_json_response_data_as_dictionary(response):\r\n return json.loads(response)['data'][0]\r\n\r\ndef compare_dictionaries(actual_dictionary, expected_dictionary):\r\n d1_keys = set(actual_dictionary.keys())\r\n d2_keys = set(expected_dictionary.keys())\r\n intersect_keys = d1_keys.intersection(d2_keys)\r\n unexpected_actual = d1_keys - d2_keys\r\n missing_expected = d2_keys - d1_keys\r\n different_values = {o: (actual_dictionary[o], expected_dictionary[o]) for o in intersect_keys\r\n if actual_dictionary[o] !=expected_dictionary[o]}\r\n same_values = set(o for o in intersect_keys if actual_dictionary[o] == expected_dictionary[o])\r\n\r\n if not(unexpected_actual == set([])):\r\n raise ValueError('Unexpected actual attribute/s found: ', unexpected_actual)\r\n\r\n if not(missing_expected == set([])):\r\n raise ValueError('Missing expected attribute/s: ', missing_expected)\r\n\r\n if not(different_values == {}):\r\n raise ValueError('Actual and expected attribute values do not match: ', different_values)\r\n\r\n if not(len(same_values) == len(expected_dictionary)):\r\n raise ValueError('Only the following attributes matched: ', same_values)\r\n\r\ndef get_specific_nested_json_data_attribute(response, parent_attribute, child_attribute):\r\n return json.loads(response)['data'][parent_attribute][child_attribute]\r\n\r\ndef split_and_store_attribute_list(list):\r\n attribute_list = []\r\n attributes = list.split()\r\n for attribute in attributes:\r\n attribute_list.append(attribute)\r\n return attribute_list\r\n\r\ndef check_if_specific_data_key_exists(data, attribute_list, index):\r\n expected = str(attribute_list[index])\r\n found = False\r\n for key in data:\r\n if str(key) == expected:\r\n found = True\r\n if found == False:\r\n raise ValueError('Attribute ', expected, ' does not exist on the response!', data)\r\n\r\ndef check_if_specific_data_attribute_exists(data, attribute_list, index):\r\n expected = str(attribute_list[index])\r\n found = False\r\n\r\n if any(expected in key for key in data):\r\n found = True\r\n if found == False:\r\n raise ValueError('Attribute ', expected, ' does not exist on the response!', data)\r\n\r\ndef get_month_days_count(date_preset):\r\n if date_preset == \"last_month\":\r\n return str(calendar.monthrange(datetime.now().year,datetime.now().month-1)[1])\r\n elif date_preset == \"this_month\":\r\n return str(datetime.now().day)\r\n\r\ndef get_date_preset_count(date_preset):\r\n # switcher = {\r\n # \"today\": \"1\",\r\n # \"yesterday\": \"1\",\r\n # \"last_3d\": \"3\",\r\n # \"last_7d\": \"7\",\r\n # \"last_14d\": \"14\",\r\n # \"last_28d\": \"28\",\r\n # \"last_30d\": \"30\",\r\n # \"last_month\": get_month_days_count(date_preset),\r\n # \"this_month\": get_month_days_count(date_preset)\r\n # }\r\n # return switcher.get(date_preset, \"Invalid date preset!\")\r\n\r\n if date_preset == \"today\" or date_preset == \"yesterday\":\r\n return 1\r\n elif date_preset == \"last_3d\":\r\n return 3\r\n elif date_preset == \"last_7d\":\r\n return 7\r\n elif date_preset == \"last_14d\":\r\n return 14\r\n elif date_preset == \"last_28d\":\r\n return 28\r\n elif date_preset == \"last_30d\":\r\n return 30\r\n elif date_preset == \"last_month\":\r\n return get_month_days_count(date_preset)\r\n elif date_preset == \"this_month\":\r\n return get_month_days_count(date_preset)\r\n else:\r\n raise ValueError('Value ', date_preset, ' is not a valid date_preset!')\r\n\r\ndef loop_check_and_store_attributes(response, attribute_list, date_preset):\r\n date_preset_count = get_date_preset_count(str(date_preset.encode(\"utf-8\")))\r\n length = 1\r\n index = 0\r\n data = json.loads(response)['data']\r\n datetime_stamp_values = []\r\n kpi_values = []\r\n\r\n for count in range(0, int(date_preset_count)):\r\n while int(length) <= len(attribute_list):\r\n # check if each data attribute exists\r\n check_if_specific_data_attribute_exists(data, attribute_list, index)\r\n\r\n # get and store each attribute count\r\n datetime_stamp_values.append(json.loads(response)['data'][index]['datetime_stamp'])\r\n kpi_values.append(json.loads(response)['data'][index]['aggregated_likes_kpi_value'])\r\n\r\n length = length + 1\r\n index = index + 1\r\n return date_preset_count, datetime_stamp_values, kpi_values\r\n\r\ndef daterange(date1, date2):\r\n for n in range(int((date2 - date1).days) + 1):\r\n yield date1 + timedelta(n)\r\n\r\ndef get_last_month_or_this_month_days_list(date_preset, current_month):\r\n expected_datetime_list = []\r\n # get number of days\r\n if date_preset == \"last_month\":\r\n month_count = current_month - 1\r\n total_days_count = calendar.monthrange(datetime.now().year, current_month - 1)[1]\r\n elif date_preset == \"this_month\":\r\n month_count = current_month\r\n total_days_count = datetime.now().day\r\n\r\n # create list of days\r\n start_dt = date(datetime.now().year, month_count, 1)\r\n end_dt = date(datetime.now().year, month_count, total_days_count)\r\n for dt in daterange(start_dt, end_dt):\r\n expected_datetime_list.append(dt)\r\n return expected_datetime_list\r\n\r\ndef create_datetime_list(date_preset, date_preset_count):\r\n expected_datetime_list = []\r\n current_month = datetime.now().month\r\n if date_preset not in (\"last_month\", \"this_month\", \"today\", \"yesterday\"):\r\n for count in range(1, (date_preset_count+1)):\r\n expected_datetime_list.append(datetime.now() - timedelta(days=count))\r\n elif date_preset == \"last_month\":\r\n expected_datetime_list = get_last_month_or_this_month_days_list(date_preset, current_month)\r\n elif date_preset == \"this_month\":\r\n expected_datetime_list = get_last_month_or_this_month_days_list(date_preset, current_month)\r\n return expected_datetime_list\r\n\r\ndef create_kpi_list(date_preset, date_preset_count, kpi_value):\r\n expected_kpi_list = []\r\n current_month = datetime.now().month\r\n if date_preset == \"last_month\":\r\n date_preset_count = calendar.monthrange(datetime.now().year, current_month - 1)[1]\r\n elif date_preset == \"this_month\":\r\n date_preset_count = datetime.now().day\r\n\r\n for count in range(1, (date_preset_count + 1)):\r\n expected_kpi_list.append(kpi_value * count)\r\n return expected_kpi_list\r\n\r\ndef convert_to_timestamp(timestamp):\r\n return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d')\r\n # value = datetime.fromtimestamp(timestamp)\r\n # return value.strftime('%Y-%m-%d')\r\n\r\ndef check_and_store_nested_attributes(response, attribute_list):\r\n length = 1\r\n index = 0\r\n data = json.loads(response)['data']\r\n\r\n count_values = []\r\n actual_percentage_values = []\r\n formatted_percentage_values = []\r\n\r\n while int(length) <= len(attribute_list):\r\n # check if each data attribute exists\r\n check_if_specific_data_key_exists(data, attribute_list, index)\r\n\r\n # get and store each attribute count\r\n count = get_specific_nested_json_data_attribute(response, attribute_list[index], 'count')\r\n percentage = get_specific_nested_json_data_attribute(response, attribute_list[index], 'percentage')\r\n formatted_percentage = get_specific_nested_json_data_attribute(response, attribute_list[index],\r\n 'formatted_percentage')\r\n count_values.append(count)\r\n actual_percentage_values.append(percentage)\r\n formatted_percentage_values.append(formatted_percentage)\r\n\r\n length = length + 1\r\n index = index + 1\r\n\r\n return count_values, actual_percentage_values, formatted_percentage_values\r\n\r\ndef compute_breakdown_percentages(count_values, attribute_list):\r\n # get each percentage and check if sum is 100\r\n total = sum(count_values)\r\n length = 1\r\n index = 0\r\n computed_percentage_values = []\r\n while int(length) <= len(attribute_list):\r\n computed_percentage = 100 * float(count_values[index]) / float(total)\r\n computed_percentage_values.append(computed_percentage)\r\n length = length + 1\r\n index = index + 1\r\n if not(sum(computed_percentage_values) == 100):\r\n raise ValueError('Total percentage ', sum(computed_percentage_values), ' is not equal to 100!')\r\n return computed_percentage_values\r\n\r\ndef roundoff_list_values(list_data):\r\n return ['%.2f' % elem for elem in list_data]\r\n\r\ndef compare_breakdown_percentages(attribute_list, actual_percentage_values, computed_percentage_values):\r\n #store computed percentages in dictionary\r\n computed_dictionary = dict(zip(attribute_list, roundoff_list_values(computed_percentage_values)))\r\n #store actual percentages in dictionary\r\n actual_dictionary = dict(zip(attribute_list, roundoff_list_values(actual_percentage_values)))\r\n #compare actual and computed percentage values\r\n compare_dictionaries(actual_dictionary, computed_dictionary)\r\n\r\ndef compute_and_check_count(response, attribute_list):\r\n # get each count and check if sum is 100\r\n length = 1\r\n index = 0\r\n count_values = []\r\n while int(length) <= len(attribute_list):\r\n count_values.append(get_specific_data_attribute_value(response, attribute_list[index]))\r\n length = length + 1\r\n index = index + 1\r\n if not(sum(count_values) == 100):\r\n raise ValueError('Total percentage ', sum(count_values), ' is not equal to 100!')\r\n\r\n#_EXCEL DATA_\r\ndef get_specific_value_from_data_framework(file_name, sheet_name, column_header):\r\n sheet_data = pd.read_excel(file_name, sheet_name=sheet_name)\r\n return sheet_data.ix[0, column_header]\r\n\r\ndef split_data(original_value):\r\n first_value, second_value = original_value.split(' ')\r\n return (first_value, second_value)\r\n\r\ndef open_workbook_by_sheet_index(file_path, sheet_index):\r\n return xlrd.open_workbook(file_path).sheet_by_index(int(sheet_index))\r\n\r\ndef store_excel_values_as_dictionary(file_path, sheet_index, start_index):\r\n excel_dictionary = {}\r\n sheet = open_workbook_by_sheet_index(file_path, sheet_index)\r\n\r\n while int(start_index) <= sheet.ncols-1:\r\n column_header = sheet.cell(0, int(start_index)).value\r\n column_value = sheet.cell(1, int(start_index)).value\r\n if(column_header == 'tagger_id'):\r\n column_value = str(int(column_value))\r\n excel_dictionary[column_header] = column_value\r\n start_index = int(start_index) + 1\r\n return excel_dictionary\r\n\r\n#_OTHERS_\r\ndef get_json_error_attribute_value(server, link, attribute):\r\n url = server + link\r\n try:\r\n request = urllib2.Request(url)\r\n response = urllib2.urlopen(request)\r\n except urllib2.HTTPError as e:\r\n error_body = e.read()\r\n resp_dict = json.loads(error_body)\r\n return resp_dict.get(attribute)\r\n\r\n","sub_path":"resources/utility_backend.py","file_name":"utility_backend.py","file_ext":"py","file_size_in_byte":11664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"480809357","text":"from flask import current_app as app\nfrom flask import jsonify, request\nimport flask_login, pymysql\n\n\n@flask_login.login_required\ndef _groups_get_all():\n \"\"\"\n Returns id, name, hacking space of all groups\n \"\"\"\n\n connection = app.config[\"PYMYSQL_CONNECTION\"]\n\n query = \"SELECT \\\n group_id as id, \\\n name, \\\n space as hacking_space \\\n FROM `group`;\"\n with connection.cursor() as cursor:\n cursor.execute(query)\n query_result = cursor.fetchall()\n cursor.close()\n\n # format output\n output = {\"groups_get_all\": [], \"_groups_count\": 0}\n\n for each_group in query_result:\n temp_group_details = {\n \"id\": each_group[\"id\"], \n \"name\": each_group[\"name\"], \n \"hacking_space\": each_group[\"hacking_space\"]\n }\n \n output[\"groups_get_all\"].append(temp_group_details)\n output[\"_groups_count\"] += 1\n\n return jsonify(output), 200\n","sub_path":"backend/app/backend/groups_get_all.py","file_name":"groups_get_all.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"413101851","text":"\nfrom dynaconf import Dynaconf, Validator\n\ndef check_sort_order(keys):\n valid_attrs = ['status', 'title', 'id', 'body', 'list_id', 'createdDateTime', 'dueDateTime', 'lastModifiedDateTime', 'importance', 'isReminderOn']\n for key in keys:\n if len(key) > 0 and key[0] == '-':\n # Then we need to chop out that char for validation\n key = key[1:]\n if key not in valid_attrs:\n return False\n return True\n\n\nsettings = Dynaconf(\n envvar_prefix=\"DYNACONF\",\n settings_files=['settings.toml', '.secrets.toml'],\n validators=[\n Validator('To_Do_Widget', must_exist=True),\n Validator('To_Do_Widget.update_interval', is_type_of=int),\n Validator('To_Do_Widget.incomplete_task_visibility', is_type_of=bool),\n Validator('To_Do_Widget.lists_to_use', is_type_of=list),\n Validator('To_Do_Widget.task_sort_order', is_type_of=list),\n Validator('Weather_Widget', must_exist=True),\n Validator('Weather_Widget.city_name', is_type_of=str),\n Validator('Weather_Widget.units', is_type_of=str),\n Validator('Weather_Widget.update_interval', is_type_of=int),\n Validator('To_Do_Widget.task_sort_order', condition=check_sort_order)\n ],\n)","sub_path":"dynaconf_settings.py","file_name":"dynaconf_settings.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"233562086","text":"from django.conf.urls import url, include\nfrom . import views\nfrom django.urls import path\n\nurlpatterns = [\n\turl(r'^doctor/$', views.doctor_login),\n\turl(r'^receptionist/$', views.receptionist_login),\n\turl(r'^$', views.first_page),\n\turl(r'^doctor/home/$', views.doctor_home),\n\turl(r'^receptionist/home/$', views.receptionist_home),\n\tpath('doctor/home/patient//', views.patient_doctor),\n\tpath('doctor/home/prescription//', views.prescription),\n\turl(r'^receptionist/home/appointment_new/$', views.receptionist_new_patient),\n\turl(r'^receptionist/home/appointment_exist/$', views.receptionist_existing_patient),\n\tpath('receptionist/home/appointment//edit', views.receptionist_edit_appointment),\n\turl(r'^receptionist/bill/$', views.bill_info),\n\tpath('receptionist/view_bill/',views.get_bill_print),\n\turl(r'^receptionist/view_bill', views.bill_find),\n\tpath('receptionist/bill_print/',views.bill_print),\n\tpath('receptionist/home/edit_patient//edit/', views.receptionist_edit_patient),\n\turl(r'^receptionist/home/patient_edit$', views.view_patient_edit),\n]\n","sub_path":"account/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"515307800","text":"from os import remove\nfrom tempfile import gettempdir\nimport gzip\nimport pickle\nimport pandas as pd\nimport numpy as np\nfrom janggu_layers import Reverse,Complement\n\nfrom pysster.Data import Data\nimport pysster.utils as io\nimport keras \n\nimport innvestigate\n\nimport innvestigate.utils as iutils\n#import innvestigate.utils.tests.networks.imagenet\n#import innvestigate.utils.visualizations as ivis\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\n\n\nimport utils_imagenet as imgnetutils\n\nfrom keras.models import load_model, Model\nfrom keras import backend as K\nimport keras\n\nimport vizsequence\nfrom vizsequence import viz_sequence\n\n\ndef change_activation(model):\n print(\"changing activation...\")\n custom_objects={'Reverse':Reverse,'Complement':Complement}\n path = \"{}/temp_model_file\".format(gettempdir())\n model.save(path, overwrite = True)\n model = load_model(path, custom_objects=custom_objects)\n model.layers[-1].activation = keras.activations.linear\n model.save(path, overwrite = True)\n K.clear_session()\n model = load_model(path, custom_objects=custom_objects)\n model.layers[0].name=\"in_dna\"\n remove(path)\n return model\n\ndef create_lists(analyzers,name,SEQ,methods,SCORE):\n np.save(open(name+\"_score.npy\",\"wb\"), SCORE)\n analysis=np.zeros(shape=SEQ.shape)\n print(analysis.shape)\n for j in range(0, len(analyzers)):\n for i,seq in enumerate(SEQ):\n analysis[i]=(analyzers[j].analyze(np.expand_dims(seq,axis=0)))\n print(analysis.shape)\n np.save(open(name+\"_\"+methods[j][0]+\"_iNN.npy\",\"wb\"),analysis)\n \n\n # Create analyzers.\n# patterns = net[\"patterns\"]\nmethods = [\n # NAME OPT.PARAMS POSTPROC FXN TITLE\n\n # Show input.\n# (\"input\", {}, imgnetutils.image, \"Input\"),\n\n # Function\n# (\"gradient\", {}, imgnetutils.graymap, \"Gradient\"),\n (\"integrated_gradients\", {}, imgnetutils.graymap, \"Integrated Gradients\"),\n\n # Signal\n# (\"deconvnet\", {}, imgnetutils.bk_proj, \"Deconvnet\"),\n# (\"guided_backprop\", {}, imgnetutils.bk_proj, \"Guided Backprop\"),\n #(\"pattern.net\", {\"patterns\": patterns}, imgnetutils.bk_proj, \"PatterNet\"),\n\n # Interaction\n #(\"pattern.attribution\", {\"patterns\": patterns}, imgnetutils.heatmap, \"Pattern Attribution\"),\n\n\n (\"lrp.epsilon\", {\"epsilon\": 1}, imgnetutils.heatmap, \"LRP Epsilon\"),\n\n\n #(\"lrp.sequential_preset_a_flat\", {\"epsilon\": 1}, imgnetutils.heatmap, \"LRP-PresetAFlat\"),\n #(\"lrp.sequential_preset_b_flat\", {\"epsilon\": 1}, imgnetutils.heatmap, \"LRP-PresetBFlat\"),\n]\n \nnames=[\"artificial\"]\n#names=[\"lung\"]\nfor name in names:\n\n #load data\n data=io.load_data(name+\"/data.pkl\")\n \n SEQ,IF=data._get_data(\"test\")\n \n #load model\n custom_objects={'Reverse':Reverse, 'Complement':Complement}\n model=load_model(name+\"/model.pkl.h5\", custom_objects = custom_objects)\n SCORE=model.predict(SEQ, batch_size=1000, verbose=1)\n\n pattern_type = \"relu\"\n channels_first = K.image_data_format == \"channels_first\"\n \n # model_wo_softmax = iutils.keras.graph.model_wo_softmax(model)\n model=change_activation(model)\n\n # Create analyzers.\n print(\"analyse\")\n analyzers = []\n for method in methods:\n try:\n analyzer = innvestigate.create_analyzer(method[0],\n model,\n **method[1])\n except innvestigate.NotAnalyzeableModelException:\n print(\"ERROR\")\n analyzer = None\n analyzers.append(analyzer)\n create_lists(analyzers,name,SEQ,methods,SCORE)\n \n","sub_path":"pysster/iNNvestigate_create_files.py","file_name":"iNNvestigate_create_files.py","file_ext":"py","file_size_in_byte":3891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"248367610","text":"\n##Function definitions##\n#----------------------#\n\ndef display():\n for i in range(len(twr1)):\n print (\" \" + (\" \" if twr1[i] == 0 else str(twr1[i])) +\\\n \" \" + (\" \" if twr2[i] == 0 else str(twr2[i])) +\\\n \" \" + (\" \" if twr3[i] == 0 else str(twr3[i])))\n \n print (\"--- --- ---\")\n print (\" A B C \")\n\n \ndef getInput():\n x = input();\n \n if x == 'ab':\n move(twr1,twr2)\n elif x == 'ac':\n move(twr1,twr3)\n elif x == 'ba':\n move(twr2,twr1)\n elif x == 'bc':\n move(twr2,twr3)\n elif x == 'ca':\n move(twr3,twr1)\n elif x == 'cb':\n move(twr3,twr2)\n elif x == 'solve':\n setTowers()\n solve(disks, twr1,twr2,twr3, \"A\", \"B\", \"C\")\n setTowers()\n print(\"\\nnow you try!\")\n else:\n print(\"invalid input: format should be \\\"ab\\\" \\(means from A to B\\)\")\n \n\ndef move(twrA, twrB):\n\n position = -1\n top = len(twrB)-1\n\n for i in range(len(twrA)):\n if(twrA[i]!=0):\n position = i\n break\n \n if(position == -1):\n print(\"No disks left\")\n return\n\n for i in range(len(twrB)-1, -1, -1):\n top = i;\n if(twrB[i] == 0):\n break\n \n if(twrB[len(twrB) - 1]!=0 and twrB[top+1] <= twrA[position]):\n print(\"illegal move\")\n \n else:\n twrB[top] = twrA[position]\n twrA[position] = 0\n\n \ndef solve(n, frm, using, to, fromName, usingName, toName):\n if (n == 1):\n move(frm, to)\n display()\n print (\"disk moved form {x} to {y}\".format(x=fromName, y = toName))\n input(\"press enter to continue\")\n else:\n solve(n - 1, frm, to, using, fromName, toName, usingName)\n move(frm, to)\n display()\n print (\"disk moved form {x} to {y}\".format(x=fromName, y = toName))\n input(\"press enter to continue\")\n solve(n - 1, using, frm, to, usingName, fromName, toName)\n \n\ndef setTowers(): \n for i in range(0, disks):\n twr1[i] = i+1\n twr2[i] = 0\n twr3[i] = 0\n\n \n\n##Start Program##\n#---------------#\n\ndisks = 0\ntotalMoves = 0\n\nwhile(disks < 1):\n disks = int(input(\"Enter the number of disks you would like to use\"))\n \n \ntwr1 = [0]*disks\ntwr2 = [0]*disks\ntwr3 = [0]*disks\n\nsetTowers()\n\nprint (\"Enter a move. format should be \\\"FromTo\\\" for example \\\"ab\\\" means from A to B\")\n\nwhile(twr3[0] == 0):\n display()\n getInput()\n totalMoves += 1\n \ndisplay();\nprint (\"YAY! You Win! Your total moves were \",totalMoves);\n\n","sub_path":"pythonTowers.py","file_name":"pythonTowers.py","file_ext":"py","file_size_in_byte":2304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"188170453","text":"def binary_classification_metrics(prediction, ground_truth):\n '''\n Computes metrics for binary classification\n\n Arguments:\n prediction, np array of bool (num_samples) - model predictions\n ground_truth, np array of bool (num_samples) - true labels\n\n Returns:\n precision, recall, f1, accuracy - classification metrics\n '''\n\n tp = fp = tn = fn = 0\n\n for x, y in zip(prediction, ground_truth):\n if x and y:\n tp += 1\n elif not x and not y:\n tn += 1\n elif x and not y:\n fp += 1\n else:\n fn += 1\n accuracy = (tp + tn) / prediction.shape[0]\n precision = tp / (tp + fp) if tp + fp > 0 else 0\n recall = tp / (tp + fn) if tp + fn > 0 else 0\n\n f1 = 2 * precision * recall / (precision + recall) if precision + recall > 0 else 0\n\n # implement metrics!\n # Some helpful links:\n # https://en.wikipedia.org/wiki/Precision_and_recall\n # https://en.wikipedia.org/wiki/F1_score\n\n return precision, recall, f1, accuracy\n\n\ndef multiclass_accuracy(prediction, ground_truth):\n '''\n Computes metrics for multiclass classification\n\n Arguments:\n prediction, np array of int (num_samples) - model predictions\n ground_truth, np array of int (num_samples) - true labels\n\n Returns:\n accuracy - ratio of accurate predictions to total samples\n '''\n\n # Implement computing accuracy\n\n return sum(1 for x, y in zip(prediction, ground_truth) if x == y) / prediction.shape[0]\n","sub_path":"assignments/assignment1/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"472496804","text":"import time\r\nfrom selenium import webdriver\r\nfrom bs4 import BeautifulSoup as BS\r\nimport json\r\n# 目標URL網址\r\nURL = \"https://stats.nba.com/teams/\"\r\n\r\nclass TeamPictureCrawler:\r\n def __init__(self, url):\r\n self.url_to_crawl = url\r\n self.links = []\r\n self.result = []\r\n\r\n def start_driver(self):\r\n print(\"啟動 WebDriver...\")\r\n self.driver = webdriver.Chrome(\"./chromedriver\")\r\n self.driver.implicitly_wait(10)\r\n\r\n def close_driver(self):\r\n self.driver.quit()\r\n print(\"關閉 WebDriver...\")\r\n\r\n def get_page(self, url):\r\n print(\"取得網頁...\")\r\n self.driver.get(url)\r\n time.sleep(2)\r\n\r\n def parse(self):\r\n self.start_driver() # 開啟 WebDriver\r\n self.get_page(self.url_to_crawl)\r\n self.get_links()\r\n self.close_driver() # 關閉 WebDriver\r\n\r\n def get_links(self):\r\n res = BS(self.driver.page_source, 'lxml')\r\n temps = res.select('.stats-team-list__link')\r\n for link in temps:\r\n self.links.append(link.get('href'))\r\n\r\n def get_team(self):\r\n res = BS(self.driver.page_source, 'lxml')\r\n team = {}\r\n team_city = res.select('.stats-team-summary__city')[0].text\r\n team_name = res.select('.stats-team-summary__name')[0].text\r\n team[\"name\"] = team_city + \" \" + team_name\r\n team[\"pic_url\"] = self.driver.find_element_by_xpath(\"*//img[@class='team-logo away team-img']\").get_attribute('src')\r\n self.result.append(team)\r\n\r\n def parse_detail(self):\r\n domain = \"https://stats.nba.com\"\r\n self.start_driver()\r\n for link in self.links:\r\n self.get_page(domain + link)\r\n self.get_team()\r\n self.close_driver()\r\n\r\ndef save_to_json(result):\r\n with open(\"team_pic.json\", 'w') as file_object:\r\n json.dump(result, file_object)\r\n\r\nif __name__ == '__main__':\r\n crawler = TeamPictureCrawler(URL)\r\n crawler.parse()\r\n crawler.parse_detail()\r\n save_to_json(crawler.result)\r\n","sub_path":"python/Crawler/teamPicCrawler.py","file_name":"teamPicCrawler.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"127742305","text":"import unittest\nimport snapshottest\nfrom src.data_loaders.BablTask1Loader import parse_data, split_parse_data\n\nclass BablTask1LoaderTest(snapshottest.TestCase):\n\n def test_converts_data_to_dataframe(self):\n df = parse_data('test_data/babl_task1_excerpt.txt')\n self.assertMatchSnapshot(df.to_json())\n\n def test_splits_dataframe_into_X_and_y(self):\n X, y = split_parse_data('test_data/babl_task1_excerpt.txt')\n self.assertMatchSnapshot(X.to_json())\n self.assertMatchSnapshot(y.to_json())\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"test/data_loaders/test_BablTask1Loader.py","file_name":"test_BablTask1Loader.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"268939151","text":"def add_to_inventory(inventory, added_items): # inventory -> dictionary, added_items -> list\n for value in added_items:\n inventory[value] = inventory.setdefault(value, 0) + 1\n\n\ndef display_inventory(inventory): # inventory -> dictionary\n print('Inventory : ')\n item_total = 0\n for key, value in inventory.items():\n print(str(value) + ' ' + str(key))\n item_total += value\n print('Total number of items : ' + str(item_total))\n\n\nmy_inventory = {'gold coin': 42, 'rope': 1}\ndragon_loot = ['gold coin', 'ruby', 'sapphire', 'gold coin', 'sword', 'gold coin']\nadd_to_inventory(my_inventory, dragon_loot)\ndisplay_inventory(my_inventory)\n","sub_path":"Studies/exercises/add_list_to_dictionary.py","file_name":"add_list_to_dictionary.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"160854877","text":"# Video 1: While loop\nerror=50.0\nwhile error > 1 :\n error=error/4\n prinet(error)\n \n \n# Ej 2: Basic while loop\n## Initialize offset\noffset=8\n## Code the while loop\nwhile offset != 0 :\n print(\"correcting...\")\n offset=offset-1\n print(offset)\n\n# Ej 3: Add conditionals\n ## Initialize offset\n offset = -6\n ## Code the while loop\n while offset != 0 :\n print(\"correcting...\")\n if offset > 0 :\n offset = offset - 1\n else :\n offset = offset + 1\n print(offset)\n\n# Videio 4: for loop\n ## loop:\n fam = [1.73, 1.68, 1.71, 1.89]\n for height in fam :\n print(height)\n ## enumerate:\n fam = [1.73, 1.68, 1.71, 1.89]\n for index, height in enumerate(fam) :\n print(\"index\" + str(index) +\":\" + str (height))\n ## Loop over string:\n for c in \"family\" :\n print(c.capitalize())\n\n# Ej 5: Loop over a list\n ## areas list\n areas = [11.25, 18.0, 20.0, 10.75, 9.50]\n ## Code the for loop\n for c in areas :\n print(c)\n\n# Ej 6: Indexes and values (1)\n ## areas list\n areas = [11.25, 18.0, 20.0, 10.75, 9.50]\n ## Code the for loop\n for index, area in enumerate(areas) :\n print(\"room \" + str(index) + \": \" + str(area)) \n\n# Ej 7: Indexes and values (2)\n ## areas list\n areas = [11.25, 18.0, 20.0, 10.75, 9.50]\n ## Code the for loop\n for index, area in enumerate(areas) :\n print(\"room \" + str(index+1) + \": \" + str(area))\n\n# Ej 8: Loop over list of lists\n ## house list of lists\n house = [[\"hallway\", 11.25], \n [\"kitchen\", 18.0], \n [\"living room\", 20.0], \n [\"bedroom\", 10.75], \n [\"bathroom\", 9.50]]\n ## Build a for loop from scratch\n for x in house:\n print(\"the \" + str(x[0]) + \" is \" + str(x[1]) + \" sqm\")\n\n# Video 9: Looping Data Structures, Part 1\n ## Dictionary:\n world = {\"afghanistan\":30.55,\n \"albania\":2.77,\n \"algeria\":39.21 }\n\n for key, value in world.items(): # con world solo da error\n print(key + \"--\" + str(value))\n ## Numpy Arrays:\n import nump as np\n np_height = np.array([1.73, 1.68, 1.71, 1.89, 1.79])\n np_weight = np.array([65.4, 59.2, 63.6, 88.4, 68.7])\n bmi= np_weight/np_height**2\n for val in bmi:\n print(val)\n ## 2D Numpy Arrays\n meas= np.array([np_height, np_weight])\n for val in meas:\n print(val)\n ## Recap:\n ### Dictionary: for key, val in my_dict.items() :\n ### Numpy array: for val in np.nditer(my_array) :\n\n# Ej 10: Loop over dictionary\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Intermediate Python for Data Science/4_Loops.py","file_name":"4_Loops.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"59801262","text":"# coding=utf-8\n# /usr/bin/env python3\n'''\nAuthor:Fuxin Jiang\nEmail:jiangfuxin17@mails.ucas.ac.cn\n'''\n'''\n数据说明,比赛数据(脱敏后)抽取的时间范是���连续30天的数据。总体上看,训练分为训练集数据文件、测试集数据文件、用户基本特征数据集、用户行为类汇总特征\n数据集、用户激活过的app列表、30天的APP使用日志、APP类别元数据\nage_train.csv代表训练样本,各字段之间由逗号隔开 1代表小于18岁、2代表19-23周岁、3代表24-34岁、4代表35-44岁、5代表45-54岁、6代表大于等于55周岁\n训练数据总共2010000,测试数据502500\n'''\n'''\n用户基本特征数据集user_basic_info.csv每一行代表一个用户的基本信息,包含用户人口属性、设备基本属性、各字段之间由逗号分隔,格式为:\n\"uld, gender, city, prodName, ramCapacity, ramLeftRation, romCapacity, romLeftRation, color, fontSize, ct,carrier, os \"\n用户标识(uId) 匿名化处理后的用户唯一标识(ID取值从1000001开始,依次递增)\n性别(gender) 男/女(取值空间0,1)\n常住地(city) 如深圳市、南京市等(匿名化处理,实际取值c001,c002….)\n手机型号(prodName) 如mate10、honor 10等(匿名化处理,实际取值p001、p002……)\n手机ram容量(ramCapacity) 手机ram的大小,以G为单位\nram剩余容量占比(ramLeftRation) 手机剩余的容量占总容量的比例\nrom容量(romCapacity) 手机rom的大小,以G为单位\nrom剩余容量占比(romLeftRation) 手机剩余rom容量占总rom容量的比例\n手机颜色(color) 手机机身的颜色\n字体大小(fontSize) 手机设置的字体大小\n上网类型(ct) 2G/3G/4G/WIFI\n移动运营商(carrier) 移动/联通/电信/其他\n手机系统版本(os)AndroId操作系统的版本号\n总共2512500条\n'''\n'''\n用户行为类汇总特征数据集user_behavior_info.csv每行代表一个用户的行为类信息,包含对设备的使用行为汇总数据。\n用户标识(uId) 匿名化处理后的用户唯一标识(ID取值从1000001开始,依次递增)\n开机次数(bootTimes) 一段时间内(30天)手机的总开机次数\n手机A特性使用次数(AFuncTimes) 一段时间内(30天) 手机A特性使用次数\n手机B特性使用次数(BFuncTimes) 一段时间内(30天) 手机B特性使用次数\n手机C特性使用次数(CFuncTimes) 一段时间内(30天) 手机C特性使用次数\n手机D特性使用次数(DFuncTimes) 一段时间内(30天) 手机D特性使用次数\n手机E特性使用次数(EFuncTimes) 一段时间内(30天) 手机E特性使用次数\n手机F特性使用次数(FFuncTimes) 一段时间内(30天) 手机F特性使用次数\n手机G特性使用情况(FFuncSum) 一段时间内(30天)G特性使用情况(数值)\n总共2512500条\n'''\n'''\n用户的激活APP列表文件user_app_actived.csv 每一行代表一条用户激活app的记录(APP激活的含义为用户安装并使用该APP)。特征文件格式为:\n\"uld, appld# appld# appld# appld# appld......\"uld为用户标识,appld为app应用的唯一标识,多个app以\"#\"分隔\n用户标识(uId) 匿名化处理后的用户唯一标识(ID取值从1000001开始,依次递增)\n应用标识(appId) 匿名化处理后的app唯一标识\n总共2512500条\n'''\n'''\napp使用行为日志文件user_app_usage.csv存放了30天内按天统计每个用户对具体某个app的累计打开次数和使用时长,\n用户标识(uId) 匿名化处理后的用户唯一标识(ID取值从1000001开始,依次递增)\n应用标识(appId) 匿名化处理后的app唯一标识\n使用时长(duration) 1天内用户对某app的累计使用时长\n打开次数(times) 1天内用户对某app的累计打开次数\n使用日期(use_date) 用户对某app的使用日期\n总共651007719条\n'''\n\n'''\napp对应类别文件app_info.csv每一行代表一条app的信息,格式如下:\n应用标识(appId) appId为app应用的唯一标识\n应用类型(category) app所属的应用类型\n总共188864条\n'''\nimport pandas as pd\nfrom collections import Counter\ndef data_pre():\n\n data_train = pd.read_csv(\"age_train.csv\", header=None)\n data_train.columns = ['uid', 'label']\n\n data_test = pd.read_csv(\"age_test.csv\", header=None)\n data_test.columns = ['uid']\n\n user_basic_info = pd.read_csv(\"user_basic_info.csv\", header=None)\n user_basic_info.columns = ['uid', 'gender', 'city', 'prodName', 'ramCapacity', 'ramLeftRation', 'romCapacity',\n 'romLeftRation', 'color', 'fontSize', 'ct', 'carrier', 'os']\n prodName_mapping = {label: idx for idx, label in enumerate(set(user_basic_info['prodName']))}\n user_basic_info['prodName'] = user_basic_info['prodName'].map(prodName_mapping)\n\n city_mapping = {label: idx for idx, label in enumerate(set(user_basic_info['city']))}\n user_basic_info['city'] = user_basic_info['city'].map(city_mapping)\n\n carrier_mapping = {label: idx for idx, label in enumerate(set(user_basic_info['carrier']))}\n user_basic_info['carrier'] = user_basic_info['carrier'].map(carrier_mapping)\n\n color_mapping = {label: idx for idx, label in enumerate(set(user_basic_info['color']))}\n user_basic_info['color'] = user_basic_info['color'].map(color_mapping)\n\n ct_mapping = {label: idx for idx, label in enumerate(set(user_basic_info['ct']))}\n user_basic_info['ct'] = user_basic_info['ct'].map(ct_mapping)\n\n\n user_behavior_info = pd.read_csv(\"user_behavior_info.csv\", header=None)\n user_behavior_info.columns = ['uid', 'bootTimes', 'AFuncTimes', 'BFuncTimes', 'CFuncTimes', 'DFuncTimes',\n 'EFuncTimes', 'FFuncTimes', 'GFuncTimes']\n\n app_info = pd.read_csv(\"app_info.csv\", header=None)\n app_info.columns = ['app_id', 'app_class']\n print(set(app_info['app_class']))\n app_class_to_id_dict = {}\n for class_name in set(app_info['app_class']):\n app_class_to_id_dict[class_name] = list(app_info.loc[app_info['app_class'] == class_name, 'app_id'])\n print(\"字典建立完毕!\")\n\n user_app_actived = pd.read_csv(\"user_app_actived.csv\", header=None)\n user_app_actived.columns = ['uid', 'app_ids']\n\n\n for class_name in set(app_info['app_class']):\n user_app_actived[class_name] = user_app_actived['app_ids'].apply(\n lambda x: len(set(x.strip().split('#')) & set(app_class_to_id_dict[class_name])))\n \n user_app_actived.drop(['app_ids'], axis=1, inplace=True)\n \n data_train = pd.merge(data_train, user_basic_info, how='left', on='uid')\n data_train = pd.merge(data_train, user_behavior_info, how='left', on='uid')\n data_train = pd.merge(data_train, user_app_actived, how='left', on='uid')\n data_test = pd.merge(data_test, user_basic_info, how='left', on='uid')\n data_test = pd.merge(data_test, user_behavior_info, how='left', on='uid')\n data_test = pd.merge(data_test, user_app_actived, how='left', on='uid')\n #返回分类属性\n categorical_feature = ['gender', 'city', 'prodName', 'color', 'ct', 'carrier']\n\n data_train.to_csv(\"data_train.csv\", index=False, encoding=\"utf-8\")\n data_test.to_csv(\"data_test.csv\", index=False, encoding=\"utf-8\")\n\n return data_train, data_test, categorical_feature\n\nif __name__ == \"__main__\":\n data_train, data_test ,categorical_feature = data_pre()\n print(data_train.head())\n print(data_test.head())\n app_info = pd.read_csv(\"app_info.csv\", header = None)\n app_info.columns = ['app_id', 'app_class']\n print(set(app_info['app_class']))\n app_class_to_id_dict = {}\n for class_name in set(app_info['app_class']):\n app_class_to_id_dict[class_name] = list(app_info.loc[app_info['app_class'] == class_name, 'app_id'])\n print(\"字典建立完毕!\")\n\n user_app_actived = pd.read_csv(\"user_app_actived.csv\", header = None)\n user_app_actived.columns = ['uid', 'app_ids']\n\n for class_name in set(app_info['app_class']):\n user_app_actived[class_name] = user_app_actived['app_ids'].apply(lambda x :len(set(x.strip().split('#'))&set(app_class_to_id_dict[class_name])))\n print(user_app_actived.head())\n","sub_path":"process_data_programs/datapre.py","file_name":"datapre.py","file_ext":"py","file_size_in_byte":8197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"427568199","text":"# Uses python3\nimport sys\n\n'''\nMajority Element Problem\n\nCheck whether a given sequence of numbers contains an element that appears more than 1/2 of the times.\n\nInput: A sequence of n integers\nOutput: \n Either:\n * 1, if there is an element that is repeated more than n/2 times\n * 0, if otherwise\n'''\ndef binary_search(list_, x):\n low, high = 0, len(list_) - 1\n mid = len(list_) // 2\n while high >= low:\n mid = (low + high) // 2\n\n if (list_[mid] == x):\n return mid\n elif (x > list_[mid]):\n low = mid + 1\n else:\n high = mid - 1\n\n return -1\n\ndef get_majority_in_half(numbers):\n check_num = numbers[0]\n count = 1\n for i in range(1, len(numbers)):\n if numbers[i] == check_num:\n count += 1\n else:\n check_num = numbers[i]\n count = 1\n\n if count > (len(numbers)/2):\n return (a[i], count)\n \n return (-1, -1)\n\ndef get_majority_in_half2(numbers, total_count): # [2, 2, 9]\n numbers_length = len(numbers)\n if (numbers_length == 1):\n return (numbers[0], False)\n \n # nums = numbers.copy()\n count = 1\n # current_num = nums[0]\n # i = 1\n # while (len(nums)):\n # binary_search(nums, nums[i])\n\n # [2, 2, 9, 2]\n # c i\n i = 1\n current_num = numbers[0]\n while (i + 1 < numbers_length):\n try:\n matching_number_idx = numbers.index(current_num, i)\n count += 1\n i = matching_number_idx\n except:\n print(f'ValueError. i: {i}, numbers[i]: {numbers[i]}')\n\n i += 1\n\ndef get_majority_element(a, left, right):\n total_length = len(a)\n if (total_length <= 1):\n return a[0]\n \n if (total_length == 2):\n if (a[0] != a[1]):\n return -1\n return a[0]\n\n a.sort()\n print(f'a: {a}, lefty {left}, righty {right}') # a: [2, 3, 9, 2, 2], left 0, right 5\n mid = (len(a)//2) + 1\n list_left = a[:mid] # [2, 2, 2] \n list_right = a[mid:] # [3, 9]\n len_left = len(list_left)\n \n left_majority, left_count = get_majority_in_half(list_left)\n \n # so our numbers list is at least length 3, b/c of the 2 if-statements at the beginning short-circuiting\n left_countyyy = 1\n for i in range(1, len(list_left)):\n if (list_left[i] == list_left[i - 1]):\n left_countyyy += 1\n \n\n if (left_count > total_length/2): \n return left_majority\n\n if (left_majority != -1): \n # binary search isn't actually counting all instances of element\n # need to ACTUALLY change \"something\" to count all instances of element\n \n right_majority, right_count = binary_search(list_right, left_majority)\n if ((right_count + left_count) > total_length/2):\n return left_majority\n\n if (left_majority == -1): \n right_majority = get_majority_in_half(list_right) \n if (right_majority == -1): \n return -1\n else:\n left_majority, left_count = binary_search(list_left, right_majority)\n if((right_count + left_count) > total_length/2):\n return right_majority\n\n return -1\n\n# if __name__ == '__main__':\n# # input = sys.stdin.read()\n# input = '5 2 3 9 2 2'\n# # input = '5 2 3 9 1 0'\n# #input = '5 2 2 9 9 9'\n# n, *a = list(map(int, input.split()))\n# if get_majority_element(a, 0, n) != -1:\n# print(1)\n# else:\n# print(0)\n\n\nget_majority_in_half2([2, 2, 9, 2], 5)\n\n'''\n2 2 2 3 9 \n1. Divide the array into 2 sub arrays\n 2 2 2 3 9 \n2. binary search on each subarray, starting with idx 0 as target element to count\n\n 2 2 2 3 9 \n count 3 \n\n if subarray count is majority for entire a, then return the number so that we have majority\n if subarray count is not majority, then look for more counts of the element in other array\n => check if count of all arrays is majority\n\n total count = 2\n\n3. if count is majority in 1 subarray, use binary search to see if element exists in other array and get count\n'''\n\n\n\n'''\n count = 1\n for i in range(len_left - 1):\n idx = binary_search(list_left, list_left[i])\n exists = idx != -1\n if (exists):\n count += 1\n list_left.remove(list_left[idx])\n test_length = len(list_left)\n'''\n\n","sub_path":"algorithmic-toolbox/4.divide-n-conquer/majority_binary.py","file_name":"majority_binary.py","file_ext":"py","file_size_in_byte":4338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"623594922","text":"from fastapi import APIRouter\nfrom starlette.background import BackgroundTasks\nfrom typing import List, Dict\nfrom models import User, UserDetails, FileDetails\nfrom fastapi import HTTPException, Request\nfrom database.crud import delete_user, get_files, read_user, read_users, create_user\nimport utils\n\nrouter = APIRouter(tags=[\"users\"], prefix=\"/api/users\")\n\nscopes = {\"user\":\"scopes\"}\n\n@router.get(\"/\", response_model=List[UserDetails])\nasync def users_list(request: Request, limit: int = 10):\n return read_users(limit = limit)\n\n\n@router.get(\"/{username}\", response_model=UserDetails)\nasync def user_detail(username: str):\n user_detail = read_user(username)\n if user_detail is None:\n raise HTTPException(status_code=404, detail=\"user not found\")\n return user_detail\n\n\n@router.get(\"/{username}/files\", response_model=List[FileDetails])\nasync def get_files_list(username: str):\n response = get_files(username)\n if response is None:\n raise HTTPException(status_code=404, detail = \"user not found\")\n else:\n return response\n\n\n@router.post(\"/\", response_model=UserDetails)\nasync def add_user(user: User):\n user_detail = create_user(name=user.name, username=user.username)\n return user_detail\n\n\n@router.delete(\"/{username}\", response_model=Dict[str(\"detail\"), str])\nasync def remove_user(username: str, task: BackgroundTasks):\n response = delete_user(username = username)\n if not response:\n raise HTTPException(404, detail=\"user not found!!\")\n for path in response:\n task.add_task(utils.file_delete, path=path)\n return {\"detail\": \"operation successful\"}","sub_path":"routers/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"456888656","text":"import cv2\nfrom PIL import Image\nimport numpy as np\nfrom scipy.ndimage.filters import median_filter\nfrom scipy import ndimage\nimport time\n\n# filling holes. works!\n\n# Read image\nim = cv2.imread('hole.jpg')\n\nblue = im[:, :, 0]\nthresh = blue > 50\nim[thresh] = 255\n\nimg = Image.fromarray(im)\nimg.show()\n\noriginal = thresh.copy()\na = time.time()\ndilationStruct = np.array([[False, True, False], [True, True, True], [False, True, False]])\n\nfor x in xrange(0, 1):\n thresh = ndimage.binary_dilation(thresh, structure=dilationStruct)\n thresh = median_filter(thresh, size=(3, 3))\n\ndilatedgarbage = thresh * (~ original)\n\nready = thresh.copy()\nthresh = thresh.astype(np.uint8)\n#thresh = cv2.bitwise_not(thresh)\n\ncontour, hier = cv2.findContours(thresh, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)\n\nfor cnt in contour:\n cv2.drawContours(thresh, [cnt], 0, 255, -1)\nb = time.time()\nprint (b-a)*1000\n\nimg = Image.fromarray(thresh)\nimg.show()\n\nthresh *= (~ dilatedgarbage)\nthresh *= (~ original)\n#thresh = median_filter(thresh, size=(8, 8))\n\nimg = Image.fromarray(thresh)\nimg.show()\n#gray = cv2.bitwise_not(thresh)","sub_path":"Masking/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"118197381","text":"import pygame\nfrom pygame.sprite import Sprite\n\nclass Alien(Sprite):\n \"\"\" A class to manage alien invaders \"\"\"\n\n def __init__(self, screen, ai_settings):\n \"\"\" Create a alien object in upper left corner \"\"\"\n super().__init__()\n self.screen = screen\n\n # Load the alien image and get its rect.\n self.image = pygame.image.load('images/alien.bmp')\n self.rect = self.image.get_rect()\n self.screen_rect = screen.get_rect()\n self.screen_height = ai_settings.screen_height\n\n # Start each new alien near the top of the screen.\n self.rect.x = self.rect.width\n self.rect.y = self.rect.height\n\n # Store a decimal value for the ship's center\n self.center = float(self.rect.centerx)\n\n # Store the alien's y-coord as a decimal value\n self.y = float(self.rect.y)\n self.x = float(self.rect.x)\n\n self.color = ai_settings.bullet_color\n self.speed_factor = ai_settings.alien_speed_factor\n self.ai_settings = ai_settings\n\n def update(self):\n \"\"\"Move the alien right or left.\"\"\"\n self.x += (self.speed_factor * self.ai_settings.fleet_direction)\n self.rect.x = self.x\n\n def check_edges(self):\n \"\"\" Return True if alien is at right or left edge of screen \"\"\"\n screen_rect = self.screen.get_rect()\n if self.rect.right >= screen_rect.right:\n return True\n if self.rect.left <= screen_rect.left:\n return True\n\n def check_bottom(self):\n \"\"\" Return True if alien is at the bottom of screen \"\"\"\n # print(self.rect.bottom, self.screen_height)\n if self.rect.bottom >= self.screen_height:\n return True\n else:\n return False\n\n def blitme(self):\n \"\"\" Draw the alien at its current location \"\"\"\n self.screen.blit(self.image, self.rect)\n","sub_path":"alien.py","file_name":"alien.py","file_ext":"py","file_size_in_byte":1883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"543856225","text":"import sys\ninput = sys.stdin.readline\n\ndx = [-1, 0, 1, 0] # x 가중치\ndy = [0, -1, 0, 1] # y 가중치\n\ndef bfs(s_x , s_y, R, C, graph, answer):\n # start x, start y, graph값 queue에 입력\n queue = set([(s_x, s_y, graph[s_x][s_y])])\n while queue:\n x, y, ans = queue.pop()\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n if nx < 0 or ny < 0 or nx >= R or ny >= C:\n continue\n # 만약 ans 안에 중복되는 알파벳이 없다면\n elif graph[nx][ny] not in ans:\n queue.add((nx, ny, ans + graph[nx][ny])) #추가\n answer = max(answer, len(ans) + 1) # answer 업데이트\n return answer\n \n\nR, C = map(int, input().split()) # 세로 R, 가로 C\ngraph = [list(input().strip()) for _ in range(R)] # 알파벳 그래프\nanswer = 1\nanswer = bfs(0, 0, R, C, graph, answer) # 탐색\nprint(answer)\n","sub_path":"Algorithm/JAEHYEON/1987.py","file_name":"1987.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"299255057","text":"#coding:utf-8\n#推荐系统\nimport time\nimport random\n\n\nclass Recommend(object):\n \"\"\"\n like 是反应用户最近的趋势,趋势用value[0]表示,value[1]表示其开始时间\n learn 用于再学习,info参数接受一个用户选择的结果(例如一个商品)\n result 是获取test集合的推荐结果,返回下标值\n 遍历like,其中的标签若过期了,则自动删除,不过期则于该样本比对,符合一个该样本的推荐系数+1\n \"\"\"\n def __init__(self,limit_time):\n self._like = dict() #{'key1':(value[0],value[1]),'key2':(value[0],value[1])} value[0]是喜欢的程度,value[1]是开始时间\n self._time = limit_time #有效期,按秒算\n\n def learn(self,info:dict):\n \"\"\"\n 根据info的内容学习,学习内容会连同当前的时间记录下来\n :param info: info是代表选择的属性,例如电影会具有{'title':'abc','type':'喜剧'}的形式,这些就是它需要学习的地方\n :return:\n \"\"\"\n for key in info.values():\n if key in self._like: #info的value值是self._like的键值\n self._like[key] = (self._like[key][0]+1,time.time()) #修改self._like的喜欢程度,开始时间\n else: #info的value值在self._like中没有相应的键\n self._like[key] = (1,time.time()) #新增self._like中的键值对,初始化喜欢程度\n\n def result(self,test_set:list,number:int):\n \"\"\"\n 给出测试集合,会与记录中的用户偏好进行比较,选出标签符合数最多的集合在测试集合中的下标\n :param test_set: 列表,其单个元素的内容是{p1:v1,p2:v2},v会用于与self._like的key比较\n :param number: 需要返回的选择数目\n :return: 返回一个列表,内容是test_set的下标\n \"\"\"\n #第一次\n if len(self._like) == 0:\n #返回number个,在[0,len(test_set))中的随机数字\n return [random.randrange(0,len(test_set),1) for x in range(number)]\n #已经有资料了:\n t = time.time() #t是当前时间\n res = dict() #推荐系数,与test_set中的电影一一对应\n for index in range(len(test_set)): #index是测试集合的所有下标\n res[index] = 0\n #选出self._like中前5个标签(近段时间的喜好)\n # 将self._like按value[0]也就是喜欢程度降序排列,key_list是排序后键值组成的列表\n key_list = sorted(self._like,key=lambda x:int(self._like[x][0]),reverse=True)\n if len(key_list) >= 5:\n key_list = key_list[:5]\n for like in key_list:\n w,begin_time = self._like[like]\n if begin_time >= t-self._time: #开始时间大于当前时间减有效期,说明没有过期\n if like in test_set[index].values():\n #给test_set中某项的推荐系数加一\n res[index]+=1\n else: #过期,删除self._like中的过期项\n del self._like[like]\n return sorted(res,key=lambda x:res[x],reverse=True)[:number] #返回推荐系数的列表下标\n","sub_path":"myTest2/myApp/recommend.py","file_name":"recommend.py","file_ext":"py","file_size_in_byte":3275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"648180942","text":"from typing import List, Optional, Set, Union\n\nfrom spacy.language import Language\nfrom spacy.tokens import Doc, Span, Token\n\nfrom edsnlp.pipelines.qualifiers.base import Qualifier\nfrom edsnlp.pipelines.terminations import termination\nfrom edsnlp.utils.filter import consume_spans, filter_spans, get_spans\nfrom edsnlp.utils.inclusion import check_inclusion\nfrom edsnlp.utils.resources import get_verbs\n\nfrom .patterns import following, preceding, pseudo, verbs_eds, verbs_hyp\n\n\nclass Hypothesis(Qualifier):\n \"\"\"\n Hypothesis detection with spaCy.\n\n The component looks for five kinds of expressions in the text :\n\n - preceding hypothesis, ie cues that precede a hypothetical expression\n - following hypothesis, ie cues that follow a hypothetical expression\n - pseudo hypothesis : contain a hypothesis cue, but are not hypothesis\n (eg \"pas de doute\"/\"no doubt\")\n - hypothetical verbs : verbs indicating hypothesis (eg \"douter\")\n - classic verbs conjugated to the conditional, thus indicating hypothesis\n\n Parameters\n ----------\n nlp : Language\n spaCy nlp pipeline to use for matching.\n pseudo : Optional[List[str]]\n List of pseudo hypothesis cues.\n preceding : Optional[List[str]]\n List of preceding hypothesis cues\n following : Optional[List[str]]\n List of following hypothesis cues.\n verbs_hyp : Optional[List[str]]\n List of hypothetical verbs.\n verbs_eds : Optional[List[str]]\n List of mainstream verbs.\n attr : str\n spaCy's attribute to use:\n a string with the value \"TEXT\" or \"NORM\", or a dict with the key 'term_attr'\n we can also add a key for each regex.\n on_ents_only : Union[bool, str, List[str], Set[str]]\n Whether to look for matches around detected entities only.\n Useful for faster inference in downstream tasks.\n\n - If True, will look in all ents located in `doc.ents` only\n - If an iterable of string is passed, will additionally look in `doc.spans[key]`\n for each key in the iterable\n within_ents : bool\n Whether to consider cues within entities.\n explain : bool\n Whether to keep track of cues for each entity.\n \"\"\"\n\n defaults = dict(\n following=following,\n preceding=preceding,\n pseudo=pseudo,\n termination=termination,\n verbs_eds=verbs_eds,\n verbs_hyp=verbs_hyp,\n )\n\n def __init__(\n self,\n nlp: Language,\n attr: str,\n pseudo: Optional[List[str]],\n preceding: Optional[List[str]],\n following: Optional[List[str]],\n termination: Optional[List[str]],\n verbs_eds: Optional[List[str]],\n verbs_hyp: Optional[List[str]],\n on_ents_only: Union[bool, str, List[str], Set[str]],\n within_ents: bool,\n explain: bool,\n ):\n\n terms = self.get_defaults(\n pseudo=pseudo,\n preceding=preceding,\n following=following,\n termination=termination,\n verbs_eds=verbs_eds,\n verbs_hyp=verbs_hyp,\n )\n terms[\"verbs_preceding\"], terms[\"verbs_following\"] = self.load_verbs(\n verbs_hyp=terms.pop(\"verbs_hyp\"),\n verbs_eds=terms.pop(\"verbs_eds\"),\n )\n\n super().__init__(\n nlp=nlp,\n attr=attr,\n on_ents_only=on_ents_only,\n explain=explain,\n **terms,\n )\n\n self.within_ents = within_ents\n self.set_extensions()\n\n @classmethod\n def set_extensions(cls) -> None:\n if not Token.has_extension(\"hypothesis\"):\n Token.set_extension(\"hypothesis\", default=False)\n\n if not Token.has_extension(\"hypothesis_\"):\n Token.set_extension(\n \"hypothesis_\",\n getter=lambda token: \"HYP\" if token._.hypothesis else \"CERT\",\n )\n\n if not Span.has_extension(\"hypothesis\"):\n Span.set_extension(\"hypothesis\", default=False)\n\n if not Span.has_extension(\"hypothesis_\"):\n Span.set_extension(\n \"hypothesis_\",\n getter=lambda span: \"HYP\" if span._.hypothesis else \"CERT\",\n )\n\n if not Span.has_extension(\"hypothesis_cues\"):\n Span.set_extension(\"hypothesis_cues\", default=[])\n\n if not Doc.has_extension(\"hypothesis\"):\n Doc.set_extension(\"hypothesis\", default=[])\n\n def load_verbs(\n self,\n verbs_hyp: List[str],\n verbs_eds: List[str],\n ) -> List[str]:\n \"\"\"\n Conjugate \"classic\" verbs to conditional, and add hypothesis\n verbs conjugated to all tenses.\n\n Parameters\n ----------\n verbs_hyp: List of verbs that specifically imply an hypothesis.\n verbs_eds: List of general verbs.\n\n Returns\n -------\n list of hypothesis verbs conjugated at all tenses and classic\n verbs conjugated to conditional.\n \"\"\"\n\n classic_verbs = get_verbs(verbs_eds)\n classic_verbs = classic_verbs.loc[classic_verbs[\"mode\"] == \"Conditionnel\"]\n list_classic_verbs = list(classic_verbs[\"term\"].unique())\n\n hypo_verbs = get_verbs(verbs_hyp)\n list_hypo_verbs_preceding = list(hypo_verbs[\"term\"].unique())\n\n hypo_verbs_following = hypo_verbs.loc[hypo_verbs[\"tense\"] == \"Participe Passé\"]\n list_hypo_verbs_following = list(hypo_verbs_following[\"term\"].unique())\n\n return (\n list_hypo_verbs_preceding + list_classic_verbs,\n list_hypo_verbs_following,\n )\n\n def process(self, doc: Doc) -> Doc:\n \"\"\"\n Finds entities related to hypothesis.\n\n Parameters\n ----------\n doc: spaCy Doc object\n\n Returns\n -------\n doc: spaCy Doc object, annotated for hypothesis\n \"\"\"\n\n matches = self.get_matches(doc)\n\n terminations = get_spans(matches, \"termination\")\n boundaries = self._boundaries(doc, terminations)\n\n # Removes duplicate matches and pseudo-expressions in one statement\n matches = filter_spans(matches, label_to_remove=\"pseudo\")\n\n entities = list(self.get_spans(doc))\n ents = None\n\n for start, end in boundaries:\n\n ents, entities = consume_spans(\n entities,\n filter=lambda s: check_inclusion(s, start, end),\n second_chance=ents,\n )\n\n sub_matches, matches = consume_spans(\n matches, lambda s: start <= s.start < end\n )\n\n if self.on_ents_only and not ents:\n continue\n\n sub_preceding = get_spans(sub_matches, \"preceding\")\n sub_following = get_spans(sub_matches, \"following\")\n sub_preceding += get_spans(sub_matches, \"verbs_preceding\")\n sub_following += get_spans(sub_matches, \"verbs_following\")\n\n if not sub_preceding + sub_following:\n continue\n\n if not self.on_ents_only:\n for token in doc[start:end]:\n token._.hypothesis = any(\n m.end <= token.i for m in sub_preceding\n ) or any(m.start > token.i for m in sub_following)\n\n for ent in ents:\n\n if self.within_ents:\n cues = [m for m in sub_preceding if m.end <= ent.end]\n cues += [m for m in sub_following if m.start >= ent.start]\n else:\n cues = [m for m in sub_preceding if m.end <= ent.start]\n cues += [m for m in sub_following if m.start >= ent.end]\n\n hypothesis = ent._.hypothesis or bool(cues)\n\n ent._.hypothesis = hypothesis\n\n if self.explain and hypothesis:\n ent._.hypothesis_cues += cues\n\n if not self.on_ents_only and hypothesis:\n for token in ent:\n token._.hypothesis = True\n\n return doc\n","sub_path":"edsnlp/pipelines/qualifiers/hypothesis/hypothesis.py","file_name":"hypothesis.py","file_ext":"py","file_size_in_byte":8001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"474155137","text":"# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n DsgTools\n A QGIS plugin\n Brazilian Army Cartographic Production Tools\n -------------------\n begin : 2016-02-18\n git sha : $Format:%H$\n copyright : (C) 2016 by Philipe Borba - Cartographic Engineer @ Brazilian Army\n email : borba@dsg.eb.mil.br\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program is free software; you can redistribute it and/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\nimport os\nimport json\n\nfrom PyQt4 import QtGui, uic\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import QMessageBox, QFileDialog\nfrom fileinput import filename\nfrom DsgTools.Utils.utils import Utils\n\nFORM_CLASS, _ = uic.loadUiType(os.path.join(\n os.path.dirname(__file__), 'setupEarthCoverage.ui'))\n\nclass SetupEarthCoverage(QtGui.QWizard, FORM_CLASS):\n coverageChanged = pyqtSignal()\n def __init__(self, abstractDb, areas, lines, oldCoverage, parent=None):\n '''\n Constructor\n '''\n super(self.__class__, self).__init__()\n # Set up the user interface from Designer.\n # After setupUI you can access any designer object by doing\n # self., and you can use autoconnect slots - see\n # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html\n # #widgets-and-dialogs-with-auto-connect\n self.setupUi(self)\n self.utils = Utils()\n self.areas = areas\n self.lines = lines\n self.abstractDb = abstractDb\n self.areasCustomSelector.setTitle(self.tr('Areas'))\n self.linesCustomSelector.setTitle(self.tr('Lines'))\n self.setupWizard(oldCoverage)\n self.areasCustomSelector.selectionChanged.connect(self.populateClasses)\n self.linesCustomSelector.selectionChanged.connect(self.populateDelimiters)\n self.button(QtGui.QWizard.FinishButton).clicked.connect(self.writeIntoDb)\n\n def setupFromFile(self):\n '''\n Opens a earth coverage file\n '''\n if QMessageBox.question(self, self.tr('Question'), self.tr('Do you want to open an earth coverage file?'), QMessageBox.Ok|QMessageBox.Cancel) == QMessageBox.Cancel:\n return\n filename = QFileDialog.getOpenFileName(self, self.tr('Open Earth Coverage Setup configuration'), '', self.tr('Earth Coverage Files (*.json)'))\n return filename\n\n def setupWizard(self, oldCoverage):\n '''\n Prepares the wizard\n oldCoverage: old configuration\n '''\n if oldCoverage:\n self.abstractDb.dropCentroids(oldCoverage.keys())\n filename = self.setupFromFile()\n if filename:\n setupDict = self.utils.readJsonFile(filename)\n areasToList = setupDict.keys()\n linesToList = []\n for key in areasToList:\n lines = setupDict[key]\n for line in lines:\n if line not in linesToList:\n linesToList.append(line)\n areasFromList = []\n linesFromList = []\n for area in self.areas:\n if area not in areasToList:\n areasFromList.append(area)\n for line in self.lines:\n if line not in linesToList:\n linesFromList.append(line)\n self.areasCustomSelector.setToList(areasToList)\n self.areasCustomSelector.setFromList(areasFromList)\n self.linesCustomSelector.setToList(linesToList)\n self.linesCustomSelector.setFromList(linesToList) \n self.populateClasses() \n self.populateDelimiters() \n self.checkDelimiters(setupDict)\n else:\n self.areasCustomSelector.setFromList(self.areas)\n self.linesCustomSelector.setFromList(self.lines)\n\n def checkDelimiters(self, setupDict):\n '''\n Check delimiters\n '''\n for i in range(self.treeWidget.invisibleRootItem().childCount()):\n areaItem = self.treeWidget.invisibleRootItem().child(i)\n for j in range(self.treeWidget.invisibleRootItem().child(i).childCount()):\n delimiterItem = areaItem.child(j)\n if areaItem.text(0) in setupDict.keys():\n if delimiterItem.text(1) not in setupDict[areaItem.text(0)]:\n delimiterItem.setCheckState(1,Qt.Unchecked)\n\n def loadJson(self, filename):\n '''\n Loads a json file\n '''\n filename = QFileDialog.getOpenFileName(self, self.tr('Open Field Setup configuration'), self.folder, self.tr('Field Setup Files (*.json)'))\n if not filename:\n return\n return self.readJsonFile(filename)\n\n def populateClasses(self):\n '''\n Populates area classes\n '''\n self.treeWidget.clear()\n selectedAreaClasses = []\n for i in range(self.areasCustomSelector.toList.__len__()):\n selectedAreaClasses.append(self.areasCustomSelector.toList.item(i).text())\n selectedAreaClasses.sort()\n for i in range(len(selectedAreaClasses)):\n treeItem = QtGui.QTreeWidgetItem()\n treeItem.setText(0,selectedAreaClasses[i])\n self.treeWidget.insertTopLevelItem(0,treeItem)\n self.linesCustomSelector.selectionChanged.emit()\n\n def populateDelimiters(self):\n '''\n Populates line classes (area delimiters)\n '''\n delimiterList = []\n for i in range(self.linesCustomSelector.toList.__len__()):\n delimiterList.append(self.linesCustomSelector.toList.item(i).text())\n for i in range(self.treeWidget.invisibleRootItem().childCount()):\n for delimiter in delimiterList:\n treeItem = QtGui.QTreeWidgetItem(self.treeWidget.invisibleRootItem().child(i))\n treeItem.setText(1,delimiter)\n treeItem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)\n treeItem.setCheckState(1,Qt.Checked)\n self.treeWidget.invisibleRootItem().child(i).setExpanded(True)\n\n def getEarthCoverageDictFromTree(self):\n '''\n Gets earth coverage configuration from the tree widget\n '''\n invRootItem = self.treeWidget.invisibleRootItem()\n earthCoverageDict = dict()\n for i in range(invRootItem.childCount()):\n childClass = invRootItem.child(i)\n earthCoverageDict[childClass.text(0)] = []\n for j in range(childClass.childCount()):\n if childClass.child(j).checkState(1) == Qt.Checked:\n earthCoverageDict[childClass.text(0)].append(childClass.child(j).text(1))\n return earthCoverageDict\n\n def writeIntoDb(self):\n '''\n Writes the configuration in the database\n '''\n try:\n earthDict = self.getEarthCoverageDictFromTree()\n self.abstractDb.setEarthCoverageDict(json.dumps(earthDict))\n self.abstractDb.createCentroidAuxStruct(earthDict.keys())\n self.coverageChanged.emit()\n if QMessageBox.question(self, self.tr('Question'), self.tr('Do you want to save this earth coverage setup?'), QMessageBox.Ok|QMessageBox.Cancel) == QMessageBox.Cancel:\n return\n filename = QFileDialog.getSaveFileName(self, self.tr('Save Earth Coverage Setup configuration'), '', self.tr('Earth Coverage Files (*.json)'))\n if not filename:\n QMessageBox.critical(self, self.tr('Critical!'), self.tr('Define a name for the earth coverage file!'))\n return\n with open(filename, 'w') as outfile:\n json.dump(earthDict, outfile, sort_keys=True, indent=4)\n QMessageBox.information(self, self.tr('Information!'), self.tr('Field setup file saved successfully!'))\n \n except Exception as e:\n self.abstractDb.rollbackEarthCoverage(earthDict.keys())\n QtGui.QMessageBox.warning(self, self.tr('Warning!'), self.tr('Problem saving into database! \\n')+e.args[0])\n return\n","sub_path":"ValidationTools/setupEarthCoverage.py","file_name":"setupEarthCoverage.py","file_ext":"py","file_size_in_byte":8759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"436495961","text":"import sys\nimport wos_parser\nimport wos_graph\nimport wos_clasterization\nimport test_articles\n\nif __name__ == \"__main__\":\n if \"help\" in sys.argv:\n print(\"Parameters:\")\n print(\"showbm - show articles before modification\")\n print(\"showam - show articles after modification\")\n print(\"addta - add test articles\")\n print(\"showtfidf - show tf-idf matrix, 500 columns\")\n print(\"showmds - show multidimensional scaling\")\n print(\"nodownload - don't download new article, use old\")\n print(\"showts - show titles for every claster\")\n print(\"showhdc - show hierarchical document clustering\")\n print(\"showlda - show latent Dirichlet allocation\")\n sys.exit()\n print(\"Add 'help' for showing parameters\")\n print(\"Input search string\")\n topic_name = input()\n\n if \"nodownload\" in sys.argv:\n print(\"Input count of articles\")\n cnt_articles = int(input())\n else:\n # site_parser - скачивает html-страницы каждой статьи,\n # выданной по запросу пользователя topic_name.\n # Возвращает количество статей\n cnt_articles = wos_parser.site_parser(topic_name)\n articles = []\n for i in range(1, cnt_articles+1):\n # article_parser - парсит из html страницы статьи имя,\n # автора, абстракт и статьи, на которые она ссылается\n # Эти данные добавляются в лист articles\n wos_parser.article_parser(topic_name + str(i), articles)\n\n if \"showbm\" in sys.argv:\n # show_articles - выводит на экран статьи, добавленные\n # в articles\n wos_parser.show_articles(articles)\n # correct_articles - удаляет статьи без названий, приводит\n # имена авторов в удобный для идентификации статей формат\n articles = wos_parser.correct_articles(articles)\n if \"addta\" in sys.argv:\n # add_test_articles - добавляет в конец articles тестовые\n # статьи. Они используются для проверки корректности графа\n test_articles.add_test_articles(articles)\n if \"showam\" in sys.argv:\n # show_correct_articles - выводит на экран статьи после\n # всех модификаций\n wos_parser.show_correct_articles(articles)\n\n # build_graph - строит граф, сохраняет его в формате gexf.\n # Возвращает articles без повторяющихся статей\n articles = wos_graph.build_graph(articles, topic_name)\n\n # Описания этих параметров приведены выше при обработке\n # параметра 'help'\n showtfidf = 0\n showmds = 0\n showts = 0\n showhdc = 0\n showlda = 0\n if \"showtfidf\" in sys.argv:\n showtfidf = 1\n if \"showmds\" in sys.argv:\n showmds = 1\n if \"showts\" in sys.argv:\n showts = 1\n if \"showhdc\" in sys.argv:\n showhdc = 1\n if \"showlda\" in sys.argv:\n showlda = 1\n\n # build_csv - строит базу данных по articles, сохраняет ее\n wos_clasterization.build_csv(articles, topic_name)\n # article_clasterization - разбивает статьи на кластеры\n wos_clasterization.article_clasterization(topic_name, showtfidf, showmds,\n showts, showhdc, showlda)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"416705074","text":"import characters\nCharacters = characters.Characters\n\ndef main_menu():\n \"\"\"The main menu function is called after any game event.\n\n Allows user to perform a variety of actions, such as check stats,\n use items, or equip armor.\"\"\"\n \n while True:\n print(\"\\nWhat will you do?\")\n choice = input(\"\\nEquip (e), Use Item (i), Check Something (c), done (d): \")\n if choice.lower() == \"e\":\n equip_menu()\n elif choice.lower() == \"i\":\n item_menu()\n elif choice.lower() == \"c\":\n check_menu()\n elif choice.lower() == \"d\":\n return\n\ndef equip_menu():\n char_list = [char for char in Characters.party.keys()]\n while True:\n print(\"\\nWhich character will you equip?\")\n print(\"\\n{}\".format(\" \".join(char_list)))\n choice = input(\"\\nEnter the name of the character. Check Characters (c), Back (b): \")\n if choice in Characters.party:\n who = Characters.party[choice]\n while True:\n print(f\"\\nWhat will {who.name} do?\") \n choice = input(\"\\nEquip (e), Unequip (u), Back (b): \")\n if choice.lower() == \"e\":\n while True:\n print(f\"\\nWhat equipment will {who.name} equip?\")\n choice = input(\"\\nEnter the name of the equipment. Check Equipment (c), Back (b): \")\n if choice.title() in Characters.armory:\n print()\n what = Characters.armory[choice.title()][0]\n who.equip(what)\n while True:\n choice = input(\"\\nCheck Character? Yes (y), Continue (c), Done Equipping (d): \")\n if choice.lower() == \"y\":\n print()\n who.check_member()\n break\n elif choice.lower() == \"c\":\n break\n elif choice.lower() == \"d\":\n \t return\n continue\n continue\n elif choice.lower() == \"c\":\n print()\n Characters.check_armory()\n continue\n elif choice.lower() == \"b\":\n break\n print(\"\\nYou don't have any to equip.\")\n elif choice.lower() == \"u\":\n while True:\n print(f\"\\nWhich piece of equipment will {who.name} unequip?\")\n choice = input(\"\\nWeapon (w), Armor (a), Accessory (y), All (l), Back (b): \")\n if choice.lower() in \"way\":\n choices = {\"w\": \"Weapon\", \"a\": \"Armor\", \"y\": \"Accessory\"}\n print()\n who.unequip(choices[choice])\n while True:\n choice = input(\"\\nCheck Character? Yes (y), Continue (c), Done Equipping (d): \")\n if choice.lower() == \"y\":\n print()\n who.check_member()\n break\n elif choice.lower() == \"c\":\n break\n elif choice.lower() == \"d\":\n return\n elif choice.lower() == \"l\":\n print()\n who.unequip_character()\n while True:\n choice = input(\"\\nCheck Character? Yes (y), Continue (c), Done Equipping (d): \")\n if choice.lower() == \"y\":\n print()\n who.check_member()\n break\n elif choice.lower() == \"c\":\n break\n elif choice.lower() == \"d\":\n return\n elif choice.lower() == \"b\":\n break\n elif choice.lower() == \"b\":\n break\n continue\n elif choice.lower() == \"c\":\n Characters.check_members()\n continue\n elif choice.lower() == \"b\":\n break\n print(\"\\nI don't know who that is.\")\n\n\ndef item_menu():\n char_list = [char for char in Characters.party.keys()]\n while True:\n print(\"\\nWhich item will you use?\")\n choice = input(\"\\nEnter the item name. Check Items (c), Back (b): \")\n if choice.title() in Characters.inventory:\n what = Characters.inventory[choice.title()][0] \n if what.targets == \"Single\":\n while True:\n print(\"\\nWhich character will use {}?\".format(what.name))\n print(\"\\n{}\".format(\" \".join(char_list)))\n choice = input(\"\\nEnter the name of the character. Check Characters (c), Back (b): \")\n if choice in Characters.party:\n who = Characters.party[choice]\n print()\n who.use_item(what)\n while True:\n choice = input(\"\\nCheck Character? Yes (y), Continue (c), Done Using Items (d): \")\n if choice.lower() == \"y\":\n print()\n who.check_member()\n break\n elif choice.lower() == \"c\":\n break\n elif choice.lower() == \"d\":\n return\n break\n elif choice.lower() == \"c\":\n Characters.check_members()\n continue\n elif choice.lower() == \"b\":\n break\n print(\"\\nI don't know who that is.\")\n else:\n Characters.party_item(what)\n continue\n elif choice.lower() == \"c\":\n print()\n Characters.check_items()\n continue\n elif choice.lower() == \"b\":\n break\n print(\"\\nYou don't have any to use!\")\n\ndef check_menu():\n while True:\n print(\"\\nWhat would you like to check?\")\n choice = input(\"\\nCharacters (c), GP (g), Equipment (e), Items (i), Back (b): \")\n if choice.lower() in \"cgei\":\n print()\n check(choice)\n elif choice.lower() == \"b\":\n break\n\ndef check(choice):\n if choice == \"c\":\n Characters.check_members()\n if choice == \"g\":\n Characters.check_gp()\n if choice == \"e\":\n Characters.check_armory()\n if choice == \"i\":\n Characters.check_items()\n return \n\ndef prompt():\n prompt = input() \n return\n\ndef get_name():\n while True:\n name = input(\"\\nChoose a name for your character: \")\n if len(name) < 1 or name in \" \":\n print(\"\\nYou have to give your character a name!\")\n continue\n elif name not in Characters.party:\n return name\n print(\"\\nYou already have a character with that name!\")","sub_path":"menus.py","file_name":"menus.py","file_ext":"py","file_size_in_byte":7602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"562414485","text":"from typing import List\n\nclass Solution:\n def maximalSquare(self, matrix: List[List[str]]) -> int:\n if matrix is None or len(matrix) < 1:\n return 0\n num_cols = len(matrix[0])\n num_rows = len(matrix)\n dp = [[0]*(num_cols+1) for _ in range(num_rows+1)]\n max_side = 0\n for i in range(num_rows):\n for j in range(num_cols):\n if matrix[i][j] == \"1\":\n dp[i+1][j+1] = min(dp[i][j+1], dp[i][j], dp[i+1][j]) + 1\n max_side = max(max_side, dp[i+1][j+1])\n return max_side * max_side","sub_path":"leetcode/221_maximal_square.py","file_name":"221_maximal_square.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"239457888","text":"import tensorflow as tf\n\nvgg_model_path = \"data/vgg16/vgg16-20160129.tfmodel\"\npic_path = \"data/vgg16/test.png\"\n\ndef view_ops():\n \"\"\"Help the programmer to inspect the ops names\n\n :return:\n \"\"\"\n pictures = tf.placeholder(dtype=tf.float32, shape=[None, 224, 224, 3], name=\"images\")\n\n with open(vgg_model_path, mode='rb') as f:\n file_content = f.read()\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(file_content)\n\n tf.import_graph_def(graph_def, input_map={\"images\": pictures})\n\n logits = tf.get_default_graph().get_tensor_by_name(\"import/fc7/BiasAdd:0\")\n\n predictions = tf.contrib.layers.fully_connected(\n inputs=logits,\n num_outputs=5\n )\n\n for op in [n.name for n in tf.get_default_graph().as_graph_def().node]:\n print(op)\n\n print(logits)\n\nif __name__ == \"__main__\":\n view_ops()","sub_path":"data/vgg16/vgg_helper.py","file_name":"vgg_helper.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"390145348","text":"import os\nimport platform\nimport pathlib\n\nfrom selenium.webdriver import Chrome\nfrom selenium.webdriver import Firefox\nfrom selenium.webdriver.chrome.options import Options\n\nfrom insta_utils.config_helper import ConfigHelper\n\n\ndef get_this_path():\n return str(pathlib.Path(__file__).parent.absolute())\n\n\ndef get_chrome_driver():\n driver_bin_map = {\n \"Windows\": \"chromedriver.exe\",\n \"Darwin\": \"chromedriver\",\n \"Linux\": \"chromedriver\"\n }\n driver_path = os.path.join(get_this_path(), driver_bin_map[platform.system()])\n chrome_options = Options()\n chrome_options.add_argument(\"--lang=en\")\n driver = Chrome(executable_path=driver_path, service_args=[\"--verbose\"], options=chrome_options)\n return driver\n\n\ndef get_firefox_driver():\n driver_bin_map = {\n \"Windows\": \"geckodriver.exe\",\n \"Darwin\": \"geckodriver\",\n \"Linux\": \"geckodriver\"\n }\n driver_path = os.path.join(get_this_path(), driver_bin_map[platform.system()])\n firefox_bin = ConfigHelper().get_firefix_binary_path()\n driver = Firefox(firefox_binary=firefox_bin, executable_path=driver_path)\n return driver\n","sub_path":"insta_utils/browser_drivers/browser_helper.py","file_name":"browser_helper.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"180481693","text":"#!/usr/bin/python\n\nfrom __future__ import division, print_function\nimport numpy as np\nimport pandas as pd\nfrom scipy.optimize import linprog\nfrom ast import literal_eval\nimport argparse\nfrom itertools import product\nimport time\nimport os\nimport sys\n\n# see the accompanying notebook version for more information on the general strategy (how to prioritize the\n# matchings) and the linear program (the idea of a 3D tensor, constraints, etc.)\n# it also shows the form of intermediate data (e.g. the data frames of tutor/tutee info) which may be useful to see\n\n\ndef load_tutor_info(data_path, verbose=False):\n \"\"\"\n Reads in the tutor data which must be in a file named tutor_info.txt in the directory specified by data_path.\n Columns expected in the tutor_info file are tutor id, tutor name, list of classes they will tutor, number of\n hours of availability, and number of matches they already have.\n :param data_path: path to the directory with the tutor info file\n :param verbose: whether to print out information about minor issues in the input data and how they're handled\n \"\"\"\n \n tutor_info = pd.read_csv(data_path + 'tutor_info.txt', sep='\\t', header=None, index_col=0,\n names=['id', 'name', 'classes', 'avail_hours', 'n_matches']).sort_index()\n tutor_info.classes = tutor_info.classes.apply(literal_eval)\n\n n_zero_hours = (tutor_info.avail_hours == 0).sum()\n if n_zero_hours > 0:\n if verbose:\n print(\"{} tutors had 0 hours available and are thus being dropped.\".format(n_zero_hours))\n tutor_info.drop(tutor_info[tutor_info.avail_hours == 0].index, inplace=True)\n\n max_matches = 3\n n_max_matches = (tutor_info.n_matches >= max_matches).sum()\n if n_max_matches > 0:\n if verbose:\n print(\"{} tutors had {} matches already and are thus being dropped.\".format(n_max_matches, max_matches))\n tutor_info.drop(tutor_info[tutor_info.n_matches == max_matches].index, inplace=True)\n\n n_no_classes = (tutor_info.classes.apply(len) == 0).sum()\n if n_no_classes > 0:\n if verbose:\n print(\"{} tutors had an empty class list and are thus being dropped.\".format(n_no_classes))\n tutor_info.drop(tutor_info[tutor_info.classes.apply(len) == 0].index, inplace=True)\n return tutor_info\n\n\ndef load_tutee_info(data_path, verbose=False):\n \"\"\"\n Reads in the tutee data which must be in a file named tutee_info.txt in the directory specified by data_path\n (entered as a command-line argument with default value of the current directory).\n Columns expected in the tutee_info file are tutee id, tutee name, list of classes requested for tutoring and\n number of matches they already have.\n :param data_path: path to the directory with the tutee info file\n :param verbose: whether to print out information about minor issues in the input data and how they're handled\n \"\"\"\n \n tutee_info = pd.read_csv(data_path + 'tutee_info.txt', sep='\\t', header=None, index_col=0,\n names=['id', 'name', 'classes', 'n_matches']).sort_index()\n tutee_info.classes = tutee_info.classes.apply(literal_eval)\n\n n_no_classes = (tutee_info.classes.apply(len) == 0).sum()\n if n_no_classes > 0:\n if verbose:\n print(\"{} tutees had an empty class list and are thus being dropped.\".format(n_no_classes))\n tutee_info.drop(tutee_info[tutee_info.classes.apply(len) == 0].index, inplace=True)\n\n return tutee_info\n\n\ndef get_class_priority_and_mappings(tutor_info, tutee_info):\n \"\"\"\n Computes the priority assigned to each class as the number of tutees requesting that class divided by the number of tutors available\n for that class (a priority of 0 is always given if a class doesn't have both tutees and tutors)\n Also returns a few useful mappings to/from class names.\n :returns: class_priority: pandas dataframe with columns class_name, priority\n class_to_id: map from class names to ids (as given in the input files)\n class_to_idx: map from class names to indices, which are [0:n_classes] and given in order according to class_priority\n idx_to_class: inverse map of class_to_idx\n \"\"\"\n \n # extract just a list of names of classes per tutor/tutee; reduce these into one long list; make a Series mapping names to counts\n # then set priority = n_tutees / n_tutors for each class\n tutees_per_class = pd.Series(reduce(lambda x, y: x + y, tutee_info.classes.apply(lambda x: [elem[1] for elem in x]))).value_counts()\n tutors_per_class = pd.Series(reduce(lambda x, y: x + y, tutor_info.classes.apply(lambda x: [elem[1] for elem in x]))).value_counts()\n class_priority = (tutees_per_class / tutors_per_class).fillna(0).reset_index() # NA occurs when a class doesn't have both tutors and tutees\n class_priority.rename(columns={'index': 'class_name', 0: 'priority'}, inplace=True)\n class_priority.sort_values('priority', inplace=True)\n class_priority.priority /= class_priority.priority.sum() # normalize\n \n class_id_name = np.concatenate((tutee_info.classes.map(lambda class_list: [class_elem[:2] for class_elem in class_list]).values,\n tutor_info.classes.values))\n class_to_id = {name: idx for (idx, name) in reduce(lambda x, y: x + y, class_id_name)} # id is whatever was in the input file\n class_to_idx = {class_priority.class_name.values[i]: i for i in xrange(len(class_priority))} # idx is [0 : n_classes]\n idx_to_class = {val: key for (key, val) in class_to_idx.items()}\n return class_priority, class_to_id, class_to_idx, idx_to_class\n\n\ndef get_idx(tutor_idx, tutee_idx, class_idx, n_tutees, n_tutors, n_classes):\n \"\"\"\n Computes the index in the 1D array corresponding to (tutor_idx, tutee_idx, class_idx) in the\n imagined 3D tensor\n \"\"\"\n assert tutor_idx < n_tutors\n assert tutee_idx < n_tutees\n assert class_idx < n_classes\n return tutee_idx + n_tutees * tutor_idx + n_tutees * n_tutors * class_idx\n\n\ndef get_triple_idx(idx, n_tutees, n_tutors):\n \"\"\"\n Does the inverse of get_idx: returns the (tutor_idx, tutee_idx, class_idx) corresponding to idx\n \"\"\"\n class_idx = 0\n while idx - (n_tutees * n_tutors) >= 0:\n class_idx += 1\n idx -= (n_tutees * n_tutors)\n \n tutor_idx = 0\n while idx - n_tutees >= 0:\n tutor_idx += 1\n idx -= n_tutees\n tutee_idx = idx\n return tutor_idx, tutee_idx, class_idx\n\n\ndef get_class_list_constraints(tutor_info, tutee_info, n_variables, get_class_idx):\n \"\"\"\n Computes and returns constraints & bounds that will enforce that no matching occurs between a tutor and tutee unless it\n is in a class which occurs in both of their class lists.\n :returns: class_list_bounds, class_list_constraints (both are numpy arrays that can be passed to scipy.optimize.linprog\n as constraints / bounds, respectively)\n \"\"\"\n \n n_tutees = len(tutee_info)\n n_tutors = len(tutor_info)\n n_classes = n_variables / (n_tutees * n_tutors)\n \n class_list_bounds = 0\n class_list_constraints = np.ones((1, n_variables))\n\n # set indices to 0 where the proposed matchings are valid; then any >= 0 value is possible for those matchings\n # the others will be forced to be 0 because we'll constrain their sum to be 0\n for tutor_idx in xrange(n_tutors):\n tutor_class_indices = get_class_idx([elem[1] for elem in tutor_info.classes.iloc[tutor_idx]]) # elem[1] is class name\n for class_idx in tutor_class_indices:\n for tutee_idx in xrange(n_tutees):\n tutee_class_indices = get_class_idx([elem[1] for elem in tutee_info.classes.iloc[tutee_idx]])\n if class_idx in tutee_class_indices:\n class_list_constraints[0, get_idx(tutor_idx, tutee_idx, class_idx, n_tutees, n_tutors, n_classes)] = 0\n \n return class_list_bounds, class_list_constraints\n\n\ndef get_hours_constraints(tutor_info, tutee_info, n_variables, get_class_idx, iterative_matching):\n \"\"\"\n Computes and returns constraints & bounds that will enforce that no tutor tutors more hours than they have available\n and that no tutee receives more tutoring in a class than they requested.\n :returns: hours_bounds, hours_constraints (both are numpy arrays that can be passed to scipy.optimize.linprog\n as constraints / bounds, respectively)\n \"\"\"\n n_tutors = len(tutor_info)\n n_tutees = len(tutee_info)\n n_classes = n_variables / (n_tutors * n_tutees)\n \n hours_constraints = []\n hours_bounds = []\n\n # tutees need one constraint per class (# hours requested is per class)\n for tutor_idx in xrange(n_tutors):\n class_indices = get_class_idx([elem[1] for elem in tutor_info.classes.iloc[tutor_idx]]) # elem[1] is class name\n \n if iterative_matching:\n hours_bounds.append(1)\n else:\n hours_bounds.append(tutor_info.avail_hours.iloc[tutor_idx])\n \n constraint = np.zeros((1, n_variables)) # set indices to 1 where the proposed class is valid for this tutor\n for class_idx in class_indices:\n for tutee_idx in xrange(n_tutees):\n constraint[0, get_idx(tutor_idx, tutee_idx, class_idx, n_tutees, n_tutors, n_classes)] = 1\n hours_constraints.append(constraint)\n\n for tutee_idx in xrange(n_tutees):\n class_indices = get_class_idx([elem[1] for elem in tutee_info.classes.iloc[tutee_idx]]) # elem[1] is class name\n hours_requested = [elem[2] for elem in tutee_info.classes.iloc[tutee_idx]]\n for i in xrange(len(class_indices)):\n class_idx = class_indices[i]\n \n if iterative_matching:\n hours_bounds.append(1)\n else:\n hours_bounds.append(hours_requested[i])\n \n constraint = np.zeros((1, n_variables)) # set indices to 1 where the proposed class is valid for this tutee\n for tutor_idx in xrange(n_tutors):\n constraint[0, get_idx(tutor_idx, tutee_idx, class_idx, n_tutees, n_tutors, n_classes)] = 1\n hours_constraints.append(constraint)\n\n hours_constraints = np.concatenate(hours_constraints, axis=0)\n hours_bounds = np.array(hours_bounds)\n return hours_bounds, hours_constraints\n\n\ndef get_objective(lambda_classes, lambda_students, class_priority, n_tutors, n_tutees, n_classes, get_class_idx, tutee_info):\n \"\"\"\n Generates an objective function that can be optimized using a linear program.\n What is actually returned is a 1D numpy array whose size is the number of variables.\n Each variable is represented by one index in the array. If we call the array A and the\n variables V, then the function to be optimized is\n sum_i V_i * A_i.\n That is, we maximize the weighted sum of the variables. The variables are implicit as far\n as the optimization is concerned: they are not explicitly encoded; one needs to know what\n each index corresponds to.\n Here, the weights are based on the per-class priorities and whether the students have priority\n for a given class.\n :param lambda_classes: how much weight to put on the per-class priorities. The larger the lambda\n values are, the more focus is given to high priority classes/students (even\n at the expense of matching less tutoring hours overall)\n :param lambda_students: how much weight to put on the student priorities for given classes\n :returns: a 1D numpy array where each value is the coefficient for the implicit variable at that\n index\n \"\"\"\n n_variables = n_tutors * n_tutees * n_classes\n # scale priorities by lambdas\n scaled_class_priorities = lambda_classes * class_priority.priority.values\n objective_function = np.ones(n_variables)\n\n for class_idx in xrange(n_classes):\n priority = scaled_class_priorities[class_idx]\n for tutor_idx in xrange(n_tutors):\n for tutee_idx in xrange(n_tutees):\n objective_function[get_idx(tutor_idx, tutee_idx, class_idx, n_tutees, n_tutors, n_classes)] *= priority\n\n for tutee_idx in xrange(n_tutees):\n class_indices = get_class_idx([elem[1] for elem in tutee_info.classes.iloc[tutee_idx]]) # elem[1] is class name\n priorities = [elem[3] for elem in tutee_info.classes.iloc[tutee_idx]]\n for i in xrange(len(class_indices)):\n class_idx = class_indices[i]\n priority = .01 + lambda_students * priorities[i] # so priority of 0 -> 1; we don't want to ignore students with no priority\n for tutor_idx in xrange(n_tutors):\n before = objective_function[get_idx(tutor_idx, tutee_idx, class_idx, n_tutees, n_tutors, n_classes)]\n objective_function[get_idx(tutor_idx, tutee_idx, class_idx, n_tutees, n_tutors, n_classes)] *= priority\n after = objective_function[get_idx(tutor_idx, tutee_idx, class_idx, n_tutees, n_tutors, n_classes)]\n return objective_function\n\n\ndef solve(objective_function, hours_constraints, hours_bounds, class_list_constraints, class_list_bounds, var_bounds, verbose=False):\n \"\"\"\n Uses a linear program to maximize the given objective function subject to the constraints\n which must be present as global variables: hours_constraints, hours_bounds, class_list_constraint,\n and class_list_bound.\n Attempts first a quick program with fewer bounds. If this fails (in that the solution is outside the desired bounds)\n a slower, completely bounded program is run.\n :param objective_function: a 1D numpy array as specified as the return value of get_objective.\n :returns: A scipy.optimize.OptimizeResult consisting of the following fields:\n x : (numpy ndarray) The independent variable vector which optimizes the linear programming problem.\n slack : (numpy ndarray) The values of the slack variables. Each slack variable corresponds to an inequality\n constraint. If the slack is zero, then the corresponding constraint is active.\n success : (bool) Returns True if the algorithm succeeded in finding an optimal solution.\n status : (int) An integer representing the exit status of the optimization:\n 0 : Optimization terminated successfully\n 1 : Iteration limit reached\n 2 : Problem appears to be infeasible\n 3 : Problem appears to be unbounded\n nit : (int) The number of iterations performed.\n message : (str) A string descriptor of the exit status of the optimization.\n \"\"\"\n solution = linprog(-objective_function, options={'disp': verbose},\n A_ub=hours_constraints, b_ub=hours_bounds,\n A_eq=class_list_constraints, b_eq=class_list_bounds)\n \n max_hours = var_bounds[1]\n if solution.x.max() > max_hours:\n if verbose:\n print('Quick solution exceeded max_hours ({} hours in a matching; max is {}).'.format(solution.x.max(), max_hours))\n print('Running slower, bounded program.')\n solution = linprog(-objective_function, bounds=var_bounds, options={'disp': verbose},\n A_ub=hours_constraints, b_ub=hours_bounds,\n A_eq=class_list_constraints, b_eq=class_list_bounds)\n return solution\n\n\ndef update_info(tutor_info, tutee_info, matching, max_tutees_per_tutor=3):\n \"\"\"\n Updates tutor_info and tutee_info based on the given matchings:\n Determines the number of hours to assign for each matching\n Removes the appropriate number of hours available from the tutors\n Removes matched classes from the classes list of tutees\n Drops tutors with 0 hours left\n Drops tutees with no classes left\n WARNING: all parameters are modified in place.\n \"\"\"\n \n for match_idx in xrange(len(matching)):\n tutor_id, tutee_id, class_id = matching.loc[match_idx, ['tutor_id', 'tutee_id', 'class_id']]\n avail_hours = tutor_info.loc[tutor_id].avail_hours\n classes = tutee_info.loc[tutee_id].classes\n request_hours = filter(lambda class_elem: class_elem[0] == class_id, classes)[0][2]\n\n if request_hours > 4:\n assign_hours = 3\n elif request_hours > 2:\n assign_hours = 2\n else:\n assign_hours = 1\n\n assign_hours = min(avail_hours, assign_hours)\n matching.loc[match_idx, 'n_hours'] = assign_hours\n\n hours_left = avail_hours - assign_hours\n n_matches = tutor_info.loc[tutor_id, 'n_matches'] + 1\n if hours_left > 0 and n_matches < max_tutees_per_tutor:\n tutor_info.loc[tutor_id, 'avail_hours'] = hours_left\n tutor_info.loc[tutor_id, 'n_matches'] = n_matches\n else:\n tutor_info.drop(tutor_id, inplace=True)\n\n classes_left = filter(lambda class_elem: class_elem[0] != class_id, classes)\n if len(classes_left) > 0:\n tutee_info = tutee_info.set_value(tutee_id, 'classes', classes_left) # because value is a list, need this syntax\n else:\n tutee_info.drop(tutee_id, inplace=True)\n\n\ndef get_matching(solution, tutor_info, tutee_info, idx_to_class, class_to_id, lambda_classes, lambda_students,\n iterative_matching, return_matching=False, verbose=False):\n \"\"\"\n Converts the solution to the tutor-tutee matching linear program into the desired output file format:\n a tsv with columns ['tutor_id', 'tutor_name', 'tutee_id', 'tutee_name', 'class_id', 'class_name', 'n_hours']\n which specifies all tutor-tutee matchings.\n :param solution: a scipy.optimize.OptimizeResult as returned from scipy.optimize.linprog (e.g. through the solve function)\n :param return_matching: whether to save the matching file to disk (if False) or to return it\n :param verbose: whether to print the name of the matching file.\n \"\"\"\n \n n_tutees = len(tutee_info)\n n_tutors = len(tutor_info)\n tutor_to_idx = {tutor_info.index.values[i]: i for i in xrange(n_tutors)}\n tutee_to_idx = {tutee_info.index.values[i]: i for i in xrange(n_tutees)}\n idx_to_tutor = {val: key for (key, val) in tutor_to_idx.items()}\n idx_to_tutee = {val: key for (key, val) in tutee_to_idx.items()}\n \n solution.x = solution.x.astype(np.int32)\n \n matched_indices = np.argwhere(solution.x != 0).ravel()\n matches = []\n for matched_idx in matched_indices:\n tutor_idx, tutee_idx, class_idx = get_triple_idx(matched_idx, n_tutees, n_tutors)\n tutor_id = idx_to_tutor[tutor_idx]\n tutor_name = tutor_info.name.loc[tutor_id]\n tutee_id = idx_to_tutee[tutee_idx]\n tutee_name = tutee_info.name.loc[tutee_id]\n class_name = idx_to_class[class_idx]\n class_id = class_to_id[class_name]\n n_hours = solution.x[matched_idx]\n matches.append([tutor_id, tutor_name, tutee_id, tutee_name, class_id, class_name, n_hours])\n matches = pd.DataFrame(matches,\n columns=['tutor_id', 'tutor_name', 'tutee_id', 'tutee_name', 'class_id', 'class_name', 'n_hours'])\n if return_matching:\n return matches\n else:\n fname = '{}matches_lc_{}_ls_{}_{}.tsv'.format(data_path, lambda_classes, lambda_students,\n 'iter' if iterative_matching else 'single')\n matchings.to_csv(fname, sep='\\t', index=False)\n print(\"Saved matching to {}\".format(fname))\n\n\ndef main(data_path, max_hours, verbose, use_product, lambda_classes, lambda_students, iterative_matching, return_matching=False):\n \"\"\"\n :param return_matching: if True, only one matching is computed and then returned (i.e. one can't use multiple lambda values\n and only one iteration of matching will be done, regardless of the value of iterative_matching)\n \"\"\"\n \n if use_product:\n lambdas = list(product(lambda_classes, lambda_students))\n else:\n lambdas = zip(lambda_classes, lambda_students)\n \n tutor_info_complete = load_tutor_info(data_path, verbose)\n tutee_info_complete = load_tutee_info(data_path, verbose)\n \n for lambda_idx in xrange(len(lambdas)):\n \n print(\"\\nSolving LP with lambda_classes = {}, lambda_students = {}.\".format(*lambdas[lambda_idx]))\n \n tutor_info = tutor_info_complete.copy()\n tutee_info = tutee_info_complete.copy()\n \n matchings = []\n iter_number = 0\n while True:\n iter_number += 1\n if verbose:\n print(\"\\nOn iteration\", iter_number)\n \n n_tutors = len(tutor_info)\n n_tutees = len(tutee_info)\n\n ### class priorities and info\n class_priority, class_to_id, class_to_idx, idx_to_class = get_class_priority_and_mappings(tutor_info, tutee_info)\n n_classes = len(class_priority)\n get_class_idx = np.vectorize(class_to_idx.get)\n\n ### bounds/constraints on the linear program\n\n n_variables = n_tutors * n_tutees * n_classes\n\n var_bounds = (0, max_hours) # same bound for all matchings\n class_list_bounds, class_list_constraints = get_class_list_constraints(tutor_info, tutee_info, n_variables, get_class_idx)\n hours_bounds, hours_constraints = get_hours_constraints(tutor_info, tutee_info, n_variables, get_class_idx, iterative_matching)\n\n objective_function = get_objective(lambdas[lambda_idx][0], lambdas[lambda_idx][1], class_priority,\n n_tutors, n_tutees, n_classes, get_class_idx, tutee_info)\n solution = solve(objective_function, hours_constraints, hours_bounds, class_list_constraints, class_list_bounds, var_bounds,\n verbose)\n \n if not iterative_matching and not return_matching:\n get_matching(solution, tutor_info, tutee_info, idx_to_class, class_to_id,\n lambdas[lambda_idx][0], lambdas[lambda_idx][1], iterative_matching, verbose=verbose)\n sys.exit()\n \n if return_matching:\n return get_matching(solution, tutor_info, tutee_info, idx_to_class, class_to_id, lambdas[lambda_idx][0],\n lambdas[lambda_idx][1], iterative_matching,verbose=verbose, return_matching=True)\n \n # otherwise: iterative matching and should save final result instead of returning 1 iteration of it\n matching = get_matching(solution, tutor_info, tutee_info, idx_to_class, class_to_id,\n lambdas[lambda_idx][0], lambdas[lambda_idx][1], iterative_matching, return_matching=True)\n \n if len(matching) == 0:\n break\n\n matchings.append(matching)\n update_info(tutor_info, tutee_info, matching)\n\n if len(tutor_info) == 0 or len(tutee_info) == 0:\n break\n\n matchings = pd.concat(matchings).reset_index(drop=True)\n \n ### give swap in tutors with 0 matches for those who have multiple\n zero_match_tutors = tutor_info[tutor_info.n_matches == 0]\n \n n_zero_match_tutors = len(zero_match_tutors)\n if verbose:\n if n_zero_match_tutors:\n print(\"\\nFound {} tutors with 0 matches. Attempting to swap them in.\".format(n_zero_match_tutors))\n else:\n print(\"\\nNo tutors with 0 matches found.\")\n \n for tutor_id in zero_match_tutors.index:\n class_ids = map(lambda class_elem: class_elem[0], zero_match_tutors.loc[tutor_id, 'classes']) # just get the ids\n matching_to_swap = None\n most_matches = 0\n for row in matchings.index:\n if matchings.loc[row, 'class_id'] in class_ids:\n swapped_tutor_id = matchings.loc[row, 'tutor_id']\n n_matches = matchings.tutor_id.value_counts().loc[swapped_tutor_id]\n if n_matches > max(1, most_matches):\n most_matches = n_matches\n matching_to_swap = [row, swapped_tutor_id, matchings.loc[row, 'n_hours'], matchings.loc[row, 'tutee_id'],\n matchings.loc[row, 'class_id']]\n\n if matching_to_swap: # not None\n # update the matching to use the zero-match tutor swapped for the old one\n row, swapped_tutor_id, swapped_hours, tutee_id, class_id = matching_to_swap\n hours_requested = filter(lambda class_elem: class_elem[0] == class_id, tutee_info_complete.loc[tutee_id, 'classes'])[0][2]\n hours_matched = min(zero_match_tutors.loc[tutor_id, 'avail_hours'], hours_requested)\n matchings.loc[row, 'tutor_id'] = tutor_id\n matchings.loc[row, 'tutor_name'] = zero_match_tutors.loc[tutor_id, 'name']\n matchings.loc[row, 'n_hours'] = hours_matched\n\n # also update the tutor info based on the swap; we'll try one more LP, just in case\n tutor_info.loc[tutor_id, 'n_matches'] += 1\n tutor_info.loc[tutor_id, 'avail_hours'] -= hours_matched\n\n if swapped_tutor_id in tutor_info.index: # edit existing entry\n tutor_info.loc[swapped_tutor_id, 'n_matches'] -= 1\n tutor_info.loc[swapped_tutor_id, 'avail_hours'] += swapped_hours\n else: # put an entry back in; make sure to update hours and matchings based on existing matchings\n tutor_info = tutor_info.append(tutor_info_complete.loc[swapped_tutor_id])\n tutor_info.loc[swapped_tutor_id, 'n_matches'] = len(matchings.loc[[swapped_tutor_id]])\n tutor_info.loc[swapped_tutor_id, 'avail_hours'] -= matchings.loc[[swapped_tutor_id], 'n_hours'].sum()\n\n if tutor_info.loc[tutor_id, 'avail_hours'] == 0:\n tutor_info.drop(tutor_id, inplace=True)\n \n if n_zero_match_tutors:\n # do one more matching, just in case anybody swapped out could be matched still\n tutor_info.to_csv('tmp/tutor_info.txt', sep='\\t', header=None)\n tutee_info.to_csv('tmp/tutee_info.txt', sep='\\t', header=None)\n\n matching = main('tmp/', max_hours, verbose, use_product, [lambdas[lambda_idx][0]], [lambdas[lambda_idx][1]],\n iterative_matching=True, return_matching=True)\n update_info(tutor_info, tutee_info, matching)\n matchings = pd.concat((matchings, matching))\n \n ### increase the number of hours in matchings where allowable\n hours_remaining = tutor_info_complete.avail_hours - matchings.groupby('tutor_id').n_hours.sum().sort_index()\n hours_remaining = hours_remaining[hours_remaining > 0]\n \n if verbose:\n print(\"\\nExpanding the number of hours for matches where possible.\")\n for tutor_id in hours_remaining.index:\n matchings.set_index('tutor_id', inplace=True)\n tutor_info_tmp = tutor_info_complete.loc[[tutor_id]].copy() # selecting with \"[]\" keeps it a dataframe instead of a series\n tutor_info_tmp.loc[:, 'avail_hours'] = hours_remaining.loc[tutor_id]\n tutee_info_tmp = tutee_info_complete.loc[matchings.loc[[tutor_id]].tutee_id].copy()\n\n for i in xrange(len(tutee_info_tmp)):\n tutee_id = tutee_info_tmp.index[i]\n matched_class = filter(lambda class_elem: class_elem[0] == matchings.loc[[tutor_id]].iloc[i].class_id,\n tutee_info_tmp.iloc[i].classes)\n tutee_info_tmp.set_value(tutee_id, 'classes', matched_class)\n\n tutor_info_tmp.to_csv('tmp/tutor_info.txt', sep='\\t', header=None)\n tutee_info_tmp.to_csv('tmp/tutee_info.txt', sep='\\t', header=None)\n\n matching = main('tmp/', max_hours, verbose, use_product, [lambdas[lambda_idx][0]], [lambdas[lambda_idx][1]],\n iterative_matching=False, return_matching=True)\n matchings = matchings.reset_index().set_index(['tutor_id', 'tutee_id'])\n \n for row_idx in xrange(len(matching)):\n tutee_id, n_hours = matching.iloc[row_idx].loc[['tutee_id', 'n_hours']]\n matchings.loc[(tutor_id, tutee_id), 'n_hours'] += n_hours\n matchings.reset_index(inplace=True)\n \n assert all(matchings.groupby('class_id').tutee_id.value_counts() == 1)\n assert all(matchings.tutor_id.value_counts() <= 3)\n \n fname = '{}matches_lc_{}_ls_{}_{}.tsv'.format(data_path, lambdas[lambda_idx][0], lambdas[lambda_idx][1],\n 'iter' if iterative_matching else 'single')\n matchings.to_csv(fname, sep='\\t', index=False)\n print(\"Saved matching to {}\".format(fname))\n\n if verbose:\n runtime = time.time() - start_time\n print(\"\\nRuntime: {:.0f} seconds\".format(runtime))\n\n\nif __name__ == \"__main__\":\n start_time = time.time()\n parser = argparse.ArgumentParser()\n parser.add_argument('-lc', '--lambda_classes', nargs='+', type=float, default=[1],\n help=\"The coefficients that determine how much weight is given to prioritizing 'harder'\\\n classes (those with more tutees compared to tutors); must be strictly positive. Default: 1\")\n parser.add_argument('-ls', '--lambda_students', nargs='+', type=float, default=[1],\n help=\"The coefficients that determine how much weight is given to prioritizing students\\\n in especial need (those marked as priority for a given class); must be strictly positive. Default: 1\")\n parser.add_argument('-p', '--data_path', help=\"Path to the input files (tutee_info.txt and tutor_info.txt). Default: ./\",\n default='./')\n parser.add_argument('-m', '--max_hours', help=\"Maximum number of hours allowable in one match (if doing iterative matching, this\\\n will always be set to 1). Default: 3\", type=int, default=3)\n parser.add_argument('-v', '--verbose', action='store_true',\n help=\"Whether to print addition information while running. Default: False\", default=False)\n parser.add_argument('-sm', '--single_matching', action='store_true', help=\"Whether to use iterative matching (see notebook for\\\n more on this approach) or single matching; Default: False (i.e. use iterative matching).\", default=False)\n parser.add_argument('-prod', '--cartesian_product', action='store_true', default=False,\n help=\"If this flag is given, one matching is computed for each combination of\\\n lambda_classes and lambda_students. Otherwise, the two are zipped. Example: if\\\n lambda_students = [2, 5] and lambda_classes = [2, 3] then without this flag, 2 matchings\\\n will be computed with lambdas: (2, 2) and (5, 3). With this flag set, 4 matchings will\\\n be computed: (2, 2), (2, 3), (5, 2), (5, 3). Default: False.\")\n \n args = parser.parse_args()\n data_path = args.data_path\n verbose = args.verbose\n use_product = args.cartesian_product\n lambda_classes = args.lambda_classes\n lambda_students = args.lambda_students\n iterative_matching = not args.single_matching\n \n if iterative_matching:\n max_hours = 1\n \n if verbose:\n print(\"Data path:\", data_path)\n print(\"lambda_students:\", lambda_students)\n print(\"lambda_classes:\", lambda_classes)\n print(\"Use Cartesian product of lambdas?\", use_product)\n print(\"max_hours:\", max_hours, end='\\n\\n')\n print(\"iterative_matching?\", iterative_matching)\n\n main(data_path, max_hours, verbose, use_product, lambda_classes, lambda_students, iterative_matching)","sub_path":"matching.py","file_name":"matching.py","file_ext":"py","file_size_in_byte":32207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"398415721","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nimport xadmin\nfrom apps.car.models import Carinfo, Carimageinfo\n\n\nclass CarinfoAdmin(object):\n list_display = ['CarId', 'CarName', 'ImageUrl', 'Load', 'LengthWidthHeight', 'CarType']\n # search_fields = ['CarName', ]\n # list_filter = ['CarId', 'CarName', 'Load', 'LengthWidthHeight', 'CarType']\n # class CarimageinfoInline(object):\n # model = Carimageinfo\n # exclude = [\"CarId\", ]\n # extra = 1\n # style = 'tab'\n #\n # inlines = [CarimageinfoInline]\n\nclass CarimageinfoAdmin(object):\n list_display = ['CarImageId', 'CarId', 'ImageUrl', 'IsCover']\n\n\nxadmin.site.register(Carinfo, CarinfoAdmin)\nxadmin.site.register(Carimageinfo, CarimageinfoAdmin)\n","sub_path":"XJSExpress/apps/car/adminx.py","file_name":"adminx.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"139997890","text":"import json\nimport requests\nimport re\nfrom collections import Counter\n\noutput_file = \"liu_arleen_lab2part1step4.txt\"\n\ndata = requests.get(\"http://www.recipepuppy.com/api/?\", params={'i':'beans,cheese', \"q\":'burrito', \"p\":'3'}).json()\n\nresults = []\n\ncount=0\nmatches=[]\n\nfor i in data['results']:\n\n\tif (count<3):\n\t\tprint (i['title'])\n\t\tresults.append(i['title'])\t\t\n \n\tcount=count+1\n\ntracker = 0\nnewMatch = []\n\nfor i in data['results']:\n\n\tif (tracker<3):\n\t\tmatches=re.sub(\", \",\"\\n\",str(i['ingredients']))\n\t\tnewMatch = newMatch + re.findall('.*\\n', matches)\n\t\t#results.append(str(matches))\n\t\t#print (str(matches))\n\n\ttracker=tracker+1\t\n\n#print(str(Counter(newMatch).items()))\nnewMatch = Counter(newMatch).items()\nnewMatch = sorted(newMatch)\n\ndef getKey(item):\n\treturn item[0]\n\nfor i in newMatch:\n\tprint(str(i[1])+\" \"+str(i[0]))\n\tresults.append(str(i[1])+\" \"+str(i[0]))\n\nwith open(output_file, 'w') as file:\n\tfor i in results:\n\t\tfile.write(str(i))","sub_path":"lab2/liu_arleen_lab2part1step4.py","file_name":"liu_arleen_lab2part1step4.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"586516005","text":"# coding: utf-8\nfrom blog.models import Post, Komment\nfrom django.views.generic import ListView, DetailView\nimport datetime\nfrom django.utils import timezone\nfrom django.shortcuts import get_object_or_404,render_to_response, redirect\nfrom django.http import HttpResponseRedirect,HttpResponse\nfrom django.core.urlresolvers import reverse\nfrom django.views import generic\nfrom blog.forms import ContactForm\nfrom django.template import RequestContext\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n\n\ndef PostsListView(request): \n post = Post.objects.all()\n post = post.order_by('-datetime')\n paginator = Paginator(post, 10) \n stran = paginator.page_range\n page = request.GET.get('page')\n try:\n post = paginator.page(page)\n except PageNotAnInteger: \n post = paginator.page(1)\n except EmptyPage:\n post = paginator.page(paginator.num_pages)\n\n return render_to_response('blog/post_list.html', {\"post\": post, \"stran\": stran})\n \ndef full(request,pk):\n komment = Komment.objects.filter(id_post__exact=pk)\n komment = komment.order_by('-datetime')\n post = Post.objects.filter(id__exact=pk)\n if request.method == 'POST':\n form = ContactForm(request.POST)\n if form.is_valid():\n name = form.cleaned_data['subject']\n content = form.cleaned_data['message']\n p=Komment(\n name = name,\n content = content,\n id_post = pk,\n )\n p.save()\n results=Komment.objects.all()\n return redirect('/'+pk)\n else:\n form = ContactForm()\n return render_to_response('blog/post_detail.html', {'form': form, 'komment': komment, 'post': post, },context_instance=RequestContext(request))\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"228763100","text":"import sys\nimport re\n# from numpy.random import choice\nimport numpy as np\nimport os\nfrom multiprocessing import Process, Manager, Pool\nimport time\nfrom random import random\nfrom numpy.random import RandomState\n\ndef hash_djb2(s): \n\thash = 5381\n\tfor x in s:\n\t\thash = (( hash << 5) + hash) + ord(x)\n\treturn hash & 0xFFFFFFFF\n\ndef rand(minimum, maximum):\n\treturn minimum + (maximum - minimum) * random()\n\nclass Sparse:\n\tdef __init__(self, dim, count, limit):\n\t\tself.dim = dim\n\t\tself.sparse = {}\n\t\tfor i in range(count):\n\t\t\tself.sparse[int(rand(0, dim))] = rand(-limit, limit)\n#dim = dimension of vector\n#count = number of non-zero values\n#limit = range of the non-zero values\n\n\tdef value(self):\n\t\ta = []\n\t\tfor i in range(self.dim):\n\t\t\ttry:\n\t\t\t\ta.append(self.sparse[i])\n\t\t\texcept:\n\t\t\t\ta.append(0)\n\t\treturn a\n\ndef add(a, b, weight=1):\n\tc = a\n\tfor i in b.sparse:\n\t\ttry:\n\t\t\tc.sparse[i] += (weight * b.sparse[i])\n\t\texcept:\n\t\t\tc.sparse[i] = (weight * b.sparse[i])\n\treturn c\n\ndef cleanhtml(raw_html):\n\tcleanr = re.compile('<.*?>')\n\tcleantext = re.sub(cleanr, ' ', raw_html)\n\treturn cleantext\n\nclass MySentences(object):\n\tdef __init__(self, dirname):\n\t\tself.dirname = dirname\n\n\tdef __iter__(self):\n\t\tpunct = '!\"#$%&\\'()*+,.:;<=>?@[\\\\]^`{|}~'\n\t\tfor root, dirs, files in os.walk(self.dirname):\n\t\t\tfor filename in files:\n\t\t\t\tfile_path = root + '/' + filename\n\t\t\t\tfor line in open(file_path):\n\t\t\t\t\tsline = line.strip()\n\t\t\t\t\tif sline == \"\":\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif sline.startswith('')[0].replace(' ', '_')\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\tsline = 'title/err'\n\t\t\t\t\t\t\tprint(line)\n\t\t\t\t\trline = cleanhtml(sline)\n\t\t\t\t\t# print(file_path)\n\t\t\t\t\tyield re.sub(r'[%s]' % punct, '', rline).lower().split()\n\n#using numpy\n# def randomVector(num):\n# q = 1./30\n# return choice([0, 1], size=num, p=[1 - q, q])\n\n# generate sparse random vectors fast using time.time()\n\n#using fastrand\n# def randomVector(dim):\n# rv = np.zeros(dim)\n# for i in range(10):\n# rv[fastrand.pcg32bounded(dim)] = fastrand.pcg32bounded(5)\n# return rv\n\ndef generateEmbeddings(embeddings, sentence, title):\n\tdim = 500#vector dimens\n\twindow = 6#window for context words\n\tcount = 2#number of non-zero values\n\tlimit = 5#range of non-zero values\n\twt = 1\n\t# try:\n\t# \tindex[title]\n\t# except:\n\t# \tindex[title] = Sparse(dim, count, limit)\n\n\tif len(sentence) >= window:\n\t\tfor i in range(len(sentence) - window):\n\t\t\tif sentence[i].startswith(\"resource/\"):\n\t\t\t\t#add index vector of title entity\n\t\t\t\ttry:\n\t\t\t\t\t# embeddings[sentence[i]] = add(embeddings[sentence[i]], index[title], 5)\n\t\t\t\t\tembeddings[sentence[i]] = embeddings[sentence[i]] + (5 * RandomState(hash_djb2(title)).normal(0, 0.1, dim))\n\t\t\t\texcept:\n\t\t\t\t\t# embeddings[sentence[i]] = Sparse(dim, 0, 1)\n\t\t\t\t\t# embeddings[sentence[i]] = add(embeddings[sentence[i]], index[title], 5)s\n\t\t\t\t\tembeddings[sentence[i]] = 5 * RandomState(hash_djb2(title)).normal(0, 0.1, dim)\n\t\t\t\t#neighbouring words\n\t\t\t\t# print(embeddings[sentence[i]])\n\t\t\t\tfor j in range(int(i - window/2), i):#left context\n\t\t\t\t\tif sentence[j].startswith(\"resource/\"):\n\t\t\t\t\t\twt = 3\n\t\t\t\t\telse:\n\t\t\t\t\t\twt = 1\n\t\t\t\t\t# try:\n\t\t\t\t\t# \tembeddings[sentence[j]]\n\t\t\t\t\t# \twt = 3\n\t\t\t\t\t# except:\n\t\t\t\t\t# \twt = 1\n\t\t\t\t\ttry:\n\t\t\t\t\t\t# embeddings[sentence[i]] = add(embeddings[sentence[i]], index[sentence[j]], wt)\n\t\t\t\t\t\tembeddings[sentence[i]] = embeddings[sentence[i]] + (wt * RandomState(hash_djb2(sentence[j])).normal(0, 0.1, dim))\n\t\t\t\t\texcept:\n\t\t\t\t\t\t# index[sentence[j]] = Sparse(dim, count, limit)\n\t\t\t\t\t\t# embeddings[sentence[i]] = add(embeddings[sentence[i]], index[sentence[j]], wt)\n\t\t\t\t\t\tembeddings[sentence[i]] = (wt * RandomState(hash_djb2(sentence[j])).normal(0, 0.1, dim))\n\t\t\t\tfor j in range(i + 1, int(i + (window/2) + 1)):#right context\n\t\t\t\t\tif sentence[j].startswith(\"resource/\"):\n\t\t\t\t\t\twt = 3\n\t\t\t\t\telse:\n\t\t\t\t\t\twt = 1\n\t\t\t\t\ttry:\n\t\t\t\t\t\tembeddings[sentence[i]] = embeddings[sentence[i]] + (wt * RandomState(hash_djb2(sentence[j])).normal(0, 0.1, dim))\n\t\t\t\t\texcept:\n\t\t\t\t\t\t# index[sentence[j]] = Sparse(dim, count, limit)\n\t\t\t\t\t\t# embeddings[sentence[i]] = add(embeddings[sentence[i]], index[sentence[j]], wt)\n\t\t\t\t\t\tembeddings[sentence[i]] = (wt * RandomState(hash_djb2(sentence[j])).normal(0, 0.1, dim))\n\n\t# print(\"Processed \", str(wc), \" words.\", end=\"\\r\")\n\t\t\t# print(sentence[i] + '(' + str(embeddings[sentence[i]]) + ')')\n\t\t\t# print(sentence[i], end=' ')\n\nif __name__ == '__main__':\n\tdirectory = sys.argv[1]\n\tsentences = MySentences(directory)\n\tmanager = Manager()\n\tembeddings = manager.dict()\n\twc = 0\n\ttitle = ''\n\tnow = time.time()\n\n\tpool = Pool()\n\tfor sentence in sentences:\n\t\twc += len(sentence)\n\t\tif len(sentence) > 0 and sentence[0].startswith('title/'):\n\t\t\ttitle = sentence[0].split('title/')[1]\n\t\t\tprint(title)\n\t\telse:\n\t\t\tpool.apply_async(generateEmbeddings, args=(embeddings, sentence, title))\n\tpool.close()\n\tpool.join()\n\n\tprint(\"Processed \", str(wc), \" words.\")\n\n\tprint(\"Time elapsed: \", str(time.time() - now), 's')\n\n\twith open('embeddings', 'w+') as output:\n\t\twith open('labels', 'w+') as op:\n\t\t\tfor word in embeddings.keys():\n\t\t\t\t# output.write(word + ' ==')\n\t\t\t\top.write(word + '\\n')\n\t\t\t\tfor i in embeddings[word]:\n\t\t\t\t\toutput.write(' ' + str(i))\n\t\t\t\toutput.write('\\n')","sub_path":"gsoc2017-akshay/RVA_random.py","file_name":"RVA_random.py","file_ext":"py","file_size_in_byte":5335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"497287938","text":"import os, subprocess, shutil, tempfile\nimport os.path as op\nimport nibabel as nib\nimport numpy as np\nimport pdb\n\n#pdb.set_trace()\n#subprocess.call('source /hd1/scsnl/scripts/face_blur/lin64/bin/maskface_setup.sh',shell=True, executable=\"/bin/bash\")\n\ndef reorient_like(reo_img, ref_img):\n # There is probably a better way, but fslswapdim/reorient2std will not do it\n ref = nib.load(ref_img)\n ref_aff = ref.get_affine()\n ref_ori = nib.orientations.io_orientation(ref_aff)\n reo = nib.load(reo_img)\n reo_ori = nib.orientations.io_orientation(reo.get_affine())\n reo2ref_ori_xfm = nib.orientations.ornt_transform(reo_ori, ref_ori)\n reo_data = nib.orientations.apply_orientation(reo.get_data(), reo2ref_ori_xfm)\n nib.save(nib.Nifti1Image(reo_data, ref_aff), reo_img)\n\ndef mask_face(anat_fullfile):\n temp_dir = tempfile.mkdtemp()\n anat_name = op.basename(anat_fullfile).split('.')[0]\n temp_img = op.join(temp_dir, anat_name + '.img')\n #pdb.set_trace()\n subprocess.call(['fslchfiletype ANALYZE '+ anat_fullfile + ' '+ temp_img],shell=True)\n cwd = os.getcwd()\n os.chdir(temp_dir)\n #pdb.set_trace()\n with open(os.devnull, 'wb') as DEVNULL:\n subprocess.call(['mask_face', anat_name, '-a', '-s', '0.75', '-v', '0', '-m', 'normfilter'],\n stdout = DEVNULL,\n stderr = DEVNULL,\n shell=True\n )\n #pdb.set_trace()\n mask_face_img = op.join(temp_dir, 'maskface', '%s_full_normfilter.img' % anat_name)\n mask_face_nii = op.join(op.dirname(anat_fullfile), anat_name + '_defaced.nii.gz')\n #pdb.set_trace()\n subprocess.call(['fslchfiletype NIFTI_GZ ' + anat_name + ' '+ mask_face_nii],shell=True)\n os.chdir(cwd)\n #shutil.rmtree(temp_dir)\n #reorient_like(mask_face_nii, anat_fullfile)\n return mask_face_nii\n\ndef unmask_brain(raw, defaced):\n anat_name = op.basename(raw).split('.')[0]\n anat_dir = op.dirname(raw)\n raw_nii = nib.load(raw)\n raw_data = raw_nii.get_data().astype(np.float32)\n #pdb.set_trace()\n deface_nii = nib.load(defaced)\n deface_data = deface_nii.get_data().astype(np.float32)\n face_mask = deface_data != raw_data\n # run watershed, get the brain mask, unmask any brain voxels\n stripped = op.join(anat_dir, '%s_watershed.nii.gz' % anat_name)\n # pdb.set_trace()\n #subprocess.call(['/usr/local/freesurfer/bin/mri_watershed ' + raw + ' ' + stripped],shell=True)\n #strip_nii = nib.load(stripped)\n #brain_mask = strip_nii.get_data() > 0\n #mask = op.join(anat_dir, '%s_facemask.nii.gz' % anat_name)\n #eface_data[brain_mask] = raw_data[brain_mask]\n #nib.save(nib.Nifti1Image(face_mask.astype(np.int16), deface_nii.get_affine()), mask)\n #nib.save(nib.Nifti1Image(deface_data, deface_nii.get_affine()), defaced)\n #os.remove(stripped)\n\nraw_anat_file = '/oak/stanford/groups/menon/rawdata/scsnl/100509/visit1/session1/mri/dti/100509_1_1.3T2/dwi_006.nii.gz'\ndefaced_anat_file = mask_face(raw_anat_file) # deface\n#pdb.set_trace()\n#unmask_brain(raw_anat_file, defaced_anat_file) # unblur any voxels mri_watershed thinks are brain\n\n# source freesurfer 6\n# FREESURFER_HOME=...\n# source /hd1/scsnl/scripts/face_blur/lin64/bin/maskface_setup.sh\n","sub_path":"brainImaging/mri/fmri/anonymization/deface/old/deface_gist.py","file_name":"deface_gist.py","file_ext":"py","file_size_in_byte":3256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"559208058","text":"import pandas as pd\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom sklearn.naive_bayes import MultinomialNB, GaussianNB\r\nfrom sklearn import svm\r\nfrom sklearn.model_selection import GridSearchCV \r\n\r\n\r\n# import warnings filter\r\nfrom warnings import simplefilter\r\n# ignore all future warnings\r\nsimplefilter(action='ignore', category=FutureWarning)\r\n\r\n# Load Dataset\r\ndf = pd.read_csv('spam.csv')\r\n\r\n# Split into training and testing dataset\r\nx = df['EmailText']\r\ny = df['Label']\r\n\r\nx_train, y_train = x[0:4457], y[0:4457]\r\nx_test, y_test = x[4457:], y[4457]\r\n\r\n# Extract features\r\ncv = CountVectorizer()\r\nfeatures = cv.fit_transform(x_train)\r\n\r\n# Build Model\r\ntuned_parameters = {\r\n 'kernel': ['linear', 'rbf'],\r\n 'gamma': [1e-3, 1e-4],\r\n 'C': [1, 10, 100, 1000]\r\n}\r\n\r\nmodel = GridSearchCV(svm.SVC(), tuned_parameters)\r\nmodel.fit(features, y_train)\r\n\r\nprint(model.best_params_)\r\n# Test Accuracy\r\nfeatures_test = cv.transform(x_test)\r\nprint('Accuracy of the model is: ', model.score(features_test, y_test))","sub_path":"spam.py","file_name":"spam.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"628094951","text":"# # Methods for I/O operations on image\n\n# imports\nfrom custom_exceptions import GenericException\n\nfrom common.cv_constants import bgr\n\nimport cv2\n\n\ndef read(filename, mode=bgr):\n \"\"\"\n Return image from image_file. Default Mode is bgr (see constants).\n \"\"\"\n image = cv2.imread(filename, mode)\n if image is None:\n raise GenericException('Image file not found!')\n return image\n\n\ndef show(image, window_name='Image_window', delay=0):\n \"\"\"\n Read image from filename, show it in a window named with window_name.\n - delay is the number if milliseconds to wait key press for\n (default 0 means infinitely).\n \"\"\"\n cv2.imshow(window_name, image)\n cv2.waitKey(delay)\n return\n\n\ndef save(image, image_name, file_format='.jpg'):\n \"\"\"\n Save image to filename. Extension will be JPEG if not specified.\n \"\"\"\n cv2.imwrite(image_name + file_format, image)\n return\n","sub_path":"common/IO_image.py","file_name":"IO_image.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"417730251","text":"import logging\nimport os\nimport threading\nimport time\n\nimport pykka\nimport requests\nfrom mopidy import core\n\nimport netifaces\n\nfrom . import Extension\nfrom .brainz import Brainz\n\nlogger = logging.getLogger(__name__)\n\n\nclass OLEDConfig:\n def __init__(self, config=None):\n self.size = 128\n\nclass OLEDFrontend(pykka.ThreadingActor, core.CoreListener):\n def __init__(self, config, core):\n super().__init__()\n self.core = core\n self.config = config\n self.current_track = None\n self._mode = 1\n self._playlistSize = 0\n self._playlistNum = 0\n self._playlist = None\n\n def on_start(self):\n self.display = OLED(self.config)\n self.display.start()\n self.display.update(volume=self.core.mixer.get_volume().get())\n if \"http\" in self.config:\n ifaces = netifaces.interfaces()\n ifaces.remove(\"lo\")\n\n http = self.config[\"http\"]\n if http.get(\"enabled\", False):\n hostname = http.get(\"hostname\", \"127.0.0.1\")\n port = http.get(\"port\", 6680)\n if hostname in [\"::\", \"0.0.0.0\"]:\n family = (\n netifaces.AF_INET6 if hostname == \"::\" else netifaces.AF_INET\n )\n for iface in ifaces:\n hostname = self.get_ifaddress(iface, family)\n if hostname is not None:\n break\n if hostname is not None:\n self.display.update(\n title=f\"Visit http://{hostname}:{port} to select content.\"\n )\n self.display.update_album_art(art=\"\")\n\n def on_stop(self):\n self.display.stop()\n self.display = None\n\n def get_ifaddress(self, iface, family):\n try:\n return netifaces.ifaddresses(iface)[family][0][\"addr\"]\n except (IndexError, KeyError):\n return None\n\n def mute_changed(self, mute):\n pass\n\n def options_changed(self):\n self.display.update(\n shuffle=self.core.tracklist.get_random(),\n repeat=self.core.tracklist.get_repeat(),\n )\n\n def playlist_changed(self, playlist):\n pass\n\n def playlist_deleted(self, playlist):\n pass\n\n def playlists_loaded(self):\n pass\n\n def seeked(self, time_position):\n self.update_elapsed(time_position)\n\n def stream_title_changed(self, title):\n self.display.update(title=title)\n\n def track_playback_ended(self, tl_track, time_position):\n self.update_elapsed(time_position)\n self.display.update(state=\"pause\")\n\n def track_playback_paused(self, tl_track, time_position):\n self.update_elapsed(time_position)\n self.display.update(state=\"pause\")\n\n def track_playback_resumed(self, tl_track, time_position):\n self.update_elapsed(time_position)\n self.display.update(state=\"play\")\n\n def track_playback_started(self, tl_track):\n self.update_track(tl_track.track, 0)\n self.display.update(state=\"play\")\n\n def update_elapsed(self, time_position):\n self.display.update(elapsed=float(time_position))\n\n def update_track(self, track, time_position=None):\n if track is None:\n track = self.core.playback.get_current_track().get()\n\n title = \"\"\n album = \"\"\n artist = \"\"\n\n if track.name is not None:\n title = track.name\n\n if track.album is not None and track.album.name is not None:\n album = track.album.name\n\n if track.artists is not None:\n artist = \", \".join([artist.name for artist in track.artists])\n\n self.display.update(title=title, album=album, artist=artist)\n\n if time_position is not None:\n length = track.length\n # Default to 60s long and loop the transport bar\n if length is None:\n length = 60\n time_position %= length\n\n self.display.update(elapsed=float(time_position), length=float(length))\n\n def tracklist_changed(self):\n pass\n\n def volume_changed(self, volume):\n if volume is None:\n return\n\n self.display.update(volume=volume)\n\n def playlist_list(self):\n self._playlist = self.core.playlists.as_list().get()\n self._playlistSize = len(self._playlist)\n self._playlistNum = 0\n if self._mode == 0:\n self.display.update2(self._playlist, self._playlistNum)\n\n def playlist_prev(self):\n self._playlistNum = self._playlistNum - 1\n if self._playlistNum < 0:\n self._playlistNum = self._playlistSize - 1\n self.display.update2(self._playlist, self._playlistNum)\n\n def playlist_next(self):\n self._playlistNum = (self._playlistNum + 1) % self._playlistSize\n self.display.update2(self._playlist, self._playlistNum)\n\n def playlist_select(self):\n playlist_items = self.core.playlists.get_items(self._playlist[self._playlistNum].uri).get()\n itemURIs = []\n for item in playlist_items:\n itemURIs.append(item.uri)\n self.core.tracklist.clear()\n self.core.tracklist.add(uris=itemURIs)\n\n def custom_command(self, **kwargs):\n target = kwargs.get(\"target\")\n if target == 'oled':\n self._mode = kwargs.get(\"mode\", self._mode)\n self.display.update(mode=self._mode)\n playlist = kwargs.get(\"playlist\")\n if playlist == \"list\":\n self.playlist_list()\n elif playlist == \"next\":\n self.playlist_next()\n elif playlist == \"prev\":\n self.playlist_prev()\n elif playlist == \"select\":\n self.playlist_select()\n\n\nclass OLED:\n def __init__(self, config):\n self.config = config\n self.cache_dir = Extension.get_data_dir(config)\n self.display_config = OLEDConfig(config[\"oled\"])\n self.display_class = Extension.get_display_types()[\n self.config[\"oled\"][\"display\"]\n ]\n\n self._brainz = Brainz(cache_dir=self.cache_dir)\n self._display = self.display_class(self.display_config)\n self._running = threading.Event()\n self._delay = 1.0 / 30\n self._thread = None\n\n self._mode = 1\n\n self.shuffle = False\n self.repeat = False\n self.state = \"stop\"\n self.volume = 100\n self.progress = 0\n self.elapsed = 0\n self.length = 0\n self.title = \"\"\n self.album = \"\"\n self.artist = \"\"\n self._last_progress_update = time.time()\n self._last_progress_value = 0\n self._last_art = \"\"\n\n def start(self):\n if self._thread is not None:\n return\n\n self._running = threading.Event()\n self._running.set()\n self._thread = threading.Thread(target=self._loop)\n self._thread.start()\n\n def stop(self):\n self._running.clear()\n self._thread.join()\n self._thread = None\n self._display.stop()\n\n def _handle_album_art(self, art):\n pass\n\n def update_album_art(self, art=None):\n pass\n\n def update(self, **kwargs):\n self.shuffle = kwargs.get(\"shuffle\", self.shuffle)\n self.repeat = kwargs.get(\"repeat\", self.repeat)\n self.state = kwargs.get(\"state\", self.state)\n self.volume = kwargs.get(\"volume\", self.volume)\n # self.progress = kwargs.get('progress', self.progress)\n self.elapsed = kwargs.get(\"elapsed\", self.elapsed)\n self.length = kwargs.get(\"length\", self.length)\n self.title = kwargs.get(\"title\", self.title)\n self.album = kwargs.get(\"album\", self.album)\n self.artist = kwargs.get(\"artist\", self.artist)\n self._mode = kwargs.get(\"mode\", self._mode)\n\n if \"elapsed\" in kwargs:\n if \"length\" in kwargs:\n self.progress = float(self.elapsed) / float(self.length)\n self._last_elapsed_update = time.time()\n self._last_elapsed_value = kwargs[\"elapsed\"]\n\n def _loop(self):\n while self._running.is_set():\n if self.state == \"play\":\n t_elapsed_ms = (time.time() - self._last_elapsed_update) * 1000\n self.elapsed = float(self._last_elapsed_value + t_elapsed_ms)\n self.progress = self.elapsed / self.length\n if self._mode == 1:\n self._display.update_overlay(\n self.shuffle,\n self.repeat,\n self.state,\n self.volume,\n self.progress,\n self.elapsed,\n self.title,\n self.album,\n self.artist,\n )\n\n if self._mode == 1:\n self._display.redraw()\n time.sleep(self._delay)\n\n def update2(self, playlist, index):\n self._display.update_playlist(playlist, index)\n","sub_path":"mopidy_oled/frontend.py","file_name":"frontend.py","file_ext":"py","file_size_in_byte":9029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"431194847","text":"# Imports\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\nfrom collections import deque\n\n# Environment\nclass Chain:\n\n def __init__ (self):\n self.state = 0\n self.dings = 0\n\n def reset (self):\n self.state = 0\n self.dings = 0\n return 0\n\n def step (self, action):\n\n if action == 1:\n self.state = 0\n return 1\n\n if self.state == 4:\n self.dings += 1\n return 10\n\n self.state += 1\n return 0\n\nenv = Chain ()\n\ndef state_to_array (index):\n z = np.zeros (5)\n z[index] = 1.0\n return z\n\n# Hyperparameters\nnum_episodes = 25\nnum_testepis = 1\nnum_steps = 50\ntau = 10\n\nsize_batch = 100\nsize_memory = 500\n\nlr = 0.8\ngamma = 0.7\n\nmax_eps = 1.0\nmin_eps = 0.01\n\nuse_double = False\ndata_filename = \"DataAllDeepQLearning.csv\"\n\n# Memory\nclass SumTree:\n\n def __init__ (self, capacity):\n self.capacity = capacity\n self.index = 0\n self.data = np.zeros (capacity, dtype=object)\n self.tree = np.zeros (2*capacity - 1)\n # 0\n # ,---'---,\n # 1 2\n # ,-'-, ,-'-,\n # 3 4 5 6\n\n def add (self, priority, data):\n tree_index = self.index + self.capacity - 1\n self.data[self.index] = data\n self.update (tree_index, priority)\n self.index = (self.index + 1) % self.capacity\n\n def update (self, index, priority):\n delta = priority - self.tree[index]\n self.tree[index] = priority\n # cascade up the tree\n while index != 0:\n index = (index - 1)//2\n self.tree[index] += delta\n\n def get_leaf (self, val):\n parent = 0\n while True:\n left = 2*parent + 1\n right = 2*parent + 2\n \n if left >= len (self.tree):\n # if the left child node would exceed the bounds of the tree\n # then the current node is a leaf\n break\n\n if val <= self.tree[left]:\n parent = left\n else:\n val -= self.tree[left]\n parent = right\n\n data = parent - self.capacity + 1\n return parent, self.tree[parent], self.data[data]\n \n @property\n def max_priority (self):\n return np.max (self.tree[-self.capacity:])\n \n @property\n def min_priority (self):\n return np.min (self.tree[-self.capacity:])\n \n @property\n def total_priority (self):\n return self.tree[0]\n\nclass Memory:\n \n def __init__ (self, capacity):\n self.e = 0.01\n self.a = 0.6\n self.b = 0.4\n self.clip = 1.0\n self.tree = SumTree (capacity)\n\n def append (self, experience):\n max_priority = self.tree.max_priority\n if max_priority == 0:\n max_priority = self.clip\n self.tree.add (max_priority, experience)\n\n def sample (self, num):\n batch = []\n b_index = np.empty ((num,), dtype = np.int32)\n b_weight = np.empty ((num,), dtype = np.float32)\n\n priority_segment = self.tree.total_priority / num\n max_weight = num*self.tree.min_priority / self.tree.total_priority\n max_weight = max_weight**(-self.b)\n\n for i in range (num):\n a, b = priority_segment*i, priority_segment*(i + 1)\n value = np.random.uniform (a, b)\n index, priority, data = self.tree.get_leaf (value)\n sampling_probability = priority / self.tree.total_priority\n \n b_weight[i] = (num*sampling_probability)**(-self.b) / max_weight\n b_index[i] = index\n batch.append (data)\n b_weight = np.array (b_weight)\n\n return b_index, batch, b_weight\n\n def batch_update (self, index, err):\n err += self.e\n err = np.minimum (err, self.clip)\n err = np.power (err, self.a)\n for i, e in zip (index, err):\n self.tree.update (i, e)\n\nclass Model (tf.keras.Model):\n\n def __init__ (self):\n super (Model, self).__init__ ()\n l = tf.keras.layers\n self.action_layer = l.Dense (2, input_dim = 5, activation = 'relu')\n self.value_layer = l.Dense (1, input_dim = 5, activation = 'relu')\n self.average_layer = l.Lambda (lambda x: x - tf.reduce_mean (x))\n self.q_layer = l.Add ()\n\n self.compile (optimizer = 'adam',\n loss = 'mean_squared_error',\n metrics = [])\n\n def call (self, x_in):\n x_a = self.action_layer (x_in)\n x_a = self.average_layer (x_a)\n x_v = self.value_layer (x_in)\n return self.q_layer ([x_v, x_a])\n\npolicy_a = Model ()\ntarget_a = Model ()\ntarget_a.set_weights (policy_a.get_weights ())\npolicy_b = Model ()\ntarget_b = Model ()\ntarget_b.set_weights (policy_b.get_weights ())\n\nmemory = Memory (size_memory)\n\n# Populate Memory\n\nfor i in range (size_memory):\n state0 = state_to_array (env.state)\n action = random.randrange (2)\n reward = env.step (action)\n state1 = state_to_array (env.state)\n memory.append ((state0, action, reward, state1))\n\n# Training\n\nscores = []\nfor episode in range (num_episodes):\n eps = max_eps*(min_eps/max_eps)**(episode/num_episodes)\n\n state0 = state_to_array (env.reset ())\n score = 0\n for step in range (num_steps):\n\n # choose action\n action = None\n if random.random () > eps:\n q_vals = policy_a.predict (np.array ([state0]))\n if use_double:\n q_vals = q_vals + policy_b.predict (np.array ([state0]))\n action = np.argmax (q_vals)\n else:\n action = random.randrange (2)\n\n # perform\n reward = env.step (action)\n score += reward\n state1 = state_to_array (env.state)\n memory.append ((state0, action, reward, state1))\n state0 = state1\n\n # create training batch\n b_index, batch, b_weight = memory.sample (size_batch)\n batch = list (zip (*batch))\n b_state0 = np.array (batch[0])\n b_action = np.array (batch[1])\n b_reward = np.array (batch[2])\n b_state1 = np.array (batch[3])\n\n # predict Q-values\n policy = None\n qf_val = None\n a_star = np.empty (size_batch)\n\n if use_double:\n target = None\n othert = None\n if random.random () < 0.5:\n policy = policy_a\n target = target_a\n othert = target_b\n else:\n policy = policy_b\n target = target_b\n othert = target_a\n\n qp_val = target.predict (b_state1)\n qf_val = othert.predict (b_state1)\n a_star = np.argmax (qp_val, axis = 1)\n else:\n policy = policy_a\n target = target_a\n\n qf_val = target.predict (b_state1)\n a_star = np.argmax (qf_val, axis = 1)\n\n b_target = policy.predict (b_state0)\n for i in range (size_batch):\n a = b_action[i]\n a_s = a_star[i]\n r = b_reward[i]\n b_target[i,a] += lr*(r + gamma*qf_val[i,a_s] - b_target[i,a])\n\n # fit values\n policy.fit (b_state0,\n b_target,\n epochs = 10,\n batch_size = size_batch,\n verbose = 0)\n \n # update fixed q-values\n if (step + 1) % tau == 0:\n target_a.set_weights (policy_a.get_weights ())\n target_b.set_weights (policy_b.get_weights ())\n\n # display episode results\n print (\"episode {0:3d}, score {1:3d}, dings {2:2d}, eps {3:6f}\"\n .format (episode, score, env.dings, eps))\n scores.append (score)\n\n# write results to file\nif data_filename:\n with open (data_filename, 'w') as f:\n for i in range (num_episodes):\n f.write (\"{0:d},{1:d}\\n\".format (i, scores[i]))\n\nplt.plot (scores)\nplt.show ()\n\n# Play\nfor episode in range (num_testepis):\n state0 = state_to_array (env.reset ())\n score = 0\n for step in range (num_steps):\n q_vals = policy_a.predict (np.array ([state0]))\n if use_double:\n q_vals = q_vals + policy_b.predict (np.array ([state0]))\n action = np.argmax (q_vals)\n reward = env.step (action)\n score += reward\n state = state_to_array (env.state)\n\n print (\"score\", score)\n\n","sub_path":"Code/RLChain/AllDeepQLearning.py","file_name":"AllDeepQLearning.py","file_ext":"py","file_size_in_byte":8463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"607086571","text":"\n#Function 1: TRANSLATE Reads in a DNA sequence fasta file,\nstandard_code = {\n \"UUU\": \"F\", \"UUC\": \"F\", \"UUA\": \"L\", \"UUG\": \"L\", \"UCU\": \"S\",\n \"UCC\": \"S\", \"UCA\": \"S\", \"UCG\": \"S\", \"UAU\": \"Y\", \"UAC\": \"Y\",\n \"UAA\": \"*\", \"UAG\": \"*\", \"UGA\": \"*\", \"UGU\": \"C\", \"UGC\": \"C\",\n \"UGG\": \"W\", \"CUU\": \"L\", \"CUC\": \"L\", \"CUA\": \"L\", \"CUG\": \"L\",\n \"CCU\": \"P\", \"CCC\": \"P\", \"CCA\": \"P\", \"CCG\": \"P\", \"CAU\": \"H\",\n \"CAC\": \"H\", \"CAA\": \"Q\", \"CAG\": \"Q\", \"CGU\": \"R\", \"CGC\": \"R\",\n \"CGA\": \"R\", \"CGG\": \"R\", \"AUU\": \"I\", \"AUC\": \"I\", \"AUA\": \"I\",\n \"AUG\": \"M\", \"ACU\": \"T\", \"ACC\": \"T\", \"ACA\": \"T\", \"ACG\": \"T\",\n \"AAU\": \"N\", \"AAC\": \"N\", \"AAA\": \"K\", \"AAG\": \"K\", \"AGU\": \"S\",\n \"AGC\": \"S\", \"AGA\": \"R\", \"AGG\": \"R\", \"GUU\": \"V\", \"GUC\": \"V\",\n \"GUA\": \"V\", \"GUG\": \"V\", \"GCU\": \"A\", \"GCC\": \"A\", \"GCA\": \"A\",\n \"GCG\": \"A\", \"GAU\": \"D\", \"GAC\": \"D\", \"GAA\": \"E\", \"GAG\": \"E\",\n \"GGU\": \"G\", \"GGC\": \"G\", \"GGA\": \"G\", \"GGG\": \"G\"}\n\ndef DNA2Prot(f1, f2=\"translated_fasta.txt\"):\n fn=open(f1,'U')\n fout=open(f2,'w')\n for line in fn:\n if \">\" in line:\n fout.write(line)\n pass\n else:\n codons=[]\n i=0\n protein=\"\"\n line=line.replace(\"T\",\"U\")\n line=line.strip()\n for i in range(0,len(line),3):\n codon=line[i:i+3]\n if len(codon)== 3:\n codons.append(codon)\n amino_acid = standard_code[codon]\n protein = protein + amino_acid\n else:\n pass\n fout.write(protein)\n fout.write(\"\\n\")\n\n fn.close()\n fout.close()\n return 1\n \n\n#Function 2: Reads in a fasta file of protein sequences,\n\ndef AAfreq(f1,f2=\"aatable.xls\"):\n fn = open(f1, 'r')\n fout = open(f2, 'w')\n count = 0\n countA = 0\n fseq = fn.readlines()\n fdict = {}\n for line in fseq:\n if \">\" in line:\n fseq.remove(line)\n for line in fseq:\n for line2 in fseq(countA):\n if (line2 != \"\\n\"):\n if line2 not in fdict:\n fdict[line2] = 1\n else:\n fdict[line2] += 1\n countA += 1\n if (count == 0):\n fout.write(\"AminoAcid\\t\")\n for line in fseq:\n fout.write(str(line) + \"\\t\")\n fout.write(\"\\n\")\n fout.write(\"Seq\" +str(count) + \"\\t\")\n fout.write(\"\\n\")\n count += 1\n fout.close()\n\n return f2\n\n#Function 3: Reads in a fasta file and searches for a set of motifs.\n\nimport re\n\ndef MotifFinder(f1, motif, f2=\"motifs.xls\"):\n fn = open(f1, 'r')\n fout = open(f2, 'w')\n count = 1\n fseq = fn.readlines()\n for line in fseq:\n if \">\" in line:\n fseq.remove(line)\n fout.write(\"SeqName\" + \"\\t\" + \"M1\" + \"\\t\" + \"Hits\" + \"\\t\" + \"M2\" + \"\\t\" + \"Hits\"\"\\n\")\n for line in fseq:\n fout.write(\"Seq\" +str(count))\n count += 1\n for line2 in motif:\n motifs=re.findall(line2,line)\n fout.write(\"\\t\")\n fout.write(line2)\n fout.write(\"\\t\")\n fout.write(str(len(motifs)))\n fout.write(\"\\n\")\n fout.close()\n return f2\n","sub_path":"PythonProject.py","file_name":"PythonProject.py","file_ext":"py","file_size_in_byte":3184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"232314063","text":"import colorama\nimport socket\nfrom typing import List\n\nimport paramiko.client\nfrom .worker_pool import WorkerPoolManager\n\n\nclass WorkerPoolSSHConnection:\n def __init__(self, manager: WorkerPoolManager):\n self.manager = manager\n\n def connect(self):\n instances = self.manager.list_worker_instances()\n addrs = [_get_external_ip(instance) for instance in instances]\n hosts = {ip: instance[\"name\"] for ip, instance in zip(addrs, instances)}\n clients = {}\n for ip, name in hosts.items():\n client = paramiko.client.SSHClient()\n client.set_missing_host_key_policy(_IgnoreMissingHostKeys)\n client.connect(hostname=ip)\n clients[name] = client\n return clients\n\n def stream_logs(self, colorize: bool = True):\n clients = self.connect()\n # First, establish connections to the workers.\n channels = {}\n for name, client in clients.items():\n transport = client.get_transport()\n channel = transport.open_session(timeout=1)\n channel.get_pty()\n channel.exec_command(\"journalctl -o cat -f -u thor-worker.service\")\n channel.settimeout(0.05)\n stdout = channel.makefile(\"r\", 4096)\n channels[name] = stdout\n\n # Set up pretty colors, if requested.\n if colorize:\n printer = ColorizedPrinter(list(clients.keys()))\n else:\n printer = PlainPrinter()\n\n # Loop over the open connections, printing output as we get it.\n while True:\n # Keep track of any connections that appear to be closed. We should\n # remove them from the list that we loop over.\n closed = set()\n\n for instance, stdout in channels.items():\n # If any channel greedily emits at least 1024 lines, then pause\n # and move on to other connections to give them a chance to spam\n # us too.\n i = 0\n while i < 1024:\n try:\n line = stdout.readline()[:-1]\n i += 1\n printer.print(instance, line)\n except socket.timeout:\n # Wait for more input - exit the loop.\n break\n except OSError:\n # Closed - exit the loop.\n closed.add(instance)\n break\n\n # Clean up and close channels to any commands that exited.\n for closed_instance in closed:\n client = clients[closed_instance]\n client.close()\n clients.pop(closed_instance)\n\n if len(clients) == 0:\n return\n\n\nclass ColorizedPrinter:\n def __init__(self, hosts: List[str]):\n colors = [\n colorama.Fore.GREEN,\n colorama.Fore.YELLOW,\n colorama.Fore.CYAN,\n colorama.Style.BRIGHT + colorama.Fore.BLUE,\n colorama.Style.DIM + colorama.Fore.YELLOW,\n colorama.Style.DIM + colorama.Fore.RED,\n colorama.Style.DIM + colorama.Fore.GREEN,\n colorama.Fore.RED,\n colorama.Style.BRIGHT + colorama.Fore.GREEN,\n colorama.Fore.WHITE,\n colorama.Fore.MAGENTA,\n ]\n self.colors_by_name = {}\n for i, name in enumerate(hosts):\n color = colors[i % len(colors)]\n self.colors_by_name[name] = color\n\n def print(self, hostname, message):\n color = self.colors_by_name.get(hostname, \"\")\n reset = colorama.Style.RESET_ALL\n print(f\"{color}{hostname}{reset}: {message}\")\n\n\nclass PlainPrinter:\n def __init__(self):\n pass\n\n def print(self, hostname, message):\n print(f\"{hostname}: {message}\")\n\n\ndef _get_external_ip(instance_description: dict) -> str:\n networks = instance_description.get(\"networkInterfaces\", [])\n for net in networks:\n access_configs = net.get(\"accessConfigs\", [])\n for ac in access_configs:\n if ac.get(\"natIP\", None) is not None:\n return ac[\"natIP\"]\n raise ValueError(\n f\"no external IP address found for instance {instance_description['name']}\"\n )\n\n\nclass _IgnoreMissingHostKeys(paramiko.client.MissingHostKeyPolicy):\n def missing_host_key(self, client, hostname, key):\n return\n","sub_path":"thorctl/sshconn.py","file_name":"sshconn.py","file_ext":"py","file_size_in_byte":4421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"636272900","text":"import binascii\n\ndef gcd(x, y):\n while y:\n x, y = y, x%y\n return x\n\ndef lcm(x, y):\n return x*y //gcd(x, y)\n\ndef exgcd(x, y):\n c0, c1 = x, y\n a0, a1 = 1, 0\n b0, b1 = 0, 1\n \n while c1 != 0:\n m = c0 % c1\n q = c0 // c1\n \n c0, c1 = c1, m\n a0, a1 = a1, (a0 - q * a1)\n b0, b1 = b1, (b0 - q * b1)\n \n return c0, a0, b0\n\ndef modinv(x, n):\n return x % n\n\ndef main():\n p=16764777456439012943\n q=14588483238879488297\n\n N = p*q\n e = 65537\n\n lam = lcm(p-1, q-1)\n\n c, a, b = exgcd(e, lam)\n\n a = modinv(a, lam)\n\n with open('flag.enc', 'r') as f:\n crypt = f.read()\n crypt = encode('hex')\n crypt = int(crypt('hex'), 16)\n\n ans = pow(crypt, a, N)\n\n ans = hex(ans)[2:]\n \n print(binascii.a2b_hex(ans).decode('utf-8'))\n\n\n# print(binascii.a2b_hex(ans).decode('utf-8'))\n\nif __name__ == '__main__':\n main()\n","sub_path":"crypro4b_3rd_2017/easy/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"412404515","text":"import scipy.optimize\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom collections import defaultdict, Counter\nfrom lower import Lower, Lower2, donnel\n\nR = 10\nSTEPS = 100\neps = 1e-8\n\ndef L(wx,wy,w,t1,t2):\n if w == min(wx,wy):\n l1 = (t1-t2)*(1-wx) / ((1-t1)*(wx-wy))\n l2 = t2*(wx-wy) / ((t1-t2)*wy)\n v = (1-t1)/(1-wx)\n return t1*np.log(l1) + t2*np.log(l2) + np.log(v)\n #if not wx', facecolor='black', connectionstyle='arc3,rad=0')\n )\n\ndef corollary1(wx,wy,w1,w2, c):\n # t1=1-wy, t2=1-wx\n l1, l2 = L(wx,wy,w1,1-wy,1-wx), L(wx,wy,w2,1-wy,1-wx)\n pq = (l1-di(1-wy,wx))/(l2-di(1-wy,wx))\n pu = (l1-di(1-wx,wy))/(l2-di(1-wy,wx))\n md = min(di(1-wy,wx), di(1-wx,wy))\n sr = (l1-md)/(l2-md)\n plt.scatter([pq],[pu], marker='o', c=c)\n #plt.scatter([sl],[sr], marker='o', c=c)\n plt.annotate(\n 'Corollary 1', xy=(pq, pu),\n xytext=(-50, -20),\n textcoords='offset points', ha='left', va='bottom',\n arrowprops=dict(arrowstyle = '-|>', facecolor='black', connectionstyle='arc3,rad=0')\n )\n\n\ndef chosenpath(wx,wy,w1,w2,c):\n # Chosen Path\n r = np.log(w1/max(wx,wy))/np.log(w2/max(wx,wy))\n plt.scatter([r],[r], marker='o', color=c)\n plt.annotate(\n 'Chosen Path', xy=(r, r),\n xytext=(30, -10),\n textcoords='offset points', ha='left', va='bottom',\n arrowprops=dict(arrowstyle = '-|>', facecolor='black', connectionstyle='arc3,rad=0')\n )\n\ndef bitsampling(wx,wy,w1,w2,c):\n rq = ru = np.log(1-wx-wy+2*w1)/np.log(1-wx-wy+2*w2)\n plt.scatter([rq],[ru], marker='o', color=c)\n plt.annotate(\n 'Bit Sampling', xy=(rq, ru),\n xytext=(30, -10),\n textcoords='offset points', ha='left', va='bottom',\n arrowprops=dict(arrowstyle = '-|>', facecolor='black', connectionstyle='arc3,rad=0')\n )\n\ndef spherical(wx,wy,w1,w2,c):\n a = (w1-wx*wy)/(wx*(1-wx)*wy*(1-wy))**.5\n b = (w2-wx*wy)/(wx*(1-wx)*wy*(1-wy))**.5\n # Tradeoff\n def spherical(l):\n return (1-a**(1+l))**2/(1-a**2) / ( (1-a**l*b)**2/(1-b**2)) ,\\\n (a**l - a)**2/(1-a**2) / ( (1-a**l*b)**2/(1-b**2))\n xy = [spherical(l) for l in np.linspace(-1,1)]\n x, y = zip(*xy)\n plt.plot(x, y, '--', label='Spherical Trade-off', color=c)\n # Make an extra dot on the LSH-Regime?\n # mx, my = spherical(0)\n #plt.scatter([x[0], mx, x[-1]], [y[0], my, y[-1]], marker='o', color=c)\n plt.scatter([x[0], x[-1]], [y[0], y[-1]], marker='o', color=c)\n return x[-1]\n\ndef cp_balance(wx,wy,w1,w2,c):\n if np.sign(np.log(w2/wx)*np.log(1+(-w1+wx)/(-1+wy))\n - np.log(w1/wy)*np.log((-1-w2+wx+wy)/(-1+wx))) \\\n == np.sign(np.log(w2/wx)*np.log((-1 - w1 + wx + wy)/(-1 + wx))\n - np.log(w1/wx)*np.log((-1 - w2 + wx + wy)/(-1 + wx))):\n # No trade-off if both curves are monotone in the same direction\n return\n def f(k):\n n = (k-1)*np.log((1-wx-wy+w2)/(1-wx)) + np.log(w2/wx)\n return ((k-1)*np.log((1-wx-wy+w1)/(1-wx)) + np.log(w1/wx))/n, \\\n ((k-1)*np.log((1-wx-wy+w1)/(1-wy)) + np.log(w1/wy))/n\n xy = [f(k**2) for k in range(1,100)]\n x, y = zip(*xy)\n plt.plot(x, y, '--', label='CP Trade-off', color=c)\n\ndef hyperplane(wx,wy,w1,w2,srq,c):\n # Hyper plane\n def hyper():\n a = (w1-wx*wy)/(wx*(1-wx)*wy*(1-wy))**.5\n b = (w2-wx*wy)/(wx*(1-wx)*wy*(1-wy))**.5\n return np.log(1-np.arccos(a)/np.pi)/np.log(1-np.arccos(b)/np.pi)\n hyper = hyper()\n if hyper < srq:\n plt.scatter([hyper],[hyper], marker='o', color=c)\n plt.annotate(\n 'Hyperplane', xy=(hyper, hyper),\n xytext=(-20, 20),\n textcoords='offset points', ha='right', va='bottom',\n arrowprops=dict(arrowstyle = '-|>', facecolor='black', connectionstyle='arc3,rad=0')\n )\n else:\n hyper = srq\n\n # LSH Area\n plt.plot(np.linspace(0,max(srq,hyper)), np.linspace(0,max(srq,hyper)), ':', label='LSH Regime', color=c, zorder=-1)\n\ndef t1wx_t2wy(wx,wy,w1,w2):\n rq = ((w1-wx*wy)**2*(w2**2-2*w2*wx*wy+wx*wy*(-1+wx+wy)))/((w2-wx*wy)**2*(w1**2-2*w1*wx*wy+wx*wy*(-1+wx+wy)))\n ru = ((w1-wx*wy)**2*(w2**2-2*w2*wx*wy+wx*wy*(-1+wx+wy)))/((-1+wx)*wx*(-1+wy)*wy*(w1**2-2*w1*wx*wy+wx*wy*(-1+wx+wy)))\n plt.scatter([rq],[ru], label='t1wy t2wy')\n\n\ndef theorem(wx,wy,w1,w2,c):\n upper = Upper(wx,wy,w1,w2)\n (max_rq, max_ru), _ = upper.endpoints()\n plt.scatter([max_rq, 0], [0, max_ru], marker='o', c=c)\n\n x, y = zip(*upper.calc())\n plt.plot(x, y, label='General Upper Bound', c=c)\n return upper\n\n\ndef main():\n plt.style.use('seaborn-whitegrid')\n cs = plt.rcParams['axes.prop_cycle'].by_key()['color']\n cs[0],cs[1] = cs[1], cs[0]\n\n matplotlib.rcParams['mathtext.fontset'] = 'cm'\n # Pyplot will warn about this, but we need it for tex\n matplotlib.rcParams['font.family'] = 'cmu serif'\n # This is nice in pyplot, but messes things up in tex\n #matplotlib.rcParams['font.family'] = 'STIXGeneral'\n matplotlib.rcParams['mathtext.rm'] = 'Bitstream Vera Sans'\n matplotlib.rcParams['mathtext.it'] = 'Bitstream Vera Sans:italic'\n matplotlib.rcParams['mathtext.bf'] = 'Bitstream Vera Sans:bold'\n\n #wx, wy, w1 = 0.03, 0.025, 0.024; w2 = wx*wy\n #wx, wy, w1 = 0.3, 0.2, 0.1; w2 = wx*wy\n #wx, wy, w1, w2 = 0.333, 0.333, .3, 0.033\n #wx = np.random.uniform(0,.3)\n #wy = wx\n wx = round(np.random.uniform(0,.3), 3)\n wy = round(np.random.uniform(0,wx), 3)\n w1 = round(np.random.uniform(wx*wy,min(wx,wy)), 3)\n #w1 = min(wx,wy)\n w2 = round(np.random.uniform(wx*wy,w1),3)\n #w2 = wx*wy\n #wx, wy, w1, w2 = 0.49, 0.49, 0.267, 0.0925\n\n # Subset plots for Rasmus\n #wx, wy, w1 = .002, .003, .00199; w2 = wx*wy\n #wx, wy, w1 = .02, .03, .0199; w2 = wx*wy\n #wx, wy, w1 = .01, .04, .0099; w2 = wx*wy\n #wx, wy, w1 = .1, .4, .099; w2 = wx*wy\n #wx, wy, w1 = .001, .004, .00099; w2 = wx*wy\n wx, wy, w1 = .01, .03, .0099; w2 = wx*wy\n\n # Nice other plots to check\n #wx,wy,w1,w2= 0.3789422425179251, 0.35844786217710467 ,0.2739354568368429 ,0.04288314539608652\n #wx,wy,w1,w2= 0.03276672262651542, 0.02740135136984209, 0.021632606352215717, 0.0011691647201981042\n\n\n\n fig = plt.figure(figsize=(3.5, 4), frameon=True)\n print(wx,wy,w1,w2)\n #plt.title(f'$w_x={wx}, w_y={wy}, w_1={w1}, w_2={w2}$')\n #ax = fig.add_subplot(111)\n plt.xlabel(r'$\\rho_q$')\n plt.ylabel(r'$\\rho_u$')\n #ax.set_xlabel(r'$\\rho_q$')\n #ax.set_ylabel(r'$\\rho_u$')\n #ax.margins(0, 0)\n plt.subplots_adjust(left=.225, right=.9, bottom=.125, top=.9, wspace=.2, hspace=.2)\n\n\n\n\n minhash(wx,wy,w1,w2, cs[1])\n corollary1(wx,wy,w1,w2, cs[0])\n chosenpath(wx,wy,w1,w2, cs[1])\n #bitsampling(wx,wy,w1,w2, cs[1])\n srq = spherical(wx,wy,w1,w2, cs[2])\n #cp_balance(wx,wy,w1,w2, cs[5])\n hyperplane(wx,wy,w1,w2, srq, cs[1])\n #t1wx_t2wy(wx,wy,w1,w2)\n upper = theorem(wx,wy,w1,w2, cs[0])\n #donnel(wx,wy,w1,w2,cs[5])\n\n if w2 == wx*wy:\n x, y = Lower(wx,wy,w1).calc()\n plt.plot(x, y, '-.', label='Lower bound 1', color=cs[3])\n pts, _ = Lower(wx,wy,w1).endpoints()\n #plt.scatter(*zip(*pts), color=cs[3])\n\n pts = Lower2(wx,wy,w1).calc()\n plt.plot(*zip(*pts), '-.', label='Lower bound 2 (Conj.)', color=cs[4])\n\n\n plt.legend(loc=1)\n\n name = f'fig_wx{str(wx).replace(\".\",\"_\")}.pgf'\n print(f'Saving as {name}')\n plt.savefig(name,\n bbox_inches='tight'\n #, bbox_inches =None, pad_inches = 1, transparent=True, frameon=True\n )\n plt.show()\n\n\n # T path\n x, y = zip(*[t for t,_ in upper.tpath])\n cmap = matplotlib.cm.rainbow(np.linspace(0.0, 1.0, len(x)))\n plt.scatter(x, y, color=cmap)\n #print(upper.tpath)\n _, (x, y) = min((abs(rq-ru),t) for t,(rq,ru) in upper.tpath)\n plt.scatter([x], [y], color=cs[0])\n #plt.plot(x, y)\n #plt.scatter([x[0],x[-1]],[y[0],y[-1]])\n plt.show()\n\nif __name__ == '__main__':\n main()\n","sub_path":"thesis/parts/supermajority/nbs/opt.py","file_name":"opt.py","file_ext":"py","file_size_in_byte":13192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"169711401","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport FinanceDataReader as fdr\nimport datetime\nfrom dateutil.relativedelta import relativedelta # 몇달 전, 몇달 후, 몇년 전, 몇년 후 를 구하고 싶다면 relativedelta\nfrom pypfopt.efficient_frontier import EfficientFrontier\nfrom pypfopt import risk_models\nfrom pypfopt import expected_returns\nfrom pypfopt.discrete_allocation import DiscreteAllocation, get_latest_prices\nimport warnings\nwarnings.filterwarnings(action='ignore')\n\n\n# 하루 상승빈도\n# up_down_zero_df = st.get_up_down_zero_df()\n# up_down_zero_df.to_csv(\"up_down_zero_df.csv\")\nup_down_zero_df = pd.read_csv(\"up_down_zero_df.csv\")\nup_down_zero_df.index = up_down_zero_df['Unnamed: 0']\nup_down_zero_df = up_down_zero_df.drop('Unnamed: 0', axis=1)\nidx_list = up_down_zero_df.index[:30]\nsymbol_udz = [] # 종목 코드만 가져오기\nfor i in idx_list:\n symbol_udz.append(up_down_zero_df.loc[i][0])\n\ndef Updown_sharpe():\n # 종목 이름 및 코드\n kospi_temp = fdr.StockListing('KOSPI')[['Symbol', 'Name']]\n kosdaq_temp = fdr.StockListing('KOSDAQ')[['Symbol', 'Name']]\n code_name_dict = pd.concat([kospi_temp, kosdaq_temp])\n code_name_dict = code_name_dict.set_index('Symbol').to_dict().get('Name') # {'095570': 'AJ네트웍스',\n\n assets = np.array(symbol_udz, dtype='object')\n start_date = datetime.datetime.today() - relativedelta(years=3)\n start_date = start_date.strftime('%Y%m%d')\n # start_date = '2018-08-13'\n today = datetime.datetime.today().strftime(\"%Y%m%d\")\n end_date = today\n df = pd.DataFrame()\n\n for s in assets:\n df[s] = fdr.DataReader(s, start_date, end_date)['Close']\n\n # drop null\n dfnull = df.dropna(axis=1)\n\n # 수익률의 공분산\n mu = expected_returns.mean_historical_return(dfnull)\n S = risk_models.sample_cov(dfnull)\n # print(plotting.plot_covariance(S))\n\n # 포폴 최적화 (Max sharp ratio) - 급등주\n ef = EfficientFrontier(mu, S, solver=\"SCS\")\n weights = ef.max_sharpe()\n cleaned_weights = ef.clean_weights()\n print(ef.portfolio_performance(verbose=True))\n\n one_million = 1000000\n portfolio_val = 15 * one_million\n latest_prices = get_latest_prices(dfnull)\n weights = cleaned_weights\n da = DiscreteAllocation(weights, latest_prices, total_portfolio_value=portfolio_val)\n allocation, leftover = da.lp_portfolio(verbose=False)\n rmse = da._allocation_rmse_error(verbose=False)\n\n # 각 종목별 실제 투자 금액\n inv_total_price = {}\n for i in allocation.keys():\n inv_total_price[i] = latest_prices.loc[i] * allocation[i]\n inv_total_price\n\n # 총 투자금액\n investment = 0\n for i in inv_total_price.values():\n investment += i\n print(investment)\n\n # 각 종목별 실제 투자 비중\n inv_total_weight = {}\n for i in allocation.keys():\n inv_total_weight[i] = inv_total_price[i] / investment\n inv_total_weight\n\n # 투자비중의 합계\n investment_w = 0\n for i in inv_total_weight.values():\n investment_w += i\n print(investment_w)\n\n # 결과값으로 불러올 값을 리스트로 저장\n name_list = [] # 종목명(회사이름)\n total_price_stock = [] # 각 종목별 실제 투자 금액\n total_weight_stock = [] # 각 종목별 실제 투자 비중\n for i in allocation.keys(): # i = 포트폴리오에 할당된 종목의 종목코드\n name_list.append(code_name_dict.get(i))\n total_price_stock.append(inv_total_price.get(i))\n total_weight_stock.append(inv_total_weight.get(i))\n\n # Get the discrete allocation values\n discrete_allocation_list = []\n for symbol in allocation:\n discrete_allocation_list.append(allocation.get(symbol))\n print(discrete_allocation_list)\n\n portfolio_df = pd.DataFrame(columns=['종목명', '종목코드', '수량(주)', '투자금액(원)', '투자비중'])\n portfolio_df['종목명'] = name_list\n portfolio_df['종목코드'] = allocation\n portfolio_df['수량(주)'] = discrete_allocation_list\n portfolio_df['투자금액(원)'] = total_price_stock\n portfolio_df['투자비중'] = total_weight_stock\n portfolio_df_sorted = portfolio_df.sort_values('투자비중', ascending=False)\n portfolio_df_sorted = portfolio_df_sorted.reset_index(drop=True)\n # 투��� 금액에 따라 최적화된 포트폴리오 종목별 수량\n portfolio_df_sorted.loc[\"합계\", 2:] = portfolio_df_sorted.sum()\n\n ################# 코스피랑 비교 ####################\n # 각 일자별, 종목별 종가에 해당 weights를 곱해주기\n for i, weight in cleaned_weights.items():\n dfnull[i] = dfnull[i] * weight\n\n # 일자별 종목의 (종가*비중) 합계를 Port열에 저장\n dfnull['Port'] = dfnull.sum(axis=1)\n\n # 일자별 종가의 전일대비 변동률(수익률)을 portfolio라는 데이터프레임으로 저장\n portfolio = dfnull[['Port']].pct_change()\n\n # 코스피지수 불러오기\n kospi = fdr.DataReader('KS11', start_date, end_date)[['Close']]\n\n # 코스피지수의 변동률(수익률) 구하기\n # 변동률(수익률) = (당일가격-전일가격) / 전일가격\n # 7/20의 변동률(수익률) = (7/20 가격-7-19 가격) / 7/19 가격\n kospi_pct = kospi.pct_change()\n\n # 코스피와 포트폴리오 합치기\n result = kospi_pct.join(portfolio)\n\n # 1열을 0으로 (Nan 값을 0으로)\n result.iloc[0] = 0\n\n # 열 이름 변경\n result.columns = ['KOSPI', 'PORTFOLIO']\n\n # 1에서 시작해서, 전일대비 변동률(수익률)을 적용하여 수치화하기\n wealth = (1 + result).cumprod()\n\n # 포트폴리오와 KOSPI 지수의 '누적 수익률 추이'를 시각화하여 비교\n\n # matplotlib.pyplot 스타일시트 설정\n plt.style.use('fivethirtyeight')\n\n plt.figure(figsize=(18, 5))\n plt.plot(wealth.index, wealth.KOSPI, 'r', label='KOSPI')\n plt.plot(wealth.index, wealth.PORTFOLIO, 'b', label=\"PORTFOLIO(Up.Down.Zero)\")\n plt.grid(True)\n plt.title('Return Trend')\n plt.xlabel('Date', fontsize=18, labelpad=7)\n plt.ylabel('Return', fontsize=18, labelpad=7)\n plt.legend(loc='best')\n plt.savefig('Updown_sharpe_return.png', dpi=100)\n plt.show()\n\n # 변동률 비교\n plt.figure(figsize=(18, 10))\n\n plt.subplot(2, 1, 1)\n plt.title('Volatility Trend')\n\n plt.plot(result.index, result.KOSPI, 'r', label='KOSPI')\n plt.yticks([-0.15, -0.10, -0.05, 0.00, 0.05, 0.10, 0.15])\n plt.grid(True)\n plt.ylabel('Volatility', fontsize=18, labelpad=7)\n plt.legend(loc='best')\n\n plt.subplot(2, 1, 2)\n plt.title('Volatility Trend')\n plt.plot(result.index, result.PORTFOLIO, 'b', label=\"PORTFOLIO(Up.Down.Zero)\")\n plt.yticks([-0.15, -0.10, -0.05, 0.00, 0.05, 0.10, 0.15])\n plt.ylabel('Volatility', fontsize=18, labelpad=7)\n plt.legend(loc='best')\n\n plt.grid(True)\n plt.savefig('Updown_sharpe_votality.png', dpi=100)\n plt.show()\n\n # print(portfolio_df_sorted) # 데이터 프레임 출력시 시간이 걸림.\n\n print('----- Up.Down.Zero portfolio performance -----')\n # Show Funds Remaining\n print('Funds Remaining: ', leftover, ' KRW')\n\n # Show Portfolio performance\n print(ef.portfolio_performance(verbose=True))","sub_path":"CSV/def_Updown_sharpe.py","file_name":"def_Updown_sharpe.py","file_ext":"py","file_size_in_byte":7291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"104659301","text":"#!/usr/bin/env python3\n\nimport numpy as np\nimport time\nimport pprint\nimport itertools\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.decomposition import PCA, FastICA, TruncatedSVD\nfrom sklearn.random_projection import GaussianRandomProjection\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.neural_network import MLPClassifier\n#from sklearn.model_selection import cross_val_score\n\ndef plot_stuff(cluster_counts, k_means, expect_max, name):\n font = { 'family': 'Arial', 'size': 18 }\n plt.rc('font', **font)\n plt.plot(cluster_counts, k_means, label='MyKMeans')\n plt.plot(cluster_counts, expect_max, label='MyExpectMax')\n plt.ylabel('Average Silhouette', fontsize=18, fontname='Arial')\n plt.xlabel('Clusters', fontsize=18, fontname='Arial')\n plt.tight_layout()\n plt.legend()\n plt.savefig(f\"{name}.png\")\n# plt.show()\n\ndef lowest_label_error(labels1, labels2):\n # Get arrays of unique labels.\n unique_labels1 = np.unique(labels1)\n unique_labels2 = np.unique(labels2)\n\n # Check that the two inputs have the same number of unique labels.\n n_labels = unique_labels1.shape[0]\n if n_labels is not unique_labels2.shape[0]:\n print('unique_labels1', unique_labels1)\n print('unique_labels2', unique_labels2)\n raise Exception('oh no! labels are not the same length!')\n\n # Init empty masks.\n masks1 = np.zeros((n_labels, labels1.shape[0]), dtype=bool)\n masks2 = np.copy(masks1)\n\n # Create an array for each unique value and add it to a mask.\n for i in range(n_labels):\n masks1[i] = np.array([label == unique_labels1[i] for label in labels1])\n for i in range(n_labels):\n masks2[i] = np.array([label == unique_labels2[i] for label in labels2])\n\n # Find the lowest error between mask1 and every permutation of mask2.\n lowest_error = np.inf\n for masks2_perm in itertools.permutations(masks2):\n masks2_perm = np.array(masks2_perm)\n error = np.count_nonzero(masks1 != masks2_perm)\n if error < lowest_error:\n lowest_error = error\n\n # Return the error percentage.\n return lowest_error / masks1.size\n\nRS = 11\n\n# Wine Quality\nname = 'wq'\ntarget = 'quality'\ntrain = pd.read_csv(f'wine_train.csv')\ntest = pd.read_csv(f'wine_test.csv')\n\ny_train = train.loc[:,target]\nX_train = train.drop(target, axis=1)\ny_test = test.loc[:,target]\nX_test = test.drop(target, axis=1)\n\ntransformers = [\n None,\n PCA(n_components=1, random_state=RS),\n FastICA(random_state=RS),\n GaussianRandomProjection(random_state=RS, n_components=9),\n TruncatedSVD(n_components=1, random_state=RS)\n]\n\nnp.random.seed(RS)\nrandom_states = np.random.choice(range(1000), size=5, replace=False)\ntotal_start_time = time.time()\nmetrics = {\n 'None': {},\n 'PCA': {},\n 'FastICA': {},\n 'GaussianRandomProjection': {},\n 'TruncatedSVD': {}\n}\n\nfor transformer in transformers:\n # Transform the data (or not).\n if transformer is None:\n key = 'None'\n X_train_new = np.copy(X_train)\n X_test_new = np.copy(X_test)\n else:\n key = transformer.__class__.__name__\n transform_start_time = time.time()\n transformer.fit(X_train)\n X_train_new = transformer.transform(X_train)\n X_test_new = transformer.transform(X_test)\n metrics[key]['transform_time'] = round(time.time() - transform_start_time, 3)\n print(key)\n\n try:\n # Perform a grid seach to find the best hyper parameters.\n grid = {\n 'random_state': [RS],\n 'hidden_layer_sizes': [(5,), (10,), (50,), (100,)],\n 'alpha': [0.0001, 0.0002, 0.0003, 0.0004],\n 'learning_rate_init': [1e-4, 1e-3, 1e-2],\n 'max_iter': [500]\n }\n clf = GridSearchCV(MLPClassifier(), grid, n_jobs=-1, cv=5)\n grid_start_time = time.time()\n clf.fit(X_train_new, y_train)\n metrics[key]['grid_time'] = round(time.time() - grid_start_time, 3)\n metrics[key]['best_params'] = clf.best_params_\n\n # Define new classifier based on best hyperparamters\n clf = MLPClassifier(**clf.best_params_)\n\n # Train the new classifier on all training data.\n train_start_time = time.time()\n clf.fit(X_train_new, y_train)\n metrics[key]['iters'] = clf.n_iter_\n metrics[key]['train_time'] = round(time.time() - train_start_time, 3)\n\n # Calculate the final scores.\n metrics[key]['final_train_score'] = clf.score(X_train_new, y_train)\n metrics[key]['final_test_score'] = clf.score(X_test_new, y_test)\n except Exception as e:\n print('EXCEPTION!')\n print(e)\n\npprint.PrettyPrinter(indent=4).pprint(metrics)\nprint('total_time:', time.time() - total_start_time)\n","sub_path":"a3/nn_dim_reduce.py","file_name":"nn_dim_reduce.py","file_ext":"py","file_size_in_byte":4749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"365840672","text":"# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.3'\n# jupytext_version: 0.8.6\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# +\nimport warnings\n\nimport pandas as pd\nimport numpy as np\n\nimport scipy.stats as st\n\nimport iqplot\n\nimport bebi103\n\nimport bokeh.io\nbokeh.io.output_notebook()\nimport holoviews as hv\nhv.extension('bokeh')\nimport panel as pn\n\nimport tidy_data\n\ndata_path = \"../data/\"\nrg = np.random.default_rng()\n\n# +\n##########\n# Don't comment out!!1!!\n##########\n\ndf = tidy_data.tidy_concentrations()\n\n#made ndarrays of various concentrations\nconcentrations = df.concentration.unique()\n\n#make ndarrays of catastrophe times for different concentrations\n#catastrophe_times[0] is for the lowest concentration, while cat_times[4] is for the highest concentration\ncatastrophe_times = np.array([\n df.loc[df['concentration'] == concent, 'catastrophe time'] for concent in df.concentration.unique()\n])\n\n# +\ndef plot_overlaid_ecdfs(alpha, time, concentration):\n \"\"\"\n ecdfs of catastrophe times,\n colored by concentration\n also includes gamma distribution overlaid\n Output:\n bokeh figure object\n \"\"\"\n if concentration != 'all':\n sub_df = df.loc[df['concentration_int'] == concentration]\n else:\n sub_df = df\n \n #plot actual data\n p = iqplot.ecdf(\n data = sub_df,\n q = 'catastrophe time',\n cats = 'concentration',\n marker_kwargs=dict(line_width=0.3, alpha = 0.6),\n show_legend = True,\n palette=bokeh.palettes.Magma8[1:-2][::-1],\n tooltips=[\n ('concentration', '@{concentration}'),\n ('catastrophe time', '@{catastrophe time}')\n ],\n )\n p.xaxis.axis_label = \"catastrophe times (s)\"\n \n #get points to plot line\n x = np.linspace(0, 2000)\n y = st.gamma.cdf(x, alpha, scale=time)\n \n #overlay ecdf, can be scaled by widgets\n p.line(\n x = x,\n y = y,\n color = 'yellowgreen',\n width = 3\n )\n \n p.title.text = 'ECDF of catastrophe times by concentration'\n return p\n\n\n# #uncomment to show\n# p = plot_exploratory_ecdfs()\n# bokeh.io.show(p)\n\n# +\nalpha_slider = pn.widgets.FloatSlider(\n name='alpha',\n start=1.8,\n end=4.2,\n step=0.1,\n value=2.4075\n)\n\ntime_slider = pn.widgets.FloatSlider(\n name='average interarrival time (s)',\n start=75,\n end=215,\n step=10,\n value=1 / 0.005462\n)\n\nconcentration_slider = pn.widgets.Select(\n name='concentration (uM)',\n options=[7, 9, 10, 12, 14, 'all',],\n value = 'all',\n)\n# -\n\n@pn.depends(\n alpha=alpha_slider.param.value, \n time=time_slider.param.value,\n concentration = concentration_slider.param.value\n)\ndef plot_overlaid_ecdfs_pn(alpha, time, concentration):\n return plot_overlaid_ecdfs(alpha, time, concentration)\n\nwidgets = pn.Column(pn.Spacer(width=30), alpha_slider, time_slider, concentration_slider, width=500)\npanel = pn.Column(plot_overlaid_ecdfs_pn, widgets)\npanel.save('interactive', embed = True, max_opts = 40)\n\ndef main():\n p = plot_overlaid_ecdfs(2, 1 / .005, 'all')\n bokeh.io.show(p)\n\n \n \n return True\nif __name__ == '__main__': main()\n\n\n# +\n#!jupytext --to python viz_dashboard.ipynb\n","sub_path":"sandbox_code/viz_dashboard.py","file_name":"viz_dashboard.py","file_ext":"py","file_size_in_byte":3326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"576607255","text":"\n\n#calss header\nclass _TONIC():\n\tdef __init__(self,): \n\t\tself.name = \"TONIC\"\n\t\tself.definitions = [u'a liquid medicine that has the general effect of making you feel better rather than treating a particular health problem that you might have', u'something that makes you feel stronger or happier: ', u'carbonated (= with bubbles) water with a bitter taste that can be drunk on its own or added to alcoholic drinks: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_tonic.py","file_name":"_tonic.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"60113752","text":"import os\n\nfrom daiquiri.core.settings.base import BASE_DIR\nDAIQUIRI_APPS = [\n 'daiquiri.archive',\n 'daiquiri.auth',\n 'daiquiri.contact',\n 'daiquiri.core',\n 'daiquiri.files',\n 'daiquiri.jobs',\n 'daiquiri.meetings',\n 'daiquiri.metadata',\n 'daiquiri.query',\n 'daiquiri.serve',\n 'daiquiri.stats',\n 'daiquiri.tap',\n 'daiquiri.uws'\n]\n\nINSTALLED_APPS = []\n\nFIXTURE_DIRS = (\n os.path.join(BASE_DIR, 'fixtures'),\n)\n\nREST_FRAMEWORK = {\n 'DEFAULT_THROTTLE_CLASSES': (\n 'rest_framework.throttling.ScopedRateThrottle',\n ),\n 'DEFAULT_THROTTLE_RATES': {\n 'query.create': '1000/second'\n }\n}\n\nAUTH_SIGNUP = True\nAUTH_WORKFLOW = 'confirmation'\n\nARCHIVE_ANONYMOUS = False\nARCHIVE_BASE_PATH = os.path.join(BASE_DIR, 'files')\n\nMEETINGS_PARTICIPANT_DETAIL_KEYS = [\n {\n 'key': 'affiliation',\n 'label': 'Affiliation',\n 'data_type': 'text',\n 'required': True\n },\n {\n 'key': 'dinner',\n 'label': 'Conference dinner',\n 'data_type': 'radio',\n 'required': True,\n 'options': [\n {'id': 'yes', 'label': 'yes'},\n {'id': 'no', 'label': 'no'}\n ]\n }\n]\n\nSERVE_DOWNLOAD_DIR = os.path.join(BASE_DIR, 'files')\n","sub_path":"testing/config/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"636079109","text":"from socket import *\nimport struct\nimport time\nimport json\nimport subprocess\n\nip_port = ('127.0.0.1', 8080)\nBUFSIZE = 1024\n\ntcp_socket_server = socket(AF_INET, SOCK_STREAM)\ntcp_socket_server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\ntcp_socket_server.bind(ip_port)\ntcp_socket_server.listen(5)\n\nwhile True:\n print(\"server 开始运行,等待客户端连接\")\n conn, addr = tcp_socket_server.accept() # 等待连接\n print('客户端', addr)\n\n while True:\n try:\n print(\"server开始接受消息\")\n cmd = conn.recv(BUFSIZE)\n if len(cmd) == 0:\n break\n print(\"接收到\", cmd)\n res = subprocess.Popen(cmd.decode('utf-8'), # 字节解码为字符串\n shell=True,\n stdout=subprocess.PIPE,\n stdin=subprocess.PIPE,\n stderr=subprocess.PIPE)\n # 解析命令的返回值\n result = (res.stderr.read() + res.stdout.read()).decode('gbk').encode('utf-8') # 注意是utf-8,client必须用utf-8来解码\n # 4.获得真实数据的字节长度\n total_res_bytes = len(result)\n # 5.自定制字典报头\n head_dic = {\n 'time': time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()),\n 'size': total_res_bytes, # 字节长度\n 'MD5': '8f6fbf8347faa4924a76856701edb0f3',\n 'file_name': 'badminton.txt',\n }\n # 6. 序列化字典 ,并将其转换成字节形式\n head_dic_bytes = json.dumps(head_dic).encode('utf-8')\n # 7.使用 struct 封装报头字典head_dic_bytes ,固定长度(4个字节)\n # 封装成字节,发送给客户端,还是按照字节取出来.\n head = struct.pack('i', len(head_dic_bytes))\n # 8. 先将固定头发送给客户端\n conn.send(head)\n # 9 . 再将自定制报头发送给客户端\n conn.send(head_dic_bytes)\n # 10. 最后将真实结果发送给客户端\n conn.send(result)\n # 这里就是拼接字节\n # 格式: 固定头 + 自定义报头 +真实数据\n\n # 如果命令没有返回值,但是也能执行成功,例如cd ..\n if not result:\n result = \"run command successfully\"\n conn.send(result.encode('utf-8'))\n print(\"server端处理一条消息\")\n except Exception:\n break\n conn.close()\ntcp_socket_server.close()","sub_path":"socket/packet_splicing/tcp_server_resolve_splicing.py","file_name":"tcp_server_resolve_splicing.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"276396115","text":"# Copyright (c) 2016 Matt Davis, \n# Chris Houseknecht, \n#\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nimport os\nimport re\nimport types\nimport copy\nimport inspect\nimport traceback\nimport json\n\nfrom os.path import expanduser\n\nfrom ansible.module_utils.basic import AnsibleModule, missing_required_lib\ntry:\n from ansible.module_utils.ansible_release import __version__ as ANSIBLE_VERSION\nexcept Exception:\n ANSIBLE_VERSION = 'unknown'\nfrom ansible.module_utils.six.moves import configparser\nimport ansible.module_utils.six.moves.urllib.parse as urlparse\n\nAZURE_COMMON_ARGS = dict(\n auth_source=dict(\n type='str',\n choices=['auto', 'cli', 'env', 'credential_file', 'msi']\n ),\n profile=dict(type='str'),\n subscription_id=dict(type='str'),\n client_id=dict(type='str', no_log=True),\n secret=dict(type='str', no_log=True),\n tenant=dict(type='str', no_log=True),\n ad_user=dict(type='str', no_log=True),\n password=dict(type='str', no_log=True),\n cloud_environment=dict(type='str', default='AzureCloud'),\n cert_validation_mode=dict(type='str', choices=['validate', 'ignore']),\n api_profile=dict(type='str', default='latest'),\n adfs_authority_url=dict(type='str', default=None)\n)\n\nAZURE_CREDENTIAL_ENV_MAPPING = dict(\n profile='AZURE_PROFILE',\n subscription_id='AZURE_SUBSCRIPTION_ID',\n client_id='AZURE_CLIENT_ID',\n secret='AZURE_SECRET',\n tenant='AZURE_TENANT',\n ad_user='AZURE_AD_USER',\n password='AZURE_PASSWORD',\n cloud_environment='AZURE_CLOUD_ENVIRONMENT',\n cert_validation_mode='AZURE_CERT_VALIDATION_MODE',\n adfs_authority_url='AZURE_ADFS_AUTHORITY_URL'\n)\n\n# FUTURE: this should come from the SDK or an external location.\n# For now, we have to copy from azure-cli\nAZURE_API_PROFILES = {\n 'latest': {\n 'ContainerInstanceManagementClient': '2018-02-01-preview',\n 'ComputeManagementClient': dict(\n default_api_version='2018-10-01',\n resource_skus='2018-10-01',\n disks='2018-06-01',\n snapshots='2018-10-01',\n virtual_machine_run_commands='2018-10-01'\n ),\n 'NetworkManagementClient': '2018-08-01',\n 'ResourceManagementClient': '2017-05-10',\n 'StorageManagementClient': '2017-10-01',\n 'WebSiteManagementClient': '2018-02-01',\n 'PostgreSQLManagementClient': '2017-12-01',\n 'MySQLManagementClient': '2017-12-01',\n 'MariaDBManagementClient': '2019-03-01',\n 'ManagementLockClient': '2016-09-01'\n },\n\n '2017-03-09-profile': {\n 'ComputeManagementClient': '2016-03-30',\n 'NetworkManagementClient': '2015-06-15',\n 'ResourceManagementClient': '2016-02-01',\n 'StorageManagementClient': '2016-01-01'\n }\n}\n\nAZURE_TAG_ARGS = dict(\n tags=dict(type='dict'),\n append_tags=dict(type='bool', default=True),\n)\n\nAZURE_COMMON_REQUIRED_IF = [\n ('log_mode', 'file', ['log_path'])\n]\n\nANSIBLE_USER_AGENT = 'Ansible/{0}'.format(ANSIBLE_VERSION)\nCLOUDSHELL_USER_AGENT_KEY = 'AZURE_HTTP_USER_AGENT'\nVSCODEEXT_USER_AGENT_KEY = 'VSCODEEXT_USER_AGENT'\n\nCIDR_PATTERN = re.compile(r\"(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1\"\n r\"[0-9]{2}|2[0-4][0-9]|25[0-5])(/([0-9]|[1-2][0-9]|3[0-2]))\")\n\nAZURE_SUCCESS_STATE = \"Succeeded\"\nAZURE_FAILED_STATE = \"Failed\"\n\nHAS_AZURE = True\nHAS_AZURE_EXC = None\nHAS_AZURE_CLI_CORE = True\nHAS_AZURE_CLI_CORE_EXC = None\n\nHAS_MSRESTAZURE = True\nHAS_MSRESTAZURE_EXC = None\n\ntry:\n import importlib\nexcept ImportError:\n # This passes the sanity import test, but does not provide a user friendly error message.\n # Doing so would require catching Exception for all imports of Azure dependencies in modules and module_utils.\n importlib = None\n\ntry:\n from packaging.version import Version\n HAS_PACKAGING_VERSION = True\n HAS_PACKAGING_VERSION_EXC = None\nexcept ImportError:\n Version = None\n HAS_PACKAGING_VERSION = False\n HAS_PACKAGING_VERSION_EXC = traceback.format_exc()\n\n# NB: packaging issue sometimes cause msrestazure not to be installed, check it separately\ntry:\n from msrest.serialization import Serializer\nexcept ImportError:\n HAS_MSRESTAZURE_EXC = traceback.format_exc()\n HAS_MSRESTAZURE = False\n\ntry:\n from enum import Enum\n from msrestazure.azure_active_directory import AADTokenCredentials\n from msrestazure.azure_exceptions import CloudError\n from msrestazure.azure_active_directory import MSIAuthentication\n from msrestazure.tools import parse_resource_id, resource_id, is_valid_resource_id\n from msrestazure import azure_cloud\n from azure.common.credentials import ServicePrincipalCredentials, UserPassCredentials\n from azure.mgmt.monitor.version import VERSION as monitor_client_version\n from azure.mgmt.network.version import VERSION as network_client_version\n from azure.mgmt.storage.version import VERSION as storage_client_version\n from azure.mgmt.compute.version import VERSION as compute_client_version\n from azure.mgmt.resource.version import VERSION as resource_client_version\n from azure.mgmt.dns.version import VERSION as dns_client_version\n from azure.mgmt.web.version import VERSION as web_client_version\n from azure.mgmt.network import NetworkManagementClient\n from azure.mgmt.resource.resources import ResourceManagementClient\n from azure.mgmt.resource.subscriptions import SubscriptionClient\n from azure.mgmt.storage import StorageManagementClient\n from azure.mgmt.compute import ComputeManagementClient\n from azure.mgmt.dns import DnsManagementClient\n from azure.mgmt.monitor import MonitorManagementClient\n from azure.mgmt.web import WebSiteManagementClient\n from azure.mgmt.containerservice import ContainerServiceClient\n from azure.mgmt.marketplaceordering import MarketplaceOrderingAgreements\n from azure.mgmt.trafficmanager import TrafficManagerManagementClient\n from azure.storage.cloudstorageaccount import CloudStorageAccount\n from azure.storage.blob import PageBlobService, BlockBlobService\n from adal.authentication_context import AuthenticationContext\n from azure.mgmt.sql import SqlManagementClient\n from azure.mgmt.servicebus import ServiceBusManagementClient\n import azure.mgmt.servicebus.models as ServicebusModel\n from azure.mgmt.rdbms.postgresql import PostgreSQLManagementClient\n from azure.mgmt.rdbms.mysql import MySQLManagementClient\n from azure.mgmt.rdbms.mariadb import MariaDBManagementClient\n from azure.mgmt.containerregistry import ContainerRegistryManagementClient\n from azure.mgmt.containerinstance import ContainerInstanceManagementClient\n from azure.mgmt.loganalytics import LogAnalyticsManagementClient\n import azure.mgmt.loganalytics.models as LogAnalyticsModels\n from azure.mgmt.automation import AutomationClient\n import azure.mgmt.automation.models as AutomationModel\n from azure.mgmt.iothub import IotHubClient\n from azure.mgmt.iothub import models as IoTHubModels\n from msrest.service_client import ServiceClient\n from msrestazure import AzureConfiguration\n from msrest.authentication import Authentication\n from azure.mgmt.resource.locks import ManagementLockClient\nexcept ImportError as exc:\n Authentication = object\n HAS_AZURE_EXC = traceback.format_exc()\n HAS_AZURE = False\n\nfrom base64 import b64encode, b64decode\nfrom hashlib import sha256\nfrom hmac import HMAC\nfrom time import time\n\ntry:\n from urllib import (urlencode, quote_plus)\nexcept ImportError:\n from urllib.parse import (urlencode, quote_plus)\n\ntry:\n from azure.cli.core.util import CLIError\n from azure.common.credentials import get_azure_cli_credentials, get_cli_profile\n from azure.common.cloud import get_cli_active_cloud\nexcept ImportError:\n HAS_AZURE_CLI_CORE = False\n HAS_AZURE_CLI_CORE_EXC = None\n CLIError = Exception\n\n\ndef azure_id_to_dict(id):\n pieces = re.sub(r'^\\/', '', id).split('/')\n result = {}\n index = 0\n while index < len(pieces) - 1:\n result[pieces[index]] = pieces[index + 1]\n index += 1\n return result\n\n\ndef format_resource_id(val, subscription_id, namespace, types, resource_group):\n return resource_id(name=val,\n resource_group=resource_group,\n namespace=namespace,\n type=types,\n subscription=subscription_id) if not is_valid_resource_id(val) else val\n\n\ndef normalize_location_name(name):\n return name.replace(' ', '').lower()\n\n\n# FUTURE: either get this from the requirements file (if we can be sure it's always available at runtime)\n# or generate the requirements files from this so we only have one source of truth to maintain...\nAZURE_PKG_VERSIONS = {\n 'StorageManagementClient': {\n 'package_name': 'storage',\n 'expected_version': '3.1.0'\n },\n 'ComputeManagementClient': {\n 'package_name': 'compute',\n 'expected_version': '4.4.0'\n },\n 'ContainerInstanceManagementClient': {\n 'package_name': 'containerinstance',\n 'expected_version': '0.4.0'\n },\n 'NetworkManagementClient': {\n 'package_name': 'network',\n 'expected_version': '2.3.0'\n },\n 'ResourceManagementClient': {\n 'package_name': 'resource',\n 'expected_version': '2.1.0'\n },\n 'DnsManagementClient': {\n 'package_name': 'dns',\n 'expected_version': '2.1.0'\n },\n 'WebSiteManagementClient': {\n 'package_name': 'web',\n 'expected_version': '0.41.0'\n },\n 'TrafficManagerManagementClient': {\n 'package_name': 'trafficmanager',\n 'expected_version': '0.50.0'\n },\n} if HAS_AZURE else {}\n\n\nAZURE_MIN_RELEASE = '2.0.0'\n\n\nclass AzureRMModuleBase(object):\n def __init__(self, derived_arg_spec, bypass_checks=False, no_log=False,\n check_invalid_arguments=None, mutually_exclusive=None, required_together=None,\n required_one_of=None, add_file_common_args=False, supports_check_mode=False,\n required_if=None, supports_tags=True, facts_module=False, skip_exec=False):\n\n merged_arg_spec = dict()\n merged_arg_spec.update(AZURE_COMMON_ARGS)\n if supports_tags:\n merged_arg_spec.update(AZURE_TAG_ARGS)\n\n if derived_arg_spec:\n merged_arg_spec.update(derived_arg_spec)\n\n merged_required_if = list(AZURE_COMMON_REQUIRED_IF)\n if required_if:\n merged_required_if += required_if\n\n self.module = AnsibleModule(argument_spec=merged_arg_spec,\n bypass_checks=bypass_checks,\n no_log=no_log,\n check_invalid_arguments=check_invalid_arguments,\n mutually_exclusive=mutually_exclusive,\n required_together=required_together,\n required_one_of=required_one_of,\n add_file_common_args=add_file_common_args,\n supports_check_mode=supports_check_mode,\n required_if=merged_required_if)\n\n if not HAS_PACKAGING_VERSION:\n self.fail(msg=missing_required_lib('packaging'),\n exception=HAS_PACKAGING_VERSION_EXC)\n\n if not HAS_MSRESTAZURE:\n self.fail(msg=missing_required_lib('msrestazure'),\n exception=HAS_MSRESTAZURE_EXC)\n\n if not HAS_AZURE:\n self.fail(msg=missing_required_lib('ansible[azure] (azure >= {0})'.format(AZURE_MIN_RELEASE)),\n exception=HAS_AZURE_EXC)\n\n self._network_client = None\n self._storage_client = None\n self._resource_client = None\n self._compute_client = None\n self._dns_client = None\n self._web_client = None\n self._marketplace_client = None\n self._sql_client = None\n self._mysql_client = None\n self._mariadb_client = None\n self._postgresql_client = None\n self._containerregistry_client = None\n self._containerinstance_client = None\n self._containerservice_client = None\n self._managedcluster_client = None\n self._traffic_manager_management_client = None\n self._monitor_client = None\n self._resource = None\n self._log_analytics_client = None\n self._servicebus_client = None\n self._automation_client = None\n self._IoThub_client = None\n self._lock_client = None\n\n self.check_mode = self.module.check_mode\n self.api_profile = self.module.params.get('api_profile')\n self.facts_module = facts_module\n # self.debug = self.module.params.get('debug')\n\n # delegate auth to AzureRMAuth class (shared with all plugin types)\n self.azure_auth = AzureRMAuth(fail_impl=self.fail, **self.module.params)\n\n # common parameter validation\n if self.module.params.get('tags'):\n self.validate_tags(self.module.params['tags'])\n\n if not skip_exec:\n res = self.exec_module(**self.module.params)\n self.module.exit_json(**res)\n\n def check_client_version(self, client_type):\n # Ensure Azure modules are at least 2.0.0rc5.\n package_version = AZURE_PKG_VERSIONS.get(client_type.__name__, None)\n if package_version is not None:\n client_name = package_version.get('package_name')\n try:\n client_module = importlib.import_module(client_type.__module__)\n client_version = client_module.VERSION\n except RuntimeError:\n # can't get at the module version for some reason, just fail silently...\n return\n expected_version = package_version.get('expected_version')\n if Version(client_version) < Version(expected_version):\n self.fail(\"Installed azure-mgmt-{0} client version is {1}. The minimum supported version is {2}. Try \"\n \"`pip install ansible[azure]`\".format(client_name, client_version, expected_version))\n if Version(client_version) != Version(expected_version):\n self.module.warn(\"Installed azure-mgmt-{0} client version is {1}. The expected version is {2}. Try \"\n \"`pip install ansible[azure]`\".format(client_name, client_version, expected_version))\n\n def exec_module(self, **kwargs):\n self.fail(\"Error: {0} failed to implement exec_module method.\".format(self.__class__.__name__))\n\n def fail(self, msg, **kwargs):\n '''\n Shortcut for calling module.fail()\n\n :param msg: Error message text.\n :param kwargs: Any key=value pairs\n :return: None\n '''\n self.module.fail_json(msg=msg, **kwargs)\n\n def deprecate(self, msg, version=None):\n self.module.deprecate(msg, version)\n\n def log(self, msg, pretty_print=False):\n if pretty_print:\n self.module.debug(json.dumps(msg, indent=4, sort_keys=True))\n else:\n self.module.debug(msg)\n\n def validate_tags(self, tags):\n '''\n Check if tags dictionary contains string:string pairs.\n\n :param tags: dictionary of string:string pairs\n :return: None\n '''\n if not self.facts_module:\n if not isinstance(tags, dict):\n self.fail(\"Tags must be a dictionary of string:string values.\")\n for key, value in tags.items():\n if not isinstance(value, str):\n self.fail(\"Tags values must be strings. Found {0}:{1}\".format(str(key), str(value)))\n\n def update_tags(self, tags):\n '''\n Call from the module to update metadata tags. Returns tuple\n with bool indicating if there was a change and dict of new\n tags to assign to the object.\n\n :param tags: metadata tags from the object\n :return: bool, dict\n '''\n tags = tags or dict()\n new_tags = copy.copy(tags) if isinstance(tags, dict) else dict()\n param_tags = self.module.params.get('tags') if isinstance(self.module.params.get('tags'), dict) else dict()\n append_tags = self.module.params.get('append_tags') if self.module.params.get('append_tags') is not None else True\n changed = False\n # check add or update\n for key, value in param_tags.items():\n if not new_tags.get(key) or new_tags[key] != value:\n changed = True\n new_tags[key] = value\n # check remove\n if not append_tags:\n for key, value in tags.items():\n if not param_tags.get(key):\n new_tags.pop(key)\n changed = True\n return changed, new_tags\n\n def has_tags(self, obj_tags, tag_list):\n '''\n Used in fact modules to compare object tags to list of parameter tags. Return true if list of parameter tags\n exists in object tags.\n\n :param obj_tags: dictionary of tags from an Azure object.\n :param tag_list: list of tag keys or tag key:value pairs\n :return: bool\n '''\n\n if not obj_tags and tag_list:\n return False\n\n if not tag_list:\n return True\n\n matches = 0\n result = False\n for tag in tag_list:\n tag_key = tag\n tag_value = None\n if ':' in tag:\n tag_key, tag_value = tag.split(':')\n if tag_value and obj_tags.get(tag_key) == tag_value:\n matches += 1\n elif not tag_value and obj_tags.get(tag_key):\n matches += 1\n if matches == len(tag_list):\n result = True\n return result\n\n def get_resource_group(self, resource_group):\n '''\n Fetch a resource group.\n\n :param resource_group: name of a resource group\n :return: resource group object\n '''\n try:\n return self.rm_client.resource_groups.get(resource_group)\n except CloudError as cloud_error:\n self.fail(\"Error retrieving resource group {0} - {1}\".format(resource_group, cloud_error.message))\n except Exception as exc:\n self.fail(\"Error retrieving resource group {0} - {1}\".format(resource_group, str(exc)))\n\n def parse_resource_to_dict(self, resource):\n '''\n Return a dict of the give resource, which contains name and resource group.\n\n :param resource: It can be a resource name, id or a dict contains name and resource group.\n '''\n resource_dict = parse_resource_id(resource) if not isinstance(resource, dict) else resource\n resource_dict['resource_group'] = resource_dict.get('resource_group', self.resource_group)\n resource_dict['subscription_id'] = resource_dict.get('subscription_id', self.subscription_id)\n return resource_dict\n\n def serialize_obj(self, obj, class_name, enum_modules=None):\n '''\n Return a JSON representation of an Azure object.\n\n :param obj: Azure object\n :param class_name: Name of the object's class\n :param enum_modules: List of module names to build enum dependencies from.\n :return: serialized result\n '''\n enum_modules = [] if enum_modules is None else enum_modules\n\n dependencies = dict()\n if enum_modules:\n for module_name in enum_modules:\n mod = importlib.import_module(module_name)\n for mod_class_name, mod_class_obj in inspect.getmembers(mod, predicate=inspect.isclass):\n dependencies[mod_class_name] = mod_class_obj\n self.log(\"dependencies: \")\n self.log(str(dependencies))\n serializer = Serializer(classes=dependencies)\n return serializer.body(obj, class_name, keep_readonly=True)\n\n def get_poller_result(self, poller, wait=5):\n '''\n Consistent method of waiting on and retrieving results from Azure's long poller\n\n :param poller Azure poller object\n :return object resulting from the original request\n '''\n try:\n delay = wait\n while not poller.done():\n self.log(\"Waiting for {0} sec\".format(delay))\n poller.wait(timeout=delay)\n return poller.result()\n except Exception as exc:\n self.log(str(exc))\n raise\n\n def check_provisioning_state(self, azure_object, requested_state='present'):\n '''\n Check an Azure object's provisioning state. If something did not complete the provisioning\n process, then we cannot operate on it.\n\n :param azure_object An object such as a subnet, storageaccount, etc. Must have provisioning_state\n and name attributes.\n :return None\n '''\n\n if hasattr(azure_object, 'properties') and hasattr(azure_object.properties, 'provisioning_state') and \\\n hasattr(azure_object, 'name'):\n # resource group object fits this model\n if isinstance(azure_object.properties.provisioning_state, Enum):\n if azure_object.properties.provisioning_state.value != AZURE_SUCCESS_STATE and \\\n requested_state != 'absent':\n self.fail(\"Error {0} has a provisioning state of {1}. Expecting state to be {2}.\".format(\n azure_object.name, azure_object.properties.provisioning_state, AZURE_SUCCESS_STATE))\n return\n if azure_object.properties.provisioning_state != AZURE_SUCCESS_STATE and \\\n requested_state != 'absent':\n self.fail(\"Error {0} has a provisioning state of {1}. Expecting state to be {2}.\".format(\n azure_object.name, azure_object.properties.provisioning_state, AZURE_SUCCESS_STATE))\n return\n\n if hasattr(azure_object, 'provisioning_state') or not hasattr(azure_object, 'name'):\n if isinstance(azure_object.provisioning_state, Enum):\n if azure_object.provisioning_state.value != AZURE_SUCCESS_STATE and requested_state != 'absent':\n self.fail(\"Error {0} has a provisioning state of {1}. Expecting state to be {2}.\".format(\n azure_object.name, azure_object.provisioning_state, AZURE_SUCCESS_STATE))\n return\n if azure_object.provisioning_state != AZURE_SUCCESS_STATE and requested_state != 'absent':\n self.fail(\"Error {0} has a provisioning state of {1}. Expecting state to be {2}.\".format(\n azure_object.name, azure_object.provisioning_state, AZURE_SUCCESS_STATE))\n\n def get_blob_client(self, resource_group_name, storage_account_name, storage_blob_type='block'):\n keys = dict()\n try:\n # Get keys from the storage account\n self.log('Getting keys')\n account_keys = self.storage_client.storage_accounts.list_keys(resource_group_name, storage_account_name)\n except Exception as exc:\n self.fail(\"Error getting keys for account {0} - {1}\".format(storage_account_name, str(exc)))\n\n try:\n self.log('Create blob service')\n if storage_blob_type == 'page':\n return PageBlobService(endpoint_suffix=self._cloud_environment.suffixes.storage_endpoint,\n account_name=storage_account_name,\n account_key=account_keys.keys[0].value)\n elif storage_blob_type == 'block':\n return BlockBlobService(endpoint_suffix=self._cloud_environment.suffixes.storage_endpoint,\n account_name=storage_account_name,\n account_key=account_keys.keys[0].value)\n else:\n raise Exception(\"Invalid storage blob type defined.\")\n except Exception as exc:\n self.fail(\"Error creating blob service client for storage account {0} - {1}\".format(storage_account_name,\n str(exc)))\n\n def create_default_pip(self, resource_group, location, public_ip_name, allocation_method='Dynamic', sku=None):\n '''\n Create a default public IP address to associate with a network interface.\n If a PIP address matching exists, return it. Otherwise, create one.\n\n :param resource_group: name of an existing resource group\n :param location: a valid azure location\n :param public_ip_name: base name to assign the public IP address\n :param allocation_method: one of 'Static' or 'Dynamic'\n :param sku: sku\n :return: PIP object\n '''\n pip = None\n\n self.log(\"Starting create_default_pip {0}\".format(public_ip_name))\n self.log(\"Check to see if public IP {0} exists\".format(public_ip_name))\n try:\n pip = self.network_client.public_ip_addresses.get(resource_group, public_ip_name)\n except CloudError:\n pass\n\n if pip:\n self.log(\"Public ip {0} found.\".format(public_ip_name))\n self.check_provisioning_state(pip)\n return pip\n\n params = self.network_models.PublicIPAddress(\n location=location,\n public_ip_allocation_method=allocation_method,\n sku=sku\n )\n self.log('Creating default public IP {0}'.format(public_ip_name))\n try:\n poller = self.network_client.public_ip_addresses.create_or_update(resource_group, public_ip_name, params)\n except Exception as exc:\n self.fail(\"Error creating {0} - {1}\".format(public_ip_name, str(exc)))\n\n return self.get_poller_result(poller)\n\n def create_default_securitygroup(self, resource_group, location, security_group_name, os_type, open_ports):\n '''\n Create a default security group to associate with a network interface. If a security group matching\n exists, return it. Otherwise, create one.\n\n :param resource_group: Resource group name\n :param location: azure location name\n :param security_group_name: base name to use for the security group\n :param os_type: one of 'Windows' or 'Linux'. Determins any default rules added to the security group.\n :param ssh_port: for os_type 'Linux' port used in rule allowing SSH access.\n :param rdp_port: for os_type 'Windows' port used in rule allowing RDP access.\n :return: security_group object\n '''\n group = None\n\n self.log(\"Create security group {0}\".format(security_group_name))\n self.log(\"Check to see if security group {0} exists\".format(security_group_name))\n try:\n group = self.network_client.network_security_groups.get(resource_group, security_group_name)\n except CloudError:\n pass\n\n if group:\n self.log(\"Security group {0} found.\".format(security_group_name))\n self.check_provisioning_state(group)\n return group\n\n parameters = self.network_models.NetworkSecurityGroup()\n parameters.location = location\n\n if not open_ports:\n # Open default ports based on OS type\n if os_type == 'Linux':\n # add an inbound SSH rule\n parameters.security_rules = [\n self.network_models.SecurityRule(protocol='Tcp',\n source_address_prefix='*',\n destination_address_prefix='*',\n access='Allow',\n direction='Inbound',\n description='Allow SSH Access',\n source_port_range='*',\n destination_port_range='22',\n priority=100,\n name='SSH')\n ]\n parameters.location = location\n else:\n # for windows add inbound RDP and WinRM rules\n parameters.security_rules = [\n self.network_models.SecurityRule(protocol='Tcp',\n source_address_prefix='*',\n destination_address_prefix='*',\n access='Allow',\n direction='Inbound',\n description='Allow RDP port 3389',\n source_port_range='*',\n destination_port_range='3389',\n priority=100,\n name='RDP01'),\n self.network_models.SecurityRule(protocol='Tcp',\n source_address_prefix='*',\n destination_address_prefix='*',\n access='Allow',\n direction='Inbound',\n description='Allow WinRM HTTPS port 5986',\n source_port_range='*',\n destination_port_range='5986',\n priority=101,\n name='WinRM01'),\n ]\n else:\n # Open custom ports\n parameters.security_rules = []\n priority = 100\n for port in open_ports:\n priority += 1\n rule_name = \"Rule_{0}\".format(priority)\n parameters.security_rules.append(\n self.network_models.SecurityRule(protocol='Tcp',\n source_address_prefix='*',\n destination_address_prefix='*',\n access='Allow',\n direction='Inbound',\n source_port_range='*',\n destination_port_range=str(port),\n priority=priority,\n name=rule_name)\n )\n\n self.log('Creating default security group {0}'.format(security_group_name))\n try:\n poller = self.network_client.network_security_groups.create_or_update(resource_group,\n security_group_name,\n parameters)\n except Exception as exc:\n self.fail(\"Error creating default security rule {0} - {1}\".format(security_group_name, str(exc)))\n\n return self.get_poller_result(poller)\n\n @staticmethod\n def _validation_ignore_callback(session, global_config, local_config, **kwargs):\n session.verify = False\n\n def get_api_profile(self, client_type_name, api_profile_name):\n profile_all_clients = AZURE_API_PROFILES.get(api_profile_name)\n\n if not profile_all_clients:\n raise KeyError(\"unknown Azure API profile: {0}\".format(api_profile_name))\n\n profile_raw = profile_all_clients.get(client_type_name, None)\n\n if not profile_raw:\n self.module.warn(\"Azure API profile {0} does not define an entry for {1}\".format(api_profile_name, client_type_name))\n\n if isinstance(profile_raw, dict):\n if not profile_raw.get('default_api_version'):\n raise KeyError(\"Azure API profile {0} does not define 'default_api_version'\".format(api_profile_name))\n return profile_raw\n\n # wrap basic strings in a dict that just defines the default\n return dict(default_api_version=profile_raw)\n\n def get_mgmt_svc_client(self, client_type, base_url=None, api_version=None):\n self.log('Getting management service client {0}'.format(client_type.__name__))\n self.check_client_version(client_type)\n\n client_argspec = inspect.getargspec(client_type.__init__)\n\n if not base_url:\n # most things are resource_manager, don't make everyone specify\n base_url = self.azure_auth._cloud_environment.endpoints.resource_manager\n\n client_kwargs = dict(credentials=self.azure_auth.azure_credentials, subscription_id=self.azure_auth.subscription_id, base_url=base_url)\n\n api_profile_dict = {}\n\n if self.api_profile:\n api_profile_dict = self.get_api_profile(client_type.__name__, self.api_profile)\n\n # unversioned clients won't accept profile; only send it if necessary\n # clients without a version specified in the profile will use the default\n if api_profile_dict and 'profile' in client_argspec.args:\n client_kwargs['profile'] = api_profile_dict\n\n # If the client doesn't accept api_version, it's unversioned.\n # If it does, favor explicitly-specified api_version, fall back to api_profile\n if 'api_version' in client_argspec.args:\n profile_default_version = api_profile_dict.get('default_api_version', None)\n if api_version or profile_default_version:\n client_kwargs['api_version'] = api_version or profile_default_version\n if 'profile' in client_kwargs:\n # remove profile; only pass API version if specified\n client_kwargs.pop('profile')\n\n client = client_type(**client_kwargs)\n\n # FUTURE: remove this once everything exposes models directly (eg, containerinstance)\n try:\n getattr(client, \"models\")\n except AttributeError:\n def _ansible_get_models(self, *arg, **kwarg):\n return self._ansible_models\n\n setattr(client, '_ansible_models', importlib.import_module(client_type.__module__).models)\n client.models = types.MethodType(_ansible_get_models, client)\n\n client.config = self.add_user_agent(client.config)\n\n if self.azure_auth._cert_validation_mode == 'ignore':\n client.config.session_configuration_callback = self._validation_ignore_callback\n\n return client\n\n def add_user_agent(self, config):\n # Add user agent for Ansible\n config.add_user_agent(ANSIBLE_USER_AGENT)\n # Add user agent when running from Cloud Shell\n if CLOUDSHELL_USER_AGENT_KEY in os.environ:\n config.add_user_agent(os.environ[CLOUDSHELL_USER_AGENT_KEY])\n # Add user agent when running from VSCode extension\n if VSCODEEXT_USER_AGENT_KEY in os.environ:\n config.add_user_agent(os.environ[VSCODEEXT_USER_AGENT_KEY])\n return config\n\n def generate_sas_token(self, **kwags):\n base_url = kwags.get('base_url', None)\n expiry = kwags.get('expiry', time() + 3600)\n key = kwags.get('key', None)\n policy = kwags.get('policy', None)\n url = quote_plus(base_url)\n ttl = int(expiry)\n sign_key = '{0}\\n{1}'.format(url, ttl)\n signature = b64encode(HMAC(b64decode(key), sign_key.encode('utf-8'), sha256).digest())\n result = {\n 'sr': url,\n 'sig': signature,\n 'se': str(ttl),\n }\n if policy:\n result['skn'] = policy\n return 'SharedAccessSignature ' + urlencode(result)\n\n def get_data_svc_client(self, **kwags):\n url = kwags.get('base_url', None)\n config = AzureConfiguration(base_url='https://{0}'.format(url))\n config.credentials = AzureSASAuthentication(token=self.generate_sas_token(**kwags))\n config = self.add_user_agent(config)\n return ServiceClient(creds=config.credentials, config=config)\n\n # passthru methods to AzureAuth instance for backcompat\n @property\n def credentials(self):\n return self.azure_auth.credentials\n\n @property\n def _cloud_environment(self):\n return self.azure_auth._cloud_environment\n\n @property\n def subscription_id(self):\n return self.azure_auth.subscription_id\n\n @property\n def storage_client(self):\n self.log('Getting storage client...')\n if not self._storage_client:\n self._storage_client = self.get_mgmt_svc_client(StorageManagementClient,\n base_url=self._cloud_environment.endpoints.resource_manager,\n api_version='2018-07-01')\n return self._storage_client\n\n @property\n def storage_models(self):\n return StorageManagementClient.models(\"2018-07-01\")\n\n @property\n def network_client(self):\n self.log('Getting network client')\n if not self._network_client:\n self._network_client = self.get_mgmt_svc_client(NetworkManagementClient,\n base_url=self._cloud_environment.endpoints.resource_manager,\n api_version='2018-08-01')\n return self._network_client\n\n @property\n def network_models(self):\n self.log(\"Getting network models...\")\n return NetworkManagementClient.models(\"2018-08-01\")\n\n @property\n def rm_client(self):\n self.log('Getting resource manager client')\n if not self._resource_client:\n self._resource_client = self.get_mgmt_svc_client(ResourceManagementClient,\n base_url=self._cloud_environment.endpoints.resource_manager,\n api_version='2017-05-10')\n return self._resource_client\n\n @property\n def rm_models(self):\n self.log(\"Getting resource manager models\")\n return ResourceManagementClient.models(\"2017-05-10\")\n\n @property\n def compute_client(self):\n self.log('Getting compute client')\n if not self._compute_client:\n self._compute_client = self.get_mgmt_svc_client(ComputeManagementClient,\n base_url=self._cloud_environment.endpoints.resource_manager,\n api_version='2018-06-01')\n return self._compute_client\n\n @property\n def compute_models(self):\n self.log(\"Getting compute models\")\n return ComputeManagementClient.models(\"2018-06-01\")\n\n @property\n def dns_client(self):\n self.log('Getting dns client')\n if not self._dns_client:\n self._dns_client = self.get_mgmt_svc_client(DnsManagementClient,\n base_url=self._cloud_environment.endpoints.resource_manager,\n api_version='2018-05-01')\n return self._dns_client\n\n @property\n def dns_models(self):\n self.log(\"Getting dns models...\")\n return DnsManagementClient.models('2018-05-01')\n\n @property\n def web_client(self):\n self.log('Getting web client')\n if not self._web_client:\n self._web_client = self.get_mgmt_svc_client(WebSiteManagementClient,\n base_url=self._cloud_environment.endpoints.resource_manager,\n api_version='2018-02-01')\n return self._web_client\n\n @property\n def containerservice_client(self):\n self.log('Getting container service client')\n if not self._containerservice_client:\n self._containerservice_client = self.get_mgmt_svc_client(ContainerServiceClient,\n base_url=self._cloud_environment.endpoints.resource_manager,\n api_version='2017-07-01')\n return self._containerservice_client\n\n @property\n def managedcluster_models(self):\n self.log(\"Getting container service models\")\n return ContainerServiceClient.models('2018-03-31')\n\n @property\n def managedcluster_client(self):\n self.log('Getting container service client')\n if not self._managedcluster_client:\n self._managedcluster_client = self.get_mgmt_svc_client(ContainerServiceClient,\n base_url=self._cloud_environment.endpoints.resource_manager,\n api_version='2018-03-31')\n return self._managedcluster_client\n\n @property\n def sql_client(self):\n self.log('Getting SQL client')\n if not self._sql_client:\n self._sql_client = self.get_mgmt_svc_client(SqlManagementClient,\n base_url=self._cloud_environment.endpoints.resource_manager)\n return self._sql_client\n\n @property\n def postgresql_client(self):\n self.log('Getting PostgreSQL client')\n if not self._postgresql_client:\n self._postgresql_client = self.get_mgmt_svc_client(PostgreSQLManagementClient,\n base_url=self._cloud_environment.endpoints.resource_manager)\n return self._postgresql_client\n\n @property\n def mysql_client(self):\n self.log('Getting MySQL client')\n if not self._mysql_client:\n self._mysql_client = self.get_mgmt_svc_client(MySQLManagementClient,\n base_url=self._cloud_environment.endpoints.resource_manager)\n return self._mysql_client\n\n @property\n def mariadb_client(self):\n self.log('Getting MariaDB client')\n if not self._mariadb_client:\n self._mariadb_client = self.get_mgmt_svc_client(MariaDBManagementClient,\n base_url=self._cloud_environment.endpoints.resource_manager)\n return self._mariadb_client\n\n @property\n def sql_client(self):\n self.log('Getting SQL client')\n if not self._sql_client:\n self._sql_client = self.get_mgmt_svc_client(SqlManagementClient,\n base_url=self._cloud_environment.endpoints.resource_manager)\n return self._sql_client\n\n @property\n def containerregistry_client(self):\n self.log('Getting container registry mgmt client')\n if not self._containerregistry_client:\n self._containerregistry_client = self.get_mgmt_svc_client(ContainerRegistryManagementClient,\n base_url=self._cloud_environment.endpoints.resource_manager,\n api_version='2017-10-01')\n\n return self._containerregistry_client\n\n @property\n def containerinstance_client(self):\n self.log('Getting container instance mgmt client')\n if not self._containerinstance_client:\n self._containerinstance_client = self.get_mgmt_svc_client(ContainerInstanceManagementClient,\n base_url=self._cloud_environment.endpoints.resource_manager,\n api_version='2018-06-01')\n\n return self._containerinstance_client\n\n @property\n def marketplace_client(self):\n self.log('Getting marketplace agreement client')\n if not self._marketplace_client:\n self._marketplace_client = self.get_mgmt_svc_client(MarketplaceOrderingAgreements,\n base_url=self._cloud_environment.endpoints.resource_manager)\n return self._marketplace_client\n\n @property\n def traffic_manager_management_client(self):\n self.log('Getting traffic manager client')\n if not self._traffic_manager_management_client:\n self._traffic_manager_management_client = self.get_mgmt_svc_client(TrafficManagerManagementClient,\n base_url=self._cloud_environment.endpoints.resource_manager)\n return self._traffic_manager_management_client\n\n @property\n def monitor_client(self):\n self.log('Getting monitor client')\n if not self._monitor_client:\n self._monitor_client = self.get_mgmt_svc_client(MonitorManagementClient,\n base_url=self._cloud_environment.endpoints.resource_manager)\n return self._monitor_client\n\n @property\n def log_analytics_client(self):\n self.log('Getting log analytics client')\n if not self._log_analytics_client:\n self._log_analytics_client = self.get_mgmt_svc_client(LogAnalyticsManagementClient,\n base_url=self._cloud_environment.endpoints.resource_manager)\n return self._log_analytics_client\n\n @property\n def log_analytics_models(self):\n self.log('Getting log analytics models')\n return LogAnalyticsModels\n\n @property\n def servicebus_client(self):\n self.log('Getting servicebus client')\n if not self._servicebus_client:\n self._servicebus_client = self.get_mgmt_svc_client(ServiceBusManagementClient,\n base_url=self._cloud_environment.endpoints.resource_manager)\n return self._servicebus_client\n\n @property\n def servicebus_models(self):\n return ServicebusModel\n\n @property\n def automation_client(self):\n self.log('Getting automation client')\n if not self._automation_client:\n self._automation_client = self.get_mgmt_svc_client(AutomationClient,\n base_url=self._cloud_environment.endpoints.resource_manager)\n return self._automation_client\n\n @property\n def automation_models(self):\n return AutomationModel\n\n @property\n def IoThub_client(self):\n self.log('Getting iothub client')\n if not self._IoThub_client:\n self._IoThub_client = self.get_mgmt_svc_client(IotHubClient,\n base_url=self._cloud_environment.endpoints.resource_manager)\n return self._IoThub_client\n\n @property\n def IoThub_models(self):\n return IoTHubModels\n\n @property\n def automation_client(self):\n self.log('Getting automation client')\n if not self._automation_client:\n self._automation_client = self.get_mgmt_svc_client(AutomationClient,\n base_url=self._cloud_environment.endpoints.resource_manager)\n return self._automation_client\n\n @property\n def automation_models(self):\n return AutomationModel\n\n @property\n def lock_client(self):\n self.log('Getting lock client')\n if not self._lock_client:\n self._lock_client = self.get_mgmt_svc_client(ManagementLockClient,\n base_url=self._cloud_environment.endpoints.resource_manager,\n api_version='2016-09-01')\n return self._lock_client\n\n @property\n def lock_models(self):\n self.log(\"Getting lock models\")\n return ManagementLockClient.models('2016-09-01')\n\n\nclass AzureSASAuthentication(Authentication):\n \"\"\"Simple SAS Authentication.\n An implementation of Authentication in\n https://github.com/Azure/msrest-for-python/blob/0732bc90bdb290e5f58c675ffdd7dbfa9acefc93/msrest/authentication.py\n\n :param str token: SAS token\n \"\"\"\n def __init__(self, token):\n self.token = token\n\n def signed_session(self):\n session = super(AzureSASAuthentication, self).signed_session()\n session.headers['Authorization'] = self.token\n return session\n\n\nclass AzureRMAuthException(Exception):\n pass\n\n\nclass AzureRMAuth(object):\n def __init__(self, auth_source='auto', profile=None, subscription_id=None, client_id=None, secret=None,\n tenant=None, ad_user=None, password=None, cloud_environment='AzureCloud', cert_validation_mode='validate',\n api_profile='latest', adfs_authority_url=None, fail_impl=None, **kwargs):\n\n if fail_impl:\n self._fail_impl = fail_impl\n else:\n self._fail_impl = self._default_fail_impl\n\n self._cloud_environment = None\n self._adfs_authority_url = None\n\n # authenticate\n self.credentials = self._get_credentials(\n dict(auth_source=auth_source, profile=profile, subscription_id=subscription_id, client_id=client_id, secret=secret,\n tenant=tenant, ad_user=ad_user, password=password, cloud_environment=cloud_environment,\n cert_validation_mode=cert_validation_mode, api_profile=api_profile, adfs_authority_url=adfs_authority_url))\n\n if not self.credentials:\n if HAS_AZURE_CLI_CORE:\n self.fail(\"Failed to get credentials. Either pass as parameters, set environment variables, \"\n \"define a profile in ~/.azure/credentials, or log in with Azure CLI (`az login`).\")\n else:\n self.fail(\"Failed to get credentials. Either pass as parameters, set environment variables, \"\n \"define a profile in ~/.azure/credentials, or install Azure CLI and log in (`az login`).\")\n\n # cert validation mode precedence: module-arg, credential profile, env, \"validate\"\n self._cert_validation_mode = cert_validation_mode or self.credentials.get('cert_validation_mode') or \\\n os.environ.get('AZURE_CERT_VALIDATION_MODE') or 'validate'\n\n if self._cert_validation_mode not in ['validate', 'ignore']:\n self.fail('invalid cert_validation_mode: {0}'.format(self._cert_validation_mode))\n\n # if cloud_environment specified, look up/build Cloud object\n raw_cloud_env = self.credentials.get('cloud_environment')\n if self.credentials.get('credentials') is not None and raw_cloud_env is not None:\n self._cloud_environment = raw_cloud_env\n elif not raw_cloud_env:\n self._cloud_environment = azure_cloud.AZURE_PUBLIC_CLOUD # SDK default\n else:\n # try to look up \"well-known\" values via the name attribute on azure_cloud members\n all_clouds = [x[1] for x in inspect.getmembers(azure_cloud) if isinstance(x[1], azure_cloud.Cloud)]\n matched_clouds = [x for x in all_clouds if x.name == raw_cloud_env]\n if len(matched_clouds) == 1:\n self._cloud_environment = matched_clouds[0]\n elif len(matched_clouds) > 1:\n self.fail(\"Azure SDK failure: more than one cloud matched for cloud_environment name '{0}'\".format(raw_cloud_env))\n else:\n if not urlparse.urlparse(raw_cloud_env).scheme:\n self.fail(\"cloud_environment must be an endpoint discovery URL or one of {0}\".format([x.name for x in all_clouds]))\n try:\n self._cloud_environment = azure_cloud.get_cloud_from_metadata_endpoint(raw_cloud_env)\n except Exception as e:\n self.fail(\"cloud_environment {0} could not be resolved: {1}\".format(raw_cloud_env, e.message), exception=traceback.format_exc())\n\n if self.credentials.get('subscription_id', None) is None and self.credentials.get('credentials') is None:\n self.fail(\"Credentials did not include a subscription_id value.\")\n self.log(\"setting subscription_id\")\n self.subscription_id = self.credentials['subscription_id']\n\n # get authentication authority\n # for adfs, user could pass in authority or not.\n # for others, use default authority from cloud environment\n if self.credentials.get('adfs_authority_url') is None:\n self._adfs_authority_url = self._cloud_environment.endpoints.active_directory\n else:\n self._adfs_authority_url = self.credentials.get('adfs_authority_url')\n\n # get resource from cloud environment\n self._resource = self._cloud_environment.endpoints.active_directory_resource_id\n\n if self.credentials.get('credentials') is not None:\n # AzureCLI credentials\n self.azure_credentials = self.credentials['credentials']\n elif self.credentials.get('client_id') is not None and \\\n self.credentials.get('secret') is not None and \\\n self.credentials.get('tenant') is not None:\n self.azure_credentials = ServicePrincipalCredentials(client_id=self.credentials['client_id'],\n secret=self.credentials['secret'],\n tenant=self.credentials['tenant'],\n cloud_environment=self._cloud_environment,\n verify=self._cert_validation_mode == 'validate')\n\n elif self.credentials.get('ad_user') is not None and \\\n self.credentials.get('password') is not None and \\\n self.credentials.get('client_id') is not None and \\\n self.credentials.get('tenant') is not None:\n\n self.azure_credentials = self.acquire_token_with_username_password(\n self._adfs_authority_url,\n self._resource,\n self.credentials['ad_user'],\n self.credentials['password'],\n self.credentials['client_id'],\n self.credentials['tenant'])\n\n elif self.credentials.get('ad_user') is not None and self.credentials.get('password') is not None:\n tenant = self.credentials.get('tenant')\n if not tenant:\n tenant = 'common' # SDK default\n\n self.azure_credentials = UserPassCredentials(self.credentials['ad_user'],\n self.credentials['password'],\n tenant=tenant,\n cloud_environment=self._cloud_environment,\n verify=self._cert_validation_mode == 'validate')\n else:\n self.fail(\"Failed to authenticate with provided credentials. Some attributes were missing. \"\n \"Credentials must include client_id, secret and tenant or ad_user and password, or \"\n \"ad_user, password, client_id, tenant and adfs_authority_url(optional) for ADFS authentication, or \"\n \"be logged in using AzureCLI.\")\n\n def fail(self, msg, exception=None, **kwargs):\n self._fail_impl(msg)\n\n def _default_fail_impl(self, msg, exception=None, **kwargs):\n raise AzureRMAuthException(msg)\n\n def _get_profile(self, profile=\"default\"):\n path = expanduser(\"~/.azure/credentials\")\n try:\n config = configparser.ConfigParser()\n config.read(path)\n except Exception as exc:\n self.fail(\"Failed to access {0}. Check that the file exists and you have read \"\n \"access. {1}\".format(path, str(exc)))\n credentials = dict()\n for key in AZURE_CREDENTIAL_ENV_MAPPING:\n try:\n credentials[key] = config.get(profile, key, raw=True)\n except Exception:\n pass\n\n if credentials.get('subscription_id'):\n return credentials\n\n return None\n\n def _get_msi_credentials(self, subscription_id_param=None, **kwargs):\n client_id = kwargs.get('client_id', None)\n credentials = MSIAuthentication(client_id=client_id)\n subscription_id = subscription_id_param or os.environ.get(AZURE_CREDENTIAL_ENV_MAPPING['subscription_id'], None)\n if not subscription_id:\n try:\n # use the first subscription of the MSI\n subscription_client = SubscriptionClient(credentials)\n subscription = next(subscription_client.subscriptions.list())\n subscription_id = str(subscription.subscription_id)\n except Exception as exc:\n self.fail(\"Failed to get MSI token: {0}. \"\n \"Please check whether your machine enabled MSI or grant access to any subscription.\".format(str(exc)))\n return {\n 'credentials': credentials,\n 'subscription_id': subscription_id\n }\n\n def _get_azure_cli_credentials(self):\n credentials, subscription_id = get_azure_cli_credentials()\n cloud_environment = get_cli_active_cloud()\n\n cli_credentials = {\n 'credentials': credentials,\n 'subscription_id': subscription_id,\n 'cloud_environment': cloud_environment\n }\n return cli_credentials\n\n def _get_env_credentials(self):\n env_credentials = dict()\n for attribute, env_variable in AZURE_CREDENTIAL_ENV_MAPPING.items():\n env_credentials[attribute] = os.environ.get(env_variable, None)\n\n if env_credentials['profile']:\n credentials = self._get_profile(env_credentials['profile'])\n return credentials\n\n if env_credentials.get('subscription_id') is not None:\n return env_credentials\n\n return None\n\n # TODO: use explicit kwargs instead of intermediate dict\n def _get_credentials(self, params):\n # Get authentication credentials.\n self.log('Getting credentials')\n\n arg_credentials = dict()\n for attribute, env_variable in AZURE_CREDENTIAL_ENV_MAPPING.items():\n arg_credentials[attribute] = params.get(attribute, None)\n\n auth_source = params.get('auth_source', None)\n if not auth_source:\n auth_source = os.environ.get('ANSIBLE_AZURE_AUTH_SOURCE', 'auto')\n\n if auth_source == 'msi':\n self.log('Retrieving credenitals from MSI')\n return self._get_msi_credentials(arg_credentials['subscription_id'], client_id=params.get('client_id', None))\n\n if auth_source == 'cli':\n if not HAS_AZURE_CLI_CORE:\n self.fail(msg=missing_required_lib('azure-cli', reason='for `cli` auth_source'),\n exception=HAS_AZURE_CLI_CORE_EXC)\n try:\n self.log('Retrieving credentials from Azure CLI profile')\n cli_credentials = self._get_azure_cli_credentials()\n return cli_credentials\n except CLIError as err:\n self.fail(\"Azure CLI profile cannot be loaded - {0}\".format(err))\n\n if auth_source == 'env':\n self.log('Retrieving credentials from environment')\n env_credentials = self._get_env_credentials()\n return env_credentials\n\n if auth_source == 'credential_file':\n self.log(\"Retrieving credentials from credential file\")\n profile = params.get('profile') or 'default'\n default_credentials = self._get_profile(profile)\n return default_credentials\n\n # auto, precedence: module parameters -> environment variables -> default profile in ~/.azure/credentials\n # try module params\n if arg_credentials['profile'] is not None:\n self.log('Retrieving credentials with profile parameter.')\n credentials = self._get_profile(arg_credentials['profile'])\n return credentials\n\n if arg_credentials['subscription_id']:\n self.log('Received credentials from parameters.')\n return arg_credentials\n\n # try environment\n env_credentials = self._get_env_credentials()\n if env_credentials:\n self.log('Received credentials from env.')\n return env_credentials\n\n # try default profile from ~./azure/credentials\n default_credentials = self._get_profile()\n if default_credentials:\n self.log('Retrieved default profile credentials from ~/.azure/credentials.')\n return default_credentials\n\n try:\n if HAS_AZURE_CLI_CORE:\n self.log('Retrieving credentials from AzureCLI profile')\n cli_credentials = self._get_azure_cli_credentials()\n return cli_credentials\n except CLIError as ce:\n self.log('Error getting AzureCLI profile credentials - {0}'.format(ce))\n\n return None\n\n def acquire_token_with_username_password(self, authority, resource, username, password, client_id, tenant):\n authority_uri = authority\n\n if tenant is not None:\n authority_uri = authority + '/' + tenant\n\n context = AuthenticationContext(authority_uri)\n token_response = context.acquire_token_with_username_password(resource, username, password, client_id)\n\n return AADTokenCredentials(token_response)\n\n def log(self, msg, pretty_print=False):\n pass\n # Use only during module development\n # if self.debug:\n # log_file = open('azure_rm.log', 'a')\n # if pretty_print:\n # log_file.write(json.dumps(msg, indent=4, sort_keys=True))\n # else:\n # log_file.write(msg + u'\\n')\n","sub_path":"env/lib/python3.9/site-packages/ansible/module_utils/azure_rm_common.py","file_name":"azure_rm_common.py","file_ext":"py","file_size_in_byte":62599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"41293104","text":"import discord\r\nimport asyncio\r\nimport random\r\nimport pickle\r\nfrom discord.ext import commands\r\nimport os\r\n\r\nclient = commands.Bot(command_prefix=':G ')\r\n\r\nfortune_point = [-6, -3, -1, 1, 4, 7, 10, 14, 19]\r\ncategory = [\"Aces\", \"Deuces\", \"Threes\", \"Fours\", \"Fives\", \"Sixes\", \"subtotal\", \"Choice\", \"4 of a Kind\", \"Full House\",\r\n \"S.Straight\", \"L.Straight\", \"Yacht\", \"Total\"]\r\n\r\n\r\n@client.event\r\nasync def on_ready():\r\n print(\"Bot ID : \" + str(client.user.id))\r\n print(\"System Online\")\r\n game = discord.Game(\"미니게임 준비\")\r\n await client.change_presence(status=discord.Status.online, activity=game)\r\n\r\n\r\n# score.bin 파일 불러오는 함수\r\ndef scoreFileRead(*user_name: discord.Member):\r\n try:\r\n with open(\"score.bin\", \"rb\") as f: # score 파일 읽기\r\n score_data = pickle.load(f)\r\n\r\n except FileNotFoundError: # 파일이 없으면\r\n with open(\"score.bin\", \"wb+\") as f: # 파일을 만들기\r\n score_data = dict()\r\n pickle.dump(score_data, f) # 저장\r\n\r\n for i in range(len(user_name)):\r\n if str(user_name[i].id) not in score_data:\r\n score_data[str(user_name[i].id)] = 0\r\n\r\n return score_data\r\n\r\n\r\n# rsp.bin 파일 불러오는 함수\r\ndef rspFileRead(*user_name: discord.Member):\r\n try:\r\n with open(\"rsp.bin\", \"rb\") as f: # score 파일 읽기\r\n rsp_data = pickle.load(f)\r\n\r\n except FileNotFoundError: # 파일이 없으면\r\n with open(\"rsp.bin\", \"wb+\") as f: # 파일을 만들기\r\n rsp_data = dict()\r\n pickle.dump(rsp_data, f) # 저장\r\n\r\n for i in range(len(user_name)):\r\n if (str(user_name[i].id), \"win\") not in rsp_data:\r\n rsp_data[str(user_name[i].id), \"win\"] = 0\r\n rsp_data[str(user_name[i].id), \"lose\"] = 0\r\n rsp_data[str(user_name[i].id), \"draw\"] = 0\r\n\r\n return rsp_data\r\n\r\n\r\n# fortune.bin 파일 불러오는 함수\r\ndef fortuneFileRead(*user_name: discord.Member):\r\n try:\r\n with open(\"fortune.bin\", \"rb\") as f: # score 파일 읽기\r\n fortune_data = pickle.load(f)\r\n\r\n except FileNotFoundError: # 파일이 없으면\r\n with open(\"fortune.bin\", \"wb+\") as f: # 파일을 만들기\r\n fortune_data = dict()\r\n pickle.dump(fortune_data, f) # 저장\r\n\r\n for i in range(len(user_name)):\r\n if (str(user_name[i].id), \"7\") not in fortune_data:\r\n fortune_data[str(user_name[i].id), \"7\"] = 0\r\n fortune_data[str(user_name[i].id), \"8\"] = 0\r\n fortune_data[str(user_name[i].id), \"9\"] = 0\r\n fortune_data[str(user_name[i].id), \"Clear\"] = 0\r\n\r\n return fortune_data\r\n\r\n\r\n# yacht.bin 파일 불러오는 함수\r\ndef yachtFileRead(*user_name: discord.Member):\r\n try:\r\n with open(\"yacht.bin\", \"rb\") as f: # score 파일 읽기\r\n yacht_data = pickle.load(f)\r\n\r\n except FileNotFoundError: # 파일이 없으면\r\n with open(\"yacht.bin\", \"wb+\") as f: # 파일을 만들기\r\n yacht_data = dict()\r\n pickle.dump(yacht_data, f) # 저장\r\n\r\n for i in range(len(user_name)):\r\n if (str(user_name[i].id), \"win\") not in yacht_data:\r\n yacht_data[str(user_name[i].id), \"win\"] = 0\r\n yacht_data[str(user_name[i].id), \"lose\"] = 0\r\n yacht_data[str(user_name[i].id), \"draw\"] = 0\r\n yacht_data[str(user_name[i].id), \"max\"] = 0\r\n\r\n return yacht_data\r\n\r\n\r\n@client.command(name=\"전적_검색\", pass_context=True)\r\n# No.100 점수 확인 명령\r\nasync def showName(ctx, user_name: discord.Member):\r\n score_data = scoreFileRead(user_name)\r\n rsp_data = rspFileRead(user_name)\r\n fortune_data = fortuneFileRead(user_name)\r\n yacht_data = yachtFileRead(user_name)\r\n\r\n # point\r\n embed = discord.Embed(title=\"[\" + str(user_name) + \"] Info\", description=\" \", color=0xffff00)\r\n embed.add_field(name=\"포인트\", value=str(score_data[str(user_name.id)]) + \" point\", inline=False)\r\n # 가위바위보\r\n if rsp_data[str(user_name.id), \"win\"] == rsp_data[str(user_name.id), \"lose\"] == rsp_data[\r\n str(user_name.id), \"draw\"] == 0:\r\n embed.add_field(name=\"가위바위보\", value=\"승률 : 0% [승무패 : 0 / 0 / 0]\", inline=False)\r\n else:\r\n embed.add_field(name=\"가위바위보\",\r\n value=\"승률 : \" + \"{0:.3f}\".format(100 * rsp_data[str(user_name.id), \"win\"] / (\r\n rsp_data[str(user_name.id), \"win\"] + rsp_data[str(user_name.id), \"lose\"]))\r\n + \"% [승무패 : \" + str(rsp_data[str(user_name.id), \"win\"]) + \" / \"\r\n + str(rsp_data[str(user_name.id), \"draw\"]) + \" / \"\r\n + str(rsp_data[str(user_name.id), \"lose\"]) + \"]\", inline=False)\r\n # 운빨망겜\r\n embed.add_field(name=\"운빨망겜\", value=\"stage 7 : \" + str(fortune_data[str(user_name.id), \"7\"])\r\n + \"회 / stage 8 : \" + str(fortune_data[str(user_name.id), \"8\"])\r\n + \"회\\nstage 9 : \" + str(fortune_data[str(user_name.id), \"9\"])\r\n + \"회 / All Stage Clear : \" + str(\r\n fortune_data[str(user_name.id), \"Clear\"]) + \"회\", inline=False)\r\n # 야추\r\n if yacht_data[str(user_name.id), \"win\"] == yacht_data[str(user_name.id), \"lose\"] == yacht_data[\r\n str(user_name.id), \"draw\"] == 0:\r\n embed.add_field(name=\"야추\",\r\n value=\"승률 : 0% [승무패 : 0 / 0 / 0]\\n최고 점수 : \" + str(yacht_data[str(user_name.id), \"max\"]),\r\n inline=False)\r\n else:\r\n embed.add_field(name=\"야추\",\r\n value=\"승률 : \" + \"{0:.3f}\".format(100 * yacht_data[str(user_name.id), \"win\"] / (\r\n yacht_data[str(user_name.id), \"win\"] + yacht_data[str(user_name.id), \"lose\"]))\r\n + \"% [승무패 : \" + str(yacht_data[str(user_name.id), \"win\"]) + \"/\"\r\n + str(yacht_data[str(user_name.id), \"draw\"]) + \"/\"\r\n + str(yacht_data[str(user_name.id), \"lose\"])\r\n + \"]\\n최고 점수 : \" + str(yacht_data[str(user_name.id), \"max\"]), inline=False)\r\n await ctx.send(embed=embed)\r\n\r\n with open(\"score.bin\", \"wb\") as f:\r\n pickle.dump(score_data, f) # 저장하기\r\n with open(\"rsp.bin\", \"wb\") as f:\r\n pickle.dump(rsp_data, f)\r\n with open(\"fortune.bin\", \"wb\") as f:\r\n pickle.dump(fortune_data, f)\r\n with open(\"yacht.bin\", \"wb\") as f:\r\n pickle.dump(yacht_data, f)\r\n\r\n\r\n@client.command(name=\"가위바위보\", pass_context=True)\r\n# No.101 가위바위보 게임 명령\r\nasync def rsp(ctx):\r\n def rsp_text(num):\r\n if num == 0:\r\n return \"가위\"\r\n elif num == 1:\r\n return \"바위\"\r\n elif num == 2:\r\n return \"보\"\r\n\r\n score_data = scoreFileRead(ctx.author)\r\n rsp_data = rspFileRead(ctx.author)\r\n\r\n embed = discord.Embed(title=\"가위바위보 [Player : \" + str(ctx.author) + \"]\",\r\n description=\":가위, :바위, :보 중 하나를 입력해 주세요.\", color=0xaaaaaa)\r\n await ctx.send(embed=embed)\r\n\r\n while True:\r\n def check(m):\r\n return m.author == ctx.author and m.channel == ctx.channel # 입력한 사람이 본인인지 확인\r\n\r\n msg = await client.wait_for(\"message\", check=check)\r\n if msg.content == \":가위\":\r\n user_choose = 0\r\n break\r\n elif msg.content == \":바위\":\r\n user_choose = 1\r\n break\r\n elif msg.content == \":보\":\r\n user_choose = 2\r\n break\r\n else:\r\n await ctx.send(\"잘못된 입력입니다. 다시 입력해주세요.\")\r\n\r\n AI_choose = random.randint(0, 2)\r\n\r\n if user_choose == AI_choose: # 비긴 경우\r\n rsp_data[str(ctx.author.id), \"draw\"] += 1\r\n embed = discord.Embed(title=\"Player : \" + rsp_text(user_choose) + \" vs. \" + rsp_text(AI_choose) + \" : Bot\",\r\n description=\"비겼습니다. 0 point 획득 [현재 point : \" + str(score_data[str(ctx.author.id)]) + \"]\",\r\n color=0xaaaaaa)\r\n\r\n elif user_choose - AI_choose == 1 or user_choose - AI_choose == -2: # 이긴 경우\r\n score_data[str(ctx.author.id)] += 5\r\n rsp_data[str(ctx.author.id), \"win\"] += 1\r\n embed = discord.Embed(title=\"Player : \" + rsp_text(user_choose) + \" vs. \" + rsp_text(AI_choose) + \" : Bot\",\r\n description=\"이겼습니다! 5 point 획득 [현재 point : \" + str(score_data[str(ctx.author.id)]) + \"]\",\r\n color=0xaaaaaa)\r\n\r\n elif user_choose - AI_choose == -1 or user_choose - AI_choose == 2: # 진 경우\r\n score_data[str(ctx.author.id)] -= 3\r\n if score_data[str(ctx.author.id)] < 0:\r\n score_data[str(ctx.author.id)] = 0\r\n rsp_data[str(ctx.author.id), \"lose\"] += 1\r\n embed = discord.Embed(title=\"Player : \" + rsp_text(user_choose) + \" vs. \" + rsp_text(AI_choose) + \" : Bot\",\r\n description=\"졌습니다. -3 point 획득 [현재 point : \" + str(score_data[str(ctx.author.id)]) + \"]\",\r\n color=0xaaaaaa)\r\n\r\n await ctx.send(embed=embed)\r\n\r\n with open(\"score.bin\", \"wb\") as f:\r\n pickle.dump(score_data, f) # 저장하기\r\n with open(\"rsp.bin\", \"wb\") as f:\r\n pickle.dump(rsp_data, f)\r\n\r\n\r\n@client.command(name=\"운빨망겜\", pass_context=True)\r\n# No.102 운빨망겜 명령\r\nasync def fortune(ctx):\r\n score_data = scoreFileRead(ctx.author)\r\n fortune_data = fortuneFileRead(ctx.author)\r\n\r\n embed = discord.Embed(title=\"운빨테스트 [Player : \" + str(ctx.author) + \"]\",\r\n description=\"게임 설명 : 1~10 중 아무 숫자나 하나를 입력하면 됩니다.\", color=0x62d4a8)\r\n await ctx.send(embed=embed)\r\n\r\n global fortune_point\r\n stage = 1\r\n percent = 90\r\n get_point = fortune_point[0]\r\n num = [0 for p in range(10)]\r\n while True:\r\n embed = discord.Embed(title=\"운빨테스트 [Stage \" + str(stage) + \" / 확률 : \" + str(percent) + \".0%]\",\r\n description=\" \", color=0x62d4a8)\r\n await ctx.send(embed=embed)\r\n\r\n erase_two = 0\r\n while True: # 숫자 입력 받기\r\n def check(m):\r\n return m.author == ctx.author and m.channel == ctx.channel # 입력한 사람이 본인인지 확인\r\n\r\n try:\r\n msg = await client.wait_for(\"message\", check=check)\r\n isRange = (1 <= int(msg.content) <= 10)\r\n\r\n except ValueError:\r\n erase_two += 1\r\n await ctx.channel.purge(limit=1)\r\n await ctx.send(\"잘못된 입력입니다. 1~10 사이의 정수를 입력해주세요.\")\r\n\r\n else:\r\n if isRange:\r\n break\r\n else:\r\n erase_two += 1\r\n await ctx.channel.purge(limit=1)\r\n await ctx.send(\"잘못된 입력입니다. 1~10 사이의 정수를 입력해주세요.\")\r\n\r\n i = 0 # 랜덤 뽑기\r\n for j in range(10): # 값 초기화\r\n num[j] = False\r\n while i < (percent / 10): # 랜덤 뽑기\r\n a = random.randint(0, 9)\r\n if not num[a]:\r\n i += 1\r\n num[a] = True\r\n\r\n if stage == 1:\r\n await ctx.channel.purge(limit=(2 + erase_two))\r\n else:\r\n await ctx.channel.purge(limit=(3 + erase_two))\r\n if num[int(msg.content) - 1]: # 당첨인 경우\r\n if stage == 9: # 마지막 스테이지까지 클리어 한 경우\r\n score_data[str(ctx.author.id)] += 25\r\n fortune_data[str(ctx.author.id), \"Clear\"] += 1\r\n embed = discord.Embed(title=\"마지막 9 stage 까지 클리어 했습니다! [Latest Stage : 어캐헀누!!]\",\r\n description=\"27 point 획득 [현재 point : \" + str(\r\n score_data[str(ctx.author.id)]) + \"]\", color=0x62d4a8)\r\n await ctx.send(embed=embed)\r\n\r\n with open(\"score.bin\", \"wb\") as f:\r\n pickle.dump(score_data, f) # 저장하기\r\n break\r\n else:\r\n stage += 1\r\n percent -= 10\r\n get_point = fortune_point[stage - 1]\r\n embed = discord.Embed(title=str(msg.content) + \"은(는) 꽝이 아니었습니다!\", description=\" \", color=0x62d4a8)\r\n await ctx.send(embed=embed)\r\n else:\r\n score_data[str(ctx.author.id)] += get_point\r\n if score_data[str(ctx.author.id)] < 0:\r\n score_data[str(ctx.author.id)] = 0\r\n if stage == 7:\r\n fortune_data[str(ctx.author.id), \"7\"] += 1\r\n if stage == 8:\r\n fortune_data[str(ctx.author.id), \"8\"] += 1\r\n if stage == 9:\r\n fortune_data[str(ctx.author.id), \"9\"] += 1\r\n\r\n p = 0\r\n clear_num: list = [0 for p in range(10 - stage)]\r\n for i in range(10):\r\n if num[i]:\r\n clear_num[p] = i + 1\r\n p += 1\r\n\r\n embed = discord.Embed(title=str(msg.content) + \"은(는) 꽝입니다. [Latest Stage : \" + str(stage) + \"]\",\r\n description=str(get_point) + \" point 획득 [현재 point : \" + str(\r\n score_data[str(ctx.author.id)]) + \"]\\n\\n클리어 숫자 :\", color=0x62d4a8)\r\n for i in range(10 - stage):\r\n embed.add_field(name=\"번호\", value=str(clear_num[i]), inline=True)\r\n await ctx.send(embed=embed)\r\n\r\n with open(\"score.bin\", \"wb\") as f:\r\n pickle.dump(score_data, f) # 저장하기\r\n with open(\"fortune.bin\", \"wb\") as f:\r\n pickle.dump(fortune_data, f)\r\n break\r\n\r\n\r\n@client.command(name=\"야추\", pass_context=True)\r\n# No.103 Yacht 명령\r\nasync def yacht(ctx, opponent: discord.Member):\r\n score = [[0] * 2 for p in range(14)]\r\n cate = [[True] * 2 for p in range(14)]\r\n surren = [False, False]\r\n\r\n def check_ctx(m): # player 입력 받는 조건 함수\r\n return m.author == ctx.author\r\n\r\n def check_opponent(m): # opponent 입력 받는 조건 함수\r\n return m.author == opponent\r\n\r\n score_data = scoreFileRead(ctx.author, opponent)\r\n yacht_data = yachtFileRead(ctx.author, opponent)\r\n\r\n time_out = False\r\n start = False\r\n go = False\r\n\r\n if ctx.author == opponent:\r\n embed = discord.Embed(title=\"Yacht Dice [Single Play]\",\r\n description=\"Player A : [\" + str(ctx.author) + \"] vs. [\" + str(opponent) + \"] : Player B\",\r\n color=0x62d4a8)\r\n embed.add_field(name=\"[주의 사항]\", value=\"1) 싱글 플레이에서는 승무패와 포인트가 저장되지 않습니다.\\n\"\r\n + \"2) 텍스트가 나오자마자 채팅을 입력하면 오작동할 가능성이 있습니다.\")\r\n await ctx.send(embed=embed)\r\n go = True\r\n await asyncio.sleep(2.0)\r\n else:\r\n # 나중에 카테고리가 만두인 경우로 변경\r\n if opponent.id == 763786586684391498 or opponent.id == 762352756652244996 or opponent.id == 762303766145269760:\r\n embed = discord.Embed(title=\"Yacht Dice [warning]\",\r\n description=\"Bot과는 게임을 돌릴 수 없습니다.\",\r\n color=0x62d4a8)\r\n await ctx.send(embed=embed)\r\n else: \r\n embed = discord.Embed(title=\"Yacht Dice [2 Player]\",\r\n description=\"Player A : [\" + str(ctx.author) + \"] vs. [\" + str(\r\n opponent) + \"] : Player B\\n\"\r\n + str(opponent) + \"님은 게임울 수락하려면 \\\"수락\\\"을, 아니면 \\\"거절\\\"을 입력하세요.\", color=0x62d4a8)\r\n embed.add_field(name=\"[주의 사항]\", value=\"1) 원활한 게임 진행을 위해 두 플레이어는 같은 체널을 사용해주세요.\\n\"\r\n + \"2) 텍스트가 나오자마자 채팅을 입력하면 오작동할 가능성이 있습니다.\")\r\n await ctx.send(embed=embed)\r\n\r\n while True: # 상대방 입장 받기\r\n try:\r\n msg = await client.wait_for(\"message\", check=check_opponent, timeout=10.0)\r\n except asyncio.TimeoutError:\r\n time_out = True\r\n break\r\n else:\r\n if msg.content == \"수락\":\r\n start = True\r\n break\r\n elif msg.content == \"거절\":\r\n start = False\r\n break\r\n else:\r\n await ctx.send(\"잘못된 입력입니다. 다시 입력해주세요.\")\r\n\r\n if time_out: # 시간이 초과된 경우\r\n embed = discord.Embed(title=\"Yacht Dice [2 Player]\",\r\n description=\"Player A : \" + str(ctx.author) + \" vs. \" + str(\r\n opponent) + \" : Player B\\n\"\r\n + \"입력 시간이 초과되었습니다.\", color=0x62d4a8)\r\n await ctx.send(embed=embed)\r\n \r\n elif not start: # 게임이 거절된 경우\r\n embed = discord.Embed(title=\"Yacht Dice [2 Player]\",\r\n description=\"Player A : \" + str(ctx.author) + \" vs. \" + str(\r\n opponent) + \" : Player B\\n\"\r\n + str(opponent) + \"에 의해 게임이 거절되었습니다.\", color=0x62d4a8)\r\n await ctx.send(embed=embed)\r\n \r\n else: # 게임을 수락한 경우\r\n go = True\r\n \r\n if go: # 게임이 수락된 경우\r\n for turn in range(24):\r\n fixed = [False, False, False, False, False]\r\n dice = [0 for p in range(5)]\r\n erase_two = 0\r\n\r\n if turn % 2 == 0:\r\n embed = discord.Embed(title=\"Yacht Dice [Player A's Turn (\" + str(int(turn / 2) + 1) + \" / 12)]\",\r\n description=\"Player A : [\" + str(ctx.author) + \"] vs. [\" + str(\r\n opponent) + \"] : Player B\", color=0xaa0000)\r\n else:\r\n embed = discord.Embed(title=\"Yacht Dice [Player B's Turn (\" + str(int(turn / 2) + 1) + \" / 12)]\",\r\n description=\"Player A : [\" + str(ctx.author) + \"] vs. [\" + str(\r\n opponent) + \"] : Player B\", color=0x0000aa)\r\n for i in range(len(category)):\r\n if i == 6:\r\n if cate[i][turn % 2]:\r\n embed.add_field(name=str(category[i]),\r\n value=str(score[i][0]) + \" / \" + str(\r\n score[i][1]) + \" [Aces ~ Sixes가 63점 이상이면 보너스 35점]\", inline=False)\r\n elif i == 13:\r\n embed.add_field(name=str(category[i]),\r\n value=str(score[i][0]) + \" / \" + str(score[i][1]), inline=True)\r\n else:\r\n if cate[i][turn % 2]:\r\n embed.add_field(name=\"[\" + str(i + 1) + \".] \" + str(category[i]),\r\n value=str(score[i][0]) + \" / \" + str(score[i][1]), inline=True)\r\n else:\r\n embed.add_field(name=str(i + 1) + \". \" + str(category[i]),\r\n value=str(score[i][0]) + \" / \" + str(score[i][1]), inline=True)\r\n embed.add_field(name=\"----------------------------------------------------------\",\r\n value=\"\\\"roll\\\"을 입력해서 주사위를 던지세요.\\n게임을 그만두려면 \\\"항복\\\"을 입력하세요.\", inline=False)\r\n await ctx.send(embed=embed)\r\n # 주사위 굴리기\r\n for p in range(3):\r\n def text(fix):\r\n if fix:\r\n return \"x \"\r\n else:\r\n return \"o \"\r\n\r\n if p != 0:\r\n if turn % 2 == 0:\r\n embed = discord.Embed(title=\"현재 주사위 [Player A]\", color=0xaa0000)\r\n else:\r\n embed = discord.Embed(title=\"현재 주사위 [Player B]\", color=0x0000aa)\r\n embed.add_field(name=\"----------------------------------------------------------\",\r\n value=str(dice[0]) + \" \" + str(dice[1]) + \" \" + str(dice[2]) + \" \" + str(\r\n dice[3]) + \" \" + str(dice[4])\r\n + \"\\n\" + text(fixed[0]) + \" \" + text(fixed[1]) + \" \" + text(\r\n fixed[2]) + \" \" + text(fixed[3]) + \" \" + text(fixed[4]), inline=False)\r\n await ctx.send(embed=embed)\r\n\r\n erase_two = 0\r\n while True: # Player 입력받기 [roll]\r\n if turn % 2 == 0:\r\n msg = await client.wait_for(\"message\", check=check_ctx)\r\n else:\r\n msg = await client.wait_for(\"message\", check=check_opponent)\r\n if msg.content == \"roll\":\r\n break\r\n elif msg.content == \"항복\":\r\n if turn % 2 == 0: # Player A가 항복한 경우\r\n embed = discord.Embed(title=\"[Player A]\", description=\"정말로 항복하시겠습니까?\\n [yes] / [no]\",\r\n color=0xaa0000)\r\n else:\r\n embed = discord.Embed(title=\"[Player B]\", description=\"정말로 항복하시겠습니까?\\n [yes] / [no]\",\r\n color=0x0000aa)\r\n await ctx.send(embed=embed)\r\n\r\n while True: # Player 입력받기\r\n if turn % 2 == 0:\r\n msg = await client.wait_for(\"message\", check=check_ctx)\r\n else:\r\n msg = await client.wait_for(\"message\", check=check_opponent)\r\n\r\n if msg.content == \"yes\":\r\n surren[turn % 2] = True\r\n await ctx.channel.purge(limit=(4 + erase_two))\r\n break\r\n elif msg.content == \"no\":\r\n await ctx.channel.purge(limit=(3 + erase_two))\r\n erase_two = 0\r\n break\r\n else:\r\n await ctx.channel.purge(limit=1)\r\n erase_two += 1\r\n await ctx.send(\"잘못된 입력입니다. 다시 입력해주세요.\")\r\n if msg.content == \"yes\":\r\n break\r\n else:\r\n await ctx.channel.purge(limit=1)\r\n erase_two += 1\r\n await ctx.send(\"잘못된 입력입니���. 다시 입력해주세요.\")\r\n\r\n if True in surren:\r\n break\r\n\r\n for i in range(5): # 주사위 굴리기\r\n if not fixed[i]:\r\n dice[i] = random.randint(1, 6)\r\n\r\n if p == 2: # 마지막 차례는 고정 선택이 아니라 바로 점수 선택으로 건너뛰기\r\n break\r\n\r\n if p == 0:\r\n await ctx.channel.purge(limit=(1 + erase_two))\r\n else:\r\n await ctx.channel.purge(limit=(2 + erase_two))\r\n if turn % 2 == 0:\r\n embed = discord.Embed(title=\"현재 주사위 [Player A]\", color=0xaa0000)\r\n else:\r\n embed = discord.Embed(title=\"현재 주사위 [Player B]\", color=0x0000aa)\r\n embed.add_field(name=\"----------------------------------------------------------\",\r\n value=str(dice[0]) + \" \" + str(dice[1]) + \" \" + str(dice[2]) + \" \" + str(\r\n dice[3]) + \" \" + str(dice[4])\r\n + \"\\n\" + text(fixed[0]) + \" \" + text(fixed[1]) + \" \" + text(\r\n fixed[2]) + \" \" + text(fixed[3]) + \" \" + text(fixed[4])\r\n + \"\\n[다시 굴릴 주사위는 o, 고정할 주사위는 x로 입력해주세요. ex) x x o o x]\", inline=False)\r\n await ctx.send(embed=embed)\r\n\r\n # 고정할 주사위 선택하는 부분\r\n erase_two = 0\r\n while True:\r\n error = False\r\n if turn % 2 == 0:\r\n msg = await client.wait_for(\"message\", check=check_ctx)\r\n else:\r\n msg = await client.wait_for(\"message\", check=check_opponent)\r\n param = msg.content.split()\r\n if len(param) == 5:\r\n for i in range(5):\r\n if param[i] == \"x\":\r\n fixed[i] = True\r\n elif param[i] == \"o\":\r\n fixed[i] = False\r\n else:\r\n error = True\r\n else:\r\n error = True\r\n\r\n if not error:\r\n break\r\n else:\r\n if msg.content == \"항복\":\r\n if turn % 2 == 0: # Player A가 항복한 경우\r\n embed = discord.Embed(title=\"[Player A]\", description=\"정말로 항복하시겠습니까?\\n [yes] / [no]\",\r\n color=0xaa0000)\r\n else:\r\n embed = discord.Embed(title=\"[Player B]\", description=\"정말로 항복하시겠습니까?\\n [yes] / [no]\",\r\n color=0x0000aa)\r\n await ctx.send(embed=embed)\r\n\r\n while True: # Player 입력받기\r\n if turn % 2 == 0:\r\n msg = await client.wait_for(\"message\", check=check_ctx)\r\n else:\r\n msg = await client.wait_for(\"message\", check=check_opponent)\r\n\r\n if msg.content == \"yes\":\r\n surren[turn % 2] = True\r\n await ctx.channel.purge(limit=(4 + erase_two))\r\n break\r\n elif msg.content == \"no\":\r\n await ctx.channel.purge(limit=(3 + erase_two))\r\n erase_two = 0\r\n break\r\n else:\r\n await ctx.channel.purge(limit=1)\r\n erase_two += 1\r\n await ctx.send(\"잘못된 입력입니다. 다시 입력해주세요.\")\r\n if msg.content == \"yes\":\r\n break\r\n else:\r\n erase_two += 1\r\n await ctx.channel.purge(limit=1)\r\n await ctx.send(\"잘못된 입력입니다. 다시 입력해주세요.\")\r\n\r\n if True in surren:\r\n break\r\n # 고정이 다 O 인 경우 반복 종료하고 점수 배정으로 넘어가기\r\n skip = 0\r\n for i in range(5):\r\n if fixed[i]:\r\n skip += 1\r\n if skip == 5:\r\n break\r\n\r\n await ctx.channel.purge(limit=(2 + erase_two))\r\n # 점수 배정 하기\r\n if True in surren:\r\n break\r\n\r\n await ctx.channel.purge(limit=(2 + erase_two))\r\n if turn % 2 == 0:\r\n embed = discord.Embed(title=\"주사위 현황 [Player A]\", color=0xaa0000)\r\n else:\r\n embed = discord.Embed(title=\"주사위 현황 [Player B]\", color=0x0000aa)\r\n embed.add_field(name=\"----------------------------------------------------------\",\r\n value=str(dice[0]) + \" \" + str(dice[1]) + \" \" + str(dice[2]) + \" \" + str(\r\n dice[3]) + \" \" + str(dice[4])\r\n + \"\\n[점수를 배정할 카테고리의 번호를 입력하세요.]\", inline=False)\r\n await ctx.send(embed=embed)\r\n\r\n erase_two = 0\r\n while True: # Player 입력받기 [카테고리]\r\n error = False\r\n choice = 0\r\n try:\r\n if turn % 2 == 0:\r\n msg = await client.wait_for(\"message\", check=check_ctx)\r\n else:\r\n msg = await client.wait_for(\"message\", check=check_opponent)\r\n\r\n if msg.content == \"항복\":\r\n if turn % 2 == 0: # Player A가 항복한 경우\r\n embed = discord.Embed(title=\"[Player A]\", description=\"정말로 항복하시겠습니까?\\n [yes] / [no]\",\r\n color=0xaa0000)\r\n else:\r\n embed = discord.Embed(title=\"[Player B]\", description=\"정말로 항복하시겠습니까?\\n [yes] / [no]\",\r\n color=0x0000aa)\r\n await ctx.send(embed=embed)\r\n\r\n while True: # Player 입력받기\r\n if turn % 2 == 0:\r\n msg = await client.wait_for(\"message\", check=check_ctx)\r\n else:\r\n msg = await client.wait_for(\"message\", check=check_opponent)\r\n\r\n if msg.content == \"yes\":\r\n surren[turn % 2] = True\r\n await ctx.channel.purge(limit=(4 + erase_two))\r\n break\r\n elif msg.content == \"no\":\r\n await ctx.channel.purge(limit=(3 + erase_two))\r\n erase_two = 0\r\n break\r\n else:\r\n await ctx.channel.purge(limit=1)\r\n erase_two += 1\r\n await ctx.send(\"잘못된 입력입니다. 다시 입력해주세요.\")\r\n if msg.content == \"yes\":\r\n break\r\n\r\n except ValueError:\r\n erase_two += 1\r\n await ctx.channel.purge(limit=1)\r\n await ctx.send(\"잘못된 입력입니다. 카테고리의 번호를 입력해주세요.\")\r\n\r\n else:\r\n for i in range(14):\r\n if msg.content == str(i + 1):\r\n if cate[i][turn % 2]:\r\n choice = i\r\n cate[i][turn % 2] = False\r\n break\r\n else:\r\n choice = 0\r\n await ctx.channel.purge(limit=1)\r\n erase_two += 1\r\n await ctx.send(\"이미 할당된 카테고리입니다. 다른 카테고리를 입력해주세요.\")\r\n error = True\r\n break\r\n\r\n # count 정의\r\n count = [0 for p in range(6)]\r\n for i in range(5):\r\n count[dice[i] - 1] += 1\r\n\r\n # subtotal / total\r\n if choice == 6 or choice == 13:\r\n await ctx.channel.purge(limit=1)\r\n erase_two += 1\r\n await ctx.send(\"subtotal이나 Total은 선택할 수 없습니다.\")\r\n error = True\r\n\r\n # Aces ~ Sixes\r\n elif 0 <= choice <= 5:\r\n for i in range(6):\r\n if choice == i:\r\n for j in range(5):\r\n if dice[j] == (i + 1):\r\n score[i][turn % 2] += (i + 1)\r\n cate[i][turn % 2] = False\r\n break\r\n\r\n # Choice\r\n elif choice == 7:\r\n for i in range(5):\r\n score[7][turn % 2] += dice[i]\r\n cate[7][turn % 2] = False\r\n\r\n # 4 of a Kind\r\n elif choice == 8:\r\n for i in range(6):\r\n if count[i] >= 4:\r\n for j in range(5):\r\n score[8][turn % 2] += dice[j]\r\n cate[8][turn % 2] = False\r\n break\r\n # Full House\r\n elif choice == 9:\r\n for i in range(36):\r\n if count[int(i / 6)] == 3 and count[i % 6] == 2:\r\n for j in range(5):\r\n score[9][turn % 2] += dice[j]\r\n cate[9][turn % 2] = False\r\n break\r\n # S.Straight\r\n elif choice == 10:\r\n if count[2] >= 1 and count[3] >= 1:\r\n if (count[0] >= 1 and count[1] >= 1) or (count[1] >= 1 and count[4] >= 1) or (\r\n count[4] >= 1 and count[5] >= 1):\r\n score[10][turn % 2] = 15\r\n cate[10][turn % 2] = False\r\n # L.Straight\r\n elif choice == 11:\r\n if count[1] == 1 and count[2] == 1 and count[3] == 1 and count[4] == 1 and (\r\n count[0] == 1 or count[5] == 1):\r\n score[11][turn % 2] = 30\r\n cate[11][turn % 2] = False\r\n # Yacht\r\n elif choice == 12:\r\n for i in range(6):\r\n if count[i] == 5:\r\n score[12][turn % 2] = 50\r\n cate[12][turn % 2] = False\r\n break\r\n else:\r\n await ctx.channel.purge(limit=1)\r\n erase_two += 1\r\n await ctx.send(\"해당 번호는 존재하지 않습니다. 점수판에 옆의 번호로 입력해주세요.\")\r\n error = True\r\n\r\n if not error:\r\n await ctx.channel.purge(limit=(3 + erase_two))\r\n break\r\n\r\n if True in surren:\r\n break\r\n\r\n # subtotal 계산\r\n score[6][turn % 2] = 0\r\n for j in range(6):\r\n score[6][turn % 2] += score[j][turn % 2]\r\n\r\n # bonus 점수\r\n if score[6][turn % 2] >= 63:\r\n bonus = 35\r\n else:\r\n bonus = 0\r\n\r\n # total 계산\r\n score[13][turn % 2] = 0\r\n for j in range(6, 13):\r\n score[13][turn % 2] += score[j][turn % 2]\r\n score[13][turn % 2] += bonus\r\n\r\n # 마무리 텍스트 출력\r\n embed = discord.Embed(title=\"Yacht Dice\",\r\n description=\"Player A : [\" + str(ctx.author) + \"] vs. [\" + str(opponent)\r\n + \"] : Player B\", color=0xaaaaaa)\r\n for i in range(len(category)):\r\n if i == 6:\r\n embed.add_field(name=\"[\" + str(category[i]) + \"]\", value=str(score[i][0]) + \" / \"\r\n + str(\r\n score[i][1]) + \" [Aces ~ Sixes가 63점 이상이면 보너스 35점]\", inline=False)\r\n else:\r\n embed.add_field(name=\"[\" + str(category[i]) + \"]\", value=str(score[i][0]) + \" / \"\r\n + str(score[i][1]), inline=True)\r\n await ctx.send(embed=embed)\r\n\r\n # 점수 계산 함수\r\n def scorefunc(player, outcome):\r\n get_point = 0\r\n if 150 <= score[13][player] < 200:\r\n get_point = 2\r\n elif 200 <= score[13][player] < 250:\r\n get_point = 4\r\n elif 250 <= score[13][player] < 275:\r\n get_point = 7\r\n elif 275 <= score[13][player] < 300:\r\n get_point = 10\r\n elif 300 <= score[13][player] <= 325:\r\n get_point = 15\r\n\r\n if outcome == \"win\":\r\n get_point += 15\r\n elif outcome == \"lose\":\r\n get_point -= 15\r\n\r\n return get_point\r\n\r\n # 점수 계산\r\n if ctx.author != opponent:\r\n if score[13][0] > score[13][1] or surren[1]: # A가 이긴 경우\r\n score_data[str(ctx.author.id)] += scorefunc(0, \"win\")\r\n yacht_data[str(ctx.author.id), \"win\"] += 1\r\n score_data[str(opponent.id)] += scorefunc(1, \"lose\")\r\n yacht_data[str(opponent.id), \"lose\"] += 1\r\n\r\n embed = discord.Embed(title=\"Yacht Dice [\" + str(ctx.author) + \" 승리!!]\", color=0xaa0000)\r\n embed.add_field(name=\"Player A : \" + str(score[13][0]) + \" vs. \" + str(score[13][1]) + \" : Player B\"\r\n , value=\"Player A : \" + str(scorefunc(0, \"win\")) + \" point 획득\\n\"\r\n + \"[현재 point : \" + str(score_data[str(ctx.author.id)]) + \"]\\n\"\r\n + \"Player B : \" + str(scorefunc(1, \"lose\")) + \" point 획득\"\r\n + \"[현재 point : \" + str(score_data[str(opponent.id)]) + \"]\", inline=False)\r\n\r\n elif score[13][0] < score[13][1] or surren[0]: # B가 이긴 경우\r\n score_data[str(ctx.author.id)] += scorefunc(0, \"lose\")\r\n yacht_data[str(ctx.author.id), \"lose\"] += 1\r\n score_data[str(opponent.id)] += scorefunc(1, \"win\")\r\n yacht_data[str(opponent.id), \"win\"] += 1\r\n\r\n embed = discord.Embed(title=\"Yacht Dice [\" + str(opponent) + \" 승리!!]\", color=0x0000aa)\r\n embed.add_field(name=\"Player A : \" + str(score[13][0]) + \" vs. \" + str(score[13][1]) + \" : Player B\"\r\n , value=\"Player A : \" + str(scorefunc(0, \"lose\")) + \" point 획득\"\r\n + \"[현재 point : \" + str(score_data[str(ctx.author.id)]) + \"]\\n\"\r\n + \"Player B : \" + str(scorefunc(1, \"win\")) + \" point 획득\"\r\n + \"[현재 point : \" + str(score_data[str(opponent.id)]) + \"]\", inline=False)\r\n\r\n elif score[13][0] == score[13][1]: # 무승부\r\n score_data[str(ctx.author.id)] += scorefunc(0, \"draw\")\r\n yacht_data[str(ctx.author.id), \"draw\"] += 1\r\n score_data[str(opponent.id)] += scorefunc(1, \"draw\")\r\n yacht_data[str(opponent.id), \"draw\"] += 1\r\n\r\n embed = discord.Embed(title=\"Yacht Dice [무승부입니다. (어캐했누)]\", color=0xaaaaaa)\r\n embed.add_field(name=\"Player A : \" + str(score[13][0]) + \" vs. \" + str(score[13][1]) + \" : Player B\"\r\n , value=\"Player A : \" + str(scorefunc(0, \"draw\")) + \" point 획득\"\r\n + \" [현재 point : \" + str(score_data[str(ctx.author.id)]) + \"]\\n\"\r\n + \"Player B : \" + str(scorefunc(1, \"draw\")) + \" point 획득\"\r\n + \" [현재 point : \" + str(score_data[str(opponent.id)]) + \"]\", inline=False)\r\n\r\n else:\r\n embed = discord.Embed(title=\"Yacht Dice [Single Play]\", color=0xaa0000)\r\n embed.add_field(name=\"Player A : \" + str(score[13][0]) + \" vs. \" + str(score[13][1]) + \" : Player B\"\r\n , value=\"[Single Play는 최고 기록만 저장됩니다.]\", inline=False)\r\n\r\n await ctx.send(embed=embed)\r\n\r\n if score[13][0] > yacht_data[str(ctx.author.id), \"max\"]:\r\n yacht_data[str(ctx.author.id), \"max\"] = score[13][0]\r\n if score[13][1] > yacht_data[str(opponent.id), \"max\"]:\r\n yacht_data[str(opponent.id), \"max\"] = score[13][1]\r\n\r\n with open(\"score.bin\", \"wb\") as f: # 저장하기\r\n pickle.dump(score_data, f)\r\n with open(\"yacht.bin\", \"wb\") as f:\r\n pickle.dump(yacht_data, f)\r\n\r\n\r\n@client.command(name=\"점수_조정\", pass_context=True)\r\n# No.104 점수 추가 명령\r\nasync def change(ctx, type, user_name: discord.Member, amount):\r\n if ctx.author.id == 540360394691313664: # 명령 입력한 사람이 llMiNEll인 경우\r\n check = False\r\n score_data = scoreFileRead(user_name)\r\n rsp_data = rspFileRead(user_name)\r\n fortune_data = fortuneFileRead(user_name)\r\n yacht_data = yachtFileRead(user_name)\r\n\r\n if type == \"점수\":\r\n score_data[str(user_name.id)] += int(amount)\r\n check = True\r\n\r\n elif type == \"가위바위보:win\":\r\n rsp_data[str(user_name.id), \"win\"] += int(amount)\r\n check = True\r\n\r\n elif type == \"가위바위보:lose\":\r\n rsp_data[str(user_name.id), \"lose\"] += int(amount)\r\n check = True\r\n\r\n elif type == \"가위바위보:draw\":\r\n rsp_data[str(user_name.id), \"draw\"] += int(amount)\r\n check = True\r\n\r\n elif type == \"운빨망겜:7\":\r\n fortune_data[str(user_name.id), \"7\"] += int(amount)\r\n check = True\r\n\r\n elif type == \"운빨망겜:8\":\r\n fortune_data[str(user_name.id), \"8\"] += int(amount)\r\n check = True\r\n\r\n elif type == \"운빨망겜:9\":\r\n fortune_data[str(user_name.id), \"9\"] += int(amount)\r\n check = True\r\n\r\n elif type == \"운빨망겜:Clear\":\r\n fortune_data[str(user_name.id), \"Clear\"] += int(amount)\r\n check = True\r\n\r\n elif type == \"야추:win\":\r\n yacht_data[str(user_name.id), \"win\"] += int(amount)\r\n check = True\r\n\r\n elif type == \"야추:lose\":\r\n yacht_data[str(user_name.id), \"lose\"] += int(amount)\r\n check = True\r\n\r\n elif type == \"야추:draw\":\r\n yacht_data[str(user_name.id), \"draw\"] += int(amount)\r\n check = True\r\n\r\n elif type == \"야추:max\":\r\n yacht_data[str(user_name.id), \"max\"] += int(amount)\r\n check = True\r\n\r\n if check:\r\n embed = discord.Embed(title=\"[System] \\\"\" + type + \"\\\"\",\r\n description=str(user_name) + \"의 점수가 \" + amount + \"만큼 증가하였습니다.\", color=0xaaaaaa)\r\n else:\r\n embed = discord.Embed(title=\"[System] 점수 조정\",\r\n description=\"Error 104002 : 존재하지 않는 type입니다.\", color=0xaaaaaa)\r\n await ctx.send(embed=embed)\r\n\r\n with open(\"score.bin\", \"wb\") as f:\r\n pickle.dump(score_data, f) # 저장하기\r\n with open(\"rsp.bin\", \"wb\") as f:\r\n pickle.dump(rsp_data, f)\r\n with open(\"fortune.bin\", \"wb\") as f:\r\n pickle.dump(fortune_data, f)\r\n with open(\"yacht.bin\", \"wb\") as f:\r\n pickle.dump(yacht_data, f)\r\n\r\n else:\r\n embed = discord.Embed(title=\"[System] 점수 조정\", description=\"Error 104001 : 이 Bot의 소유자에게만 권한이 있습니다.\",\r\n color=0xaaaaaa)\r\n await ctx.send(embed=embed)\r\n\r\naccess_token = os.environ[\"BOT_TOKEN\"]\r\nclient.run(access_token)\r\n","sub_path":"minigame_Bot.py","file_name":"minigame_Bot.py","file_ext":"py","file_size_in_byte":45632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"21588861","text":"#******************************************************************************\n#\n#******************************************************************************\nimport argparse\nimport h5py\nimport numpy\nimport csv\nimport os\n\ndef clear_metadata_value(attributes, attribute_name):\n \"\"\" Clear the specified attribute value.\n\n :param attributes: The list of attributes containing the value to be cleared.\n :param attribute_name: The name of the attribute to be cleared.\n \"\"\"\n\n if attribute_name in attributes:\n print(\"Information: The value for\", attribute_name, \"has been ignored.\")\n del attributes[attribute_name]\n\n#******************************************************************************\ndef get_metadata_type(attribute_name):\n \"\"\" Retrieve the specified attribute's type.\n\n :param attribute_name: The name of the attribute to retrive the type for.\n :returns: The attribute's type, None if not found.\n \"\"\"\n\n typeMap = dict()\n \n \"\"\"\n Carrier Metadata\n \"\"\"\n #Integer types\n typeMap['horizDatumValue'] = numpy.int64\n typeMap['timeRecordInterval'] = numpy.int64\n typeMap['numberOfTimes'] = numpy.int64\n typeMap['numberOfStations'] = numpy.int64\n typeMap['verticalDatum'] = numpy.int64\n typeMap['numPointsLongitudinal'] = numpy.int64\n typeMap['numPointsLatitudinal'] = numpy.int64\n typeMap['minGridPointLongitudinal'] = numpy.int64\n typeMap['minGridPointLatitudinal'] = numpy.int64\n\n #Real types\n typeMap['surfaceCurrentDepth'] = numpy.float64\n typeMap['gridOriginLongitude'] = numpy.float64\n typeMap['gridOriginLatitude'] = numpy.float64\n typeMap['gridSpacingLongitudinal'] = numpy.float64\n typeMap['gridSpacingLatitudinal'] = numpy.float64\n typeMap['gridLandMaskValue'] = numpy.float64\n typeMap['uncertaintyOfSpeed'] = numpy.float64\n typeMap['uncertaintyOfDirection'] = numpy.float64\n typeMap['uncertaintyOfHorzPosition'] = numpy.float64\n typeMap['uncertaintyOfVertPosition'] = numpy.float64\n typeMap['uncertaintyOfTime'] = numpy.float64\n typeMap['minSurfCurrentSpeed'] = numpy.float64\n typeMap['maxSurfCurrentSpeed'] = numpy.float64\n\n #String types\n typeMap['productSpecification'] = numpy.bytes_\n typeMap['dateTimeOfIssue'] = numpy.bytes_\n typeMap['nameRegion'] = numpy.bytes_\n typeMap['nameSubregion'] = numpy.bytes_\n typeMap['horizDatumReference'] = numpy.bytes_\n typeMap['protectionScheme'] = numpy.bytes_\n typeMap['dateTimeOfFirstRecord'] = numpy.bytes_\n typeMap['dateTimeOfLastRecord'] = numpy.bytes_ \n typeMap['methodCurrentsProduct'] = numpy.bytes_\n\n #Enumeration types\n typeMap['dataProtection'] = numpy.int64\n typeMap['typeOfCurrentData'] = numpy.int64\n typeMap['dataCodingFormat'] = numpy.int64\n typeMap['depthTypeIndex'] = numpy.int64\n\n #Removed?\n typeMap['nationalOriginator'] = numpy.bytes_\n typeMap['producingAgency'] = numpy.bytes_ \n typeMap['updateApplicationDate'] = numpy.bytes_\n typeMap['fileName'] = numpy.bytes_\n typeMap['dataType'] = numpy.bytes_\n typeMap['methodOrSource'] = numpy.bytes_\n typeMap['editionNumber'] = numpy.int64\n typeMap['updateNumber'] = numpy.int64 \n typeMap['numberOfNodes'] = numpy.int64\n \n #Removed in 1.09\n #typeMap['westBoundLongitude'] = numpy.float64\n #typeMap['eastBoundLongitude'] = numpy.float64\n #typeMap['southBoundLatitude'] = numpy.float64\n #typeMap['northBoundLatitude'] = numpy.float64\n\n if attribute_name not in typeMap:\n return None\n \n return typeMap[attribute_name]\n \n#******************************************************************************\ndef add_metadata(attributes, metadata_file):\n \"\"\" Add metadata values to the S-111 attributes.\n\n :param attributes: The S-111 attributes to be populated.\n :param metadata_file: The ASCII CSV file to retrieve the metadata values from.\n \"\"\"\n\n with open(metadata_file) as csvfile:\n reader = csv.reader(csvfile)\n \n #Grab the header and data rows.\n header = next(reader)\n data = next(reader)\n \n colnum = 0\n \n #For each column in the data row...\n for col in data:\n attribute_name = header[colnum].strip()\n attribute_value = col.strip().encode()\n attribute_type = get_metadata_type(attribute_name)\n \n #If we don't know what this attribute is, just report it to the user.\n if attribute_type == None:\n print(\"Warning: Unknown metadata value\", attribute_name)\n #Else if this is a string type...\n elif attribute_type == numpy.bytes_:\n attributes.create(attribute_name, attribute_value)\n #Else use the type returned.\n else:\n attributes.create(attribute_name, attribute_value, dtype=attribute_type)\n \n colnum += 1\n\n\n #We have a few pieces of metadata that may have been specified... but we want to ignore\n #They are computed attributes.\n clear_metadata_value(attributes, 'dateTimeOfFirstRecord')\n clear_metadata_value(attributes, 'dateTimeOfLastRecord')\n clear_metadata_value(attributes, 'numberOfStations')\n clear_metadata_value(attributes, 'numberOfTimes')\n clear_metadata_value(attributes, 'dataCodingFormat')\n clear_metadata_value(attributes, 'timeRecordInterval')\n clear_metadata_value(attributes, 'minSurfCurrentSpeed')\n clear_metadata_value(attributes, 'maxSurfCurrentSpeed')\n\n #Removed in 1.09\n #clear_metadata_value(attributes, 'westBoundLongitude')\n #clear_metadata_value(attributes, 'eastBoundLongitude')\n #clear_metadata_value(attributes, 'southBoundLatitude')\n #clear_metadata_value(attributes, 'northBoundLatitude')\n \n #Since this is a new file, we don't have any stations yet.\n attributes.create('numberOfStations', 0, dtype=numpy.int64)\n attributes.create('numberOfTimes', 0, dtype=numpy.int64)\n\n#****************************************************************************** \ndef create_dataset(output_file, metadata_file):\n \"\"\" Create a new S-111 dataset.\n\n :param output_file: The name of the file to be created.\n :param metadata_file: The ASCII CSV file to retrieve the metadata values from.\n \"\"\"\n\n #Make sure the output file has the correct extension.\n filename, file_extension = os.path.splitext(output_file)\n output_file_with_extension = filename + \".h5\"\n\n #Create the new HDF5 file.\n with h5py.File(output_file_with_extension, \"w\") as hdf_file:\n \n #Add the metadata to the file.\n add_metadata(hdf_file.attrs, metadata_file)\n \n#****************************************************************************** \ndef create_command_line():\n \"\"\"Create and initialize the command line parser.\n \n :returns: The command line parser.\n \"\"\"\n\n parser = argparse.ArgumentParser(description='Create S-111 File')\n\n parser.add_argument('-m', '--metadata-file', help='The text file containing the file metadata.', required=True)\n parser.add_argument(\"outputFile\", nargs=1)\n\n return parser\n\n#****************************************************************************** \ndef main():\n\n #Create the command line parser.\n parser = create_command_line()\n\n #Parse the command line.\n results = parser.parse_args()\n \n create_dataset(results.outputFile[0], results.metadata_file)\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/s111_create_file.py","file_name":"s111_create_file.py","file_ext":"py","file_size_in_byte":7514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"42686357","text":"import cv2,time\n\nface_cascade = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\") # create a CascadeClassofier object\n # path to the xml file which contains the face features\n\nvideo = cv2.VideoCapture(0) # method to create VideoCapture object. it will trigger the camera\n # '0' is to specify that use bulit-in camera\n # either give the path to the video file or use numbers.numbers specify that you will be using the erbcam to capture video\na = 1\n\nwhile True:\n\n a = a + 1\n check,frame = video.read() # frame -- it is a numpy array, it represents the first image that video captures\n # check -- it is bool data type, return true if python is able to read the VideoCapture object\n print(check)\n print(frame)\n\n gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)# convert each frame into a gray scale image\n \n faces = face_cascade.detectMultiScale(gray, 1.05,5) # method to search for the face rectangle co-ordinates\n # scaleFactor -- Decrease the shape value by 5%, until the face is found.smaller this value,the greater is the accuracy\n print(type(faces))\n print(faces)\n\n for x,y,w,h in faces:\n cv2.rectangle(gray,(x,y),(x+w,y+h),(0,255,0),3) # method to create the face rectangle \n\n\n cv2.imshow('Capturing',gray)\n\n key = cv2.waitKey(1) # this will generate a new frame after every 1 millseconds\n\n if key == ord('q'): # once you enter 'q' the window will be destroyed\n break\n\nprint(a)\n\nvideo.release() # this will release cmaera in some millisecond\n\ncv2.destroyAllWindows()\n\n","sub_path":"face_detection.py","file_name":"face_detection.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"609685493","text":"\"Short demo inspired by https://docs.fast.ai/callbacks.mixup.html\"\nfrom fastai.vision import *\nfrom manifold_mixup import *\n\n# gets the data\npath = untar_data(URLs.MNIST_SAMPLE)\ndata = ImageDataBunch.from_folder(path)\n\n# no mixup\nmodel = simple_cnn((3,16,16,2))\nlearn = Learner(data, model, metrics=[accuracy])\nlearn.fit(8)\nlearn.recorder.plot_losses()\n\n# input mixup\nmodel = simple_cnn((3,16,16,2))\nlearn = Learner(data, model, metrics=[accuracy]).mixup()\nlearn.fit(8)\nlearn.recorder.plot_losses()\n\n# manifold mixup\nmodel = simple_cnn((3,16,16,2))\nlearn = Learner(data, model, metrics=[accuracy]).manifold_mixup()\nlearn.fit(8)\nlearn.recorder.plot_losses()\n\n# output mixup\nmodel = simple_cnn((3,16,16,2))\nlearn = Learner(data, model, metrics=[accuracy]).output_mixup()\nlearn.fit(8)\nlearn.recorder.plot_losses()\n","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"123516634","text":"#%%\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Nov 14 13:21:10 2018\r\nUpdated on Nov 15\r\nLast Updated on Nov16\r\n\r\n@author: bcubrich\r\n\r\n\r\n\r\nSUMMARY\r\n--------------------------------\r\nThis code takes audit files for gaseous data and collects the audit and \r\nindicated measurements, then outputs a pipe delimited text file called\r\n 'QA_output.txt' that can be directly uploaded to AQS.\r\n\r\nINDEX\r\n-------------------------------\r\n1. Functions\r\n -functions to get filenames and directories \r\n\r\n2. Retrieve Data\r\n -Section of the code to get a list of startion parameter \r\n (State Code, County Code, Paramter Metho, Etc.) , and also to get the \r\n files that the user wishes to create an AQS import file for\r\n \r\n3. Create Output Dataframe\r\n -Take the data from the user input audit forms and convert it to a pandas\r\n data frame (df). This is done partly because of how I find and assign the level \r\n values, but also because a pandas dataframe can quickly and easily be written \r\n to a pipe ('|') delimited text file, which is use to to upload the data\r\n\r\n4. Write to file \r\n -Write the above df to a file\r\n\r\n5. Testing\r\n -Not used here. Was create to check if this script was working, but \r\n actually became useful for error checking data already in AQS \r\n\r\n6. Update AQS\r\n -If the above finds error in AQS then this will write and AQS update file\r\n that can fix some types of mistakes\r\n\r\n\r\n\r\n\"\"\"\r\n\r\n\r\n\r\n\r\n\r\nimport pandas as pd\r\nimport numpy as np #didn't even use numpy!!! HA!\r\n#import seaborn as sns\r\nfrom tkinter import Tk\r\nfrom tkinter.filedialog import askopenfilename\r\n#import matplotlib.pyplot as plt\r\nimport os\r\n#import xlrd\r\nimport wx\r\n\r\n'''---------------------------------------------------------------------------\r\n 1. Functions\r\n----------------------------------------------------------------------------'''\r\n\r\n#The following functions are just used to get filepaths\r\n#I usually just run it once to get the path, and then leave this \r\n#fucntion so that I can get othe rpaths if needed\r\ndef get_dat():\r\n root = Tk()\r\n root.withdraw()\r\n root.focus_force()\r\n root.attributes(\"-topmost\", True) #makes the dialog appear on top\r\n filename = askopenfilename() # Open single file\r\n \r\n return filename\r\n\r\n#Thanks Kristy Weber 11/15/18 for giving me these functions to specify directories\r\ndef audit_path():\r\n app = wx.App()\r\n \r\n frame = wx.Frame(None, -1, 'win.py')\r\n frame.SetSize(0,0,200,50)\r\n \r\n # Create open file dialog\r\n openFileDialog = wx.DirDialog(frame, \"Choose directory with audit data\", \"\",\r\n wx.DD_DEFAULT_STYLE | wx.DD_DIR_MUST_EXIST)\r\n \r\n openFileDialog.ShowModal()\r\n print(openFileDialog.GetPath())\r\n \r\n # outfile_path is the string with the path name saved as a variable\r\n path = openFileDialog.GetPath()#+'\\\\'\r\n openFileDialog.Destroy()\r\n \r\n del app\r\n return path\r\n\r\n\r\ndef get_outpath():\r\n #function to get output path of file\r\n app = wx.App()\r\n \r\n frame = wx.Frame(None, -1, 'win.py')\r\n frame.SetSize(0,0,200,50)\r\n \r\n # Create open file dialog\r\n openFileDialog = wx.DirDialog(frame, \"Choose output file directory\", \"\",\r\n wx.DD_DEFAULT_STYLE | wx.DD_DIR_MUST_EXIST)\r\n \r\n openFileDialog.ShowModal()\r\n print(openFileDialog.GetPath())\r\n \r\n # outfile_path is the string with the path name saved as a variable\r\n out_path = openFileDialog.GetPath()\r\n openFileDialog.Destroy()\r\n \r\n del app\r\n \r\n return out_path\r\n\r\n'''---------------------------------------------------------------------------\r\n 2. Retrieve Data\r\n---------------------------------------------------------------------------'''\r\n\r\n\r\nsites=r'U:/PLAN/BCUBRICH/Python/Parameter Reader/'\\\r\nr'PARAMETERS.xls'\r\n\r\nsites_df=pd.read_excel(sites, converters={'SITE NAME':str,'State Code':str,\r\n 'County Code':str, 'Site Code':str,\r\n 'Paramter':str, 'Analyt':str, \r\n 'Method':str, 'Unit':str}) # load data\r\nsites_df['Analyt']=sites_df['Analyt'].str.strip('()') #strip parentheses from \r\n\r\n#This is the original path for when I wrote the code\r\n#directory='U:/PLAN/BCUBRICH/Python/Parameter Reader/tests'\r\n\r\n#get the path where the data are stored\r\ndirectory=audit_path()\r\n\r\n#I copied these columns right out of a pipe delimeted text file, and just \r\n#pasted them here. Need to load this as a big text string here\r\ncolumns_raw=r'Transaction Type|Action Indicator|Assessment Type|Performing '\\\r\n r'Agency|State Code / Tribal Indicator|County Code / Tribal Code|Site '\\\r\n r'Number|Parameter Code|POC|Assessment Date|Assessment Number|Monitor '\\\r\n r'Method Code|Reported Unit|Level 1 Monitor Concentration|Level 1 '\\\r\n r'Assessment Concentration|Level 2 Monitor Concentration|Level 2 '\\\r\n r'Assessment Concentration|Level 3 Monitor Concentration|Level 3 '\\\r\n r'Assessment Concentration|Level 4 Monitor Concentration|Level 4 '\\\r\n r'Assessment Concentration|Level 5 Monitor Concentration|Level 5 '\\\r\n r'Assessment Concentration|Level 6 Monitor Concentration|Level 6 '\\\r\n r'Assessment Concentration|Level 7 Monitor Concentration|Level 7 '\\\r\n r'Assessment Concentration|Level 8 Monitor Concentration|Level 8 '\\\r\n r'Assessment Concentration|Level 9 Monitor Concentration|Level 9 '\\\r\n r'Assessment Concentration|Level 10 Monitor Concentration|Level '\\\r\n r'10 Assessment Concentration'\r\n\r\n#Then break it into column headers here\r\ncolumns=columns_raw.split('|')\r\n\r\n#Next, create empty df. This is very important. In order to upload the output file\r\n#when everything is done we need to make sure there are a specific number of \r\n#pipes. The easiest way I can see to do that is to create a df with the right\r\n#number of columns, then fill only those columns. When the df is written to a \r\n#csv we can just specify '|' as the sep, and it will put in pipes for each of\r\n#of the empty rows.\r\noutput_df=pd.DataFrame(columns=columns) \r\n\r\ncount=0 #just want to be able to check if we looped all the files\r\n\r\n\r\n'''---------------------------------------------------------------------------\r\n 3. Create Output Dataframe\r\n \r\nThis section focuses on the pandas df 'output_df'. I use this df to store up\r\nall the info needed for an AQS upload that can be easily saved to a pipe \r\ndelimited csv.\r\n----------------------------------------------------------------------------'''\r\n\r\n\r\nfor filename in os.listdir(directory): #loop through files in user's dir\r\n if filename.endswith(\".xls\") or filename.endswith(\".xlsx\"):\r\n# print(filename) #this is useful for double checking the files are read\r\n \r\n file=filename.split('/')[-1][:-4] #Get the filename minus the extension\r\n site_name=file[:2] #Get sitename from filename\r\n if site_name=='OG' : site_name='O2' #OG is an old site, it's now called O2\r\n if site_name=='HA' : site_name='HW' #double naming...\r\n \r\n analyt=file.split()[2] #Find out what was being measured from filename\r\n #Sometime people use the following interchangeably, but we only want the NO2 instrument name\r\n if analyt.upper() == 'NOX' or analyt.upper() == 'NO' : analyt = 'NO2'\r\n \r\n #next line gets the info about the insturment and site from the Paramters... list\r\n loc_deets=sites_df[(sites_df['Site Symbol']==site_name)&\\\r\n (sites_df['Analyt'].str.contains\\\r\n (analyt.upper()))].reset_index()\r\n \r\n #fill in the parts of the df that will be the same for every entry\r\n output_df.loc[count,'Transaction Type']='QA'\r\n output_df.loc[count,'Action Indicator']='I'\r\n output_df.loc[count,'Assessment Type']='Annual PE'\r\n output_df.loc[count,'Performing Agency']='1113'\r\n output_df.loc[count,'State Code / Tribal Indicator']='49'\r\n \r\n #need to change the date from the format in the filename to the AQS format\r\n date=file.split()[1] #get date from filename\r\n date_split=date.split('-') #split on'-'\r\n date_fmt=date_split[2]+date_split[0]+date_split[1] #rearrange\r\n \r\n \r\n if len(loc_deets)>=1: #this if prevents some errors when there wasn't a match\r\n if len(loc_deets)==2: loc_deets=loc_deets[loc_deets['POC']=='1']\r\n #This section saves all the information about the site to the out_put \r\n #df in the AQS format.\r\n output_df.loc[count,'County Code / Tribal Code']=loc_deets.loc[0,'County Code']\r\n output_df.loc[count,'Site Number']=loc_deets.loc[0,'Site Code']\r\n output_df.loc[count,'Parameter Code']=int(loc_deets.loc[0,'Parameter'])\r\n output_df.loc[count,'POC']=loc_deets.loc[0,'POC']\r\n output_df.loc[count,'Assessment Date']=date_fmt\r\n output_df.loc[count,'Assessment Number']=1\r\n output_df.loc[count,'Monitor Method Code']=loc_deets.loc[0,'Method']\r\n output_df.loc[count,'Reported Unit']=loc_deets.loc[0,'Unit']\r\n \r\n \r\n #for NO2, NOx\r\n skiprows=31\r\n n_rows=9\r\n usecols=[1,8,9]\r\n \r\n #need some if's here because the different excel spreadsheets\r\n #have data in different places. These if's just specify where the\r\n #data is saved in the excel file.\r\n if analyt == 'O3':\r\n skiprows=24\r\n n_rows=5\r\n usecols=[1,3,5]\r\n if analyt == 'SO2':\r\n skiprows=21\r\n n_rows=4\r\n usecols=[1,3,4]\r\n if analyt == 'CO':\r\n skiprows=21\r\n n_rows=4\r\n usecols=[2,4,5]\r\n \r\n #Read in the audit workbook\r\n wb=pd.read_excel((directory+'/'+filename), skiprows =skiprows, \r\n n_rows=n_rows, usecols=usecols, \r\n names=['Audit Level', 'Audit', 'Indicated'])\r\n \r\n #There are two forms of ozone workbooks, so we need some if's\r\n #here to make sure that we get the right one. This works by \r\n #looking to see if there are any levels entries in the the first wb\r\n if analyt == 'O3' and wb['Audit Level'].isna().sum()>=7:\r\n# print('HERE!!!!') #just to help debug where the old )3 forms were used\r\n skiprows=24\r\n n_rows=5\r\n usecols=[2,4,6]\r\n wb=pd.read_excel((directory+'/'+filename), skiprows =skiprows, \r\n n_rows=n_rows, usecols=usecols, \r\n names=['Audit Level', 'Audit', 'Indicated'])\r\n \r\n no_match=0\r\n #need this if because you get some errors if the wb df is empty.\r\n #There are several reasons this might happen, so if you do get not\r\n #matches it requires some debugging. The most likely cause is a \r\n #non standardized form.\r\n if wb.empty==True:\r\n no_match+=1\r\n# print('Non match '+str(int(no_match))+' = ' +filename)\r\n else:\r\n #get rid of rows where there was no Level or Indicated value reported\r\n wb=wb.dropna(subset = ['Indicated', 'Audit Level'])\r\n wb=wb.set_index('Audit Level')\r\n \r\n \r\n for level in wb.index:\r\n level = int(level)\r\n# print (level) #for debug\r\n #these next lines are where the magic happens. I find the\r\n #levels contained in the audit file, then concat a string\r\n #with the column name in the output_df that corresponds \r\n #to the level. By writing there, it makes sure that the\r\n #correct number of pipes will be included in the AQS file.\r\n col_name='Level '+str(level)+' Assessment Concentration'\r\n output_df.loc[count,col_name]=wb.loc[level, 'Audit']\r\n col_name='Level '+str(level)+' Monitor Concentration'\r\n output_df.loc[count,col_name]=wb.loc[level, 'Indicated']\r\n \r\n else:\r\n print ('No site location matched')\r\n count+=1\r\n continue\r\n else:\r\n continue\r\n\r\n\r\n\r\n\r\n'''----------------------------------------------------------------------------\r\n 4. Write to file\r\n---------------------------------------------------------------------------'''\r\n\r\n\r\n\r\nout_path = get_outpath() #get user selected output path\r\n\r\n\r\noutput_df=output_df.set_index('Transaction Type') #need to get rid of index\r\noutput_df.to_csv(out_path+'\\QA_output.txt', sep='|') #write to pipe file\r\n\r\n\r\n'''---------\r\nThe following whole bit is used to add a '#' to the first line of the file. \r\nSeems like a lot of code just to add a hashtag to the file, but I like having \r\nthe header info right in the file, in case someone only sees the text file.\r\n------'''\r\nappendText='#'\r\ntext_file=open(out_path+'\\QA_output.txt','r')\r\ntext=text_file.read()\r\ntext_file.close()\r\ntext_file=open(out_path+'\\QA_output.txt','w')\r\ntext_file.seek(0,0)\r\ntext_file.write(appendText+text)\r\ntext_file.close()\r\n\r\n#%%\r\n\r\n'''--------------------------------------------------------------------------\r\n 5. Testing\r\n \r\n-This whole part of the script is used to check if previously uploaded data\r\non AQS is accurate. It requires a file called 'verify', which is a pipe-\r\ndelimited output file from AQS of the Audit data over a given period.\r\nThe error checking is not exactly straight forward. \r\n---------------------------------------------------------------------------'''\r\ntesting=False #set to true if you want to do some testing\r\nif testing==True:\r\n output_file=open('U:/PLAN/BCUBRICH/Python/Parameter Reader/QA_output.txt','r')\r\n out=output_file.read()\r\n out_lines=out.split('\\n')\r\n verify_file=open('U:/PLAN/BCUBRICH/Python/Parameter Reader/verify.txt','r')\r\n vers=verify_file.read()\r\n vers_lines=vers.split('\\n')\r\n print(len(out_lines))\r\n match=0\r\n count_err=0\r\n count_err2=0\r\n conv_cols=r'Level 1 Monitor Concentration|Level 1 '\\\r\n r'Assessment Concentration|Level 2 Monitor Concentration|Level 2 '\\\r\n r'Assessment Concentration|Level 3 Monitor Concentration|Level 3 '\\\r\n r'Assessment Concentration|Level 4 Monitor Concentration|Level 4 '\\\r\n r'Assessment Concentration|Level 5 Monitor Concentration|Level 5 '\\\r\n r'Assessment Concentration|Level 6 Monitor Concentration|Level 6 '\\\r\n r'Assessment Concentration|Level 7 Monitor Concentration|Level 7 '\\\r\n r'Assessment Concentration|Level 8 Monitor Concentration|Level 8 '\\\r\n r'Assessment Concentration|Level 9 Monitor Concentration|Level 9 '\\\r\n r'Assessment Concentration|Level 10 Monitor Concentration|Level '\\\r\n r'10 Assessment Concentration'\r\n \r\n conv_cols=conv_cols.split('|')\r\n conv_dict=dict()\r\n missed=[]\r\n \r\n def unq(seq):\r\n # Not order preserving \r\n Set = set(seq)\r\n return list(Set)\r\n \r\n for item in conv_cols:\r\n conv_dict[item]=float\r\n \r\n \r\n for line1 in out_lines:\r\n for line2 in vers_lines:\r\n if line1==line2:\r\n match+=1\r\n else:\r\n \r\n if line1[:38]==line2[:38]:\r\n \r\n df_check_temp=pd.DataFrame([line1.split('|'), line2.split('|')], columns=columns)\r\n df_check_temp[conv_cols]=df_check_temp[conv_cols].apply(pd.to_numeric)\r\n \r\n if count_err==0:\r\n df_check=df_check_temp.copy()\r\n else:\r\n df_check=df_check.append(df_check_temp)\r\n \r\n count_err+=1\r\n \r\n for line1 in out_lines:\r\n if line1 in vers_lines:\r\n something=1\r\n else:\r\n if line1[:38] in vers_lines:\r\n something=1\r\n else:\r\n print(line1)\r\n \r\n \r\n before=len(df_check)\r\n df_check=df_check.drop_duplicates(keep=False)\r\n after=len(df_check)\r\n match=match+(before-after)/2\r\n match+=5\r\n print(match)\r\n \r\n\r\n'''----------------------------------------------------------------------------\r\n 6. Update AQS\r\n \r\nYou can create an update file from the found errors in the above\r\ntesting section here. These can be directly uploaded to \r\n----------------------------------------------------------------------------'''\r\nupdate=False #change this if you want to run this.\r\nif update==True:\r\n df_update=df_check.loc[0,:].set_index('Transaction Type')\r\n df_update['Action Indicator']='U'\r\n df_update.to_csv('U:/PLAN/BCUBRICH/Python/Parameter Reader/QA_update.txt', sep='|') \r\n \r\n '''This whole bit is used to add a '#' to the first line of the file'''\r\n appendText='#'\r\n text_file=open('U:/PLAN/BCUBRICH/Python/Parameter Reader/QA_update.txt','r')\r\n text=text_file.read()\r\n text_file.close()\r\n text_file=open('U:/PLAN/BCUBRICH/Python/Parameter Reader/QA_update.txt','w')\r\n text_file.seek(0,0)\r\n text_file.write(appendText+text)\r\n text_file.close()\r\n","sub_path":"APE_to_AQS_GASEOUS_0.0.1.py","file_name":"APE_to_AQS_GASEOUS_0.0.1.py","file_ext":"py","file_size_in_byte":17905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"243219032","text":"\"\"\"To run the tests, you will need to move test documents into the pdf-to-png\ndirectory. The tests require a single page PDF named test_singlepage.pdf, a\nmulti-page PDF named test_multipage.pdf, and a JPG named test_nonpdf.jpg.\"\"\"\n\nfrom unittest import TestCase\nfrom server import app\nfrom io import FileIO\n\n\nclass FlaskTestsServer(TestCase):\n \"\"\"Flask unit tests for server routes.\"\"\"\n\n def setUp(self):\n \"\"\"Set up test client before each test.\"\"\"\n\n self.client = app.test_client()\n app.config[\"TESTING\"] = True\n app.config[\"SECRET_KEY\"] = \"key\"\n\n def test_no_file(self):\n \"\"\"Test /upload-pdf route with no file submitted.\"\"\"\n\n result = self.client.post(\"/upload-pdf\")\n\n self.assertIn(\"No file submitted\", result.data)\n\n def test_single_page_pdf(self):\n \"\"\"Test /upload-pdf route for single page pdf.\"\"\"\n\n data = {\"file\": FileIO(\"test_singlepage.pdf\")}\n result = self.client.post(\"/upload-pdf\",\n content_type=\"multipart/form-data\",\n data=data)\n\n self.assertIn(\"/uploads/test_singlepage.png\", result.data)\n\n def test_multipage_pdf(self):\n \"\"\"Test /upload-pdf route for multi page pdf.\"\"\"\n\n data = {\"file\": FileIO(\"test_multipage.pdf\")}\n result = self.client.post(\"/upload-pdf\",\n content_type=\"multipart/form-data\",\n data=data)\n\n self.assertIn(\"/uploads/test_multipage-1.png\", result.data)\n\n def test_wrong_file_type(self):\n \"\"\"Test /upload-pdf route for non-pdf file upload.\"\"\"\n\n data = {\"file\": FileIO(\"test_nonpdf.jpg\")}\n result = self.client.post(\"/upload-pdf\",\n content_type=\"multipart/form-data\",\n data=data)\n\n self.assertIn(\"/upload-pdf route accepts only PDF file format.\",\n result.data)\n\n\nif __name__ == \"__main__\":\n import unittest\n\n unittest.main()\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"445883050","text":"import cv2, numpy as np\n\nimg = cv2.imread(\"images/IMG_20180331_180458.jpg\")\n\nimg_y_cr_cb = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)\ny, cr, cb = cv2.split(img_y_cr_cb)\n\n# Applying equalize Hist operation on Y channel.\ny_eq = cv2.equalizeHist(y)\n\nimg_y_cr_cb_eq = cv2.merge((y_eq, cr, cb))\nimg_rgb_eq = cv2.cvtColor(img_y_cr_cb_eq, cv2.COLOR_YCR_CB2BGR)\n\ncv2.imshow('original', img)\ncv2.imshow('equalized',img_rgb_eq)\ncv2.waitKey(0)\n\n# equ = cv2.equalizeHist(img)\n\n# #Contrast liomited adaptive histogram equalization\n# clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))\n# cl1 = clahe.apply(img)\n\n# res = np.hstack((img,cl1)) #stacking images side-by-side\n\n# cv2.imshow('res', res)\n# cv2.waitKey(0)","sub_path":"pre-processing/image_eqhist.py","file_name":"image_eqhist.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"275131933","text":"from joblib import load\nimport pandas as pd\nimport numpy as np\n\ndef featureCorrection(result):\n\n frame = pd.read_csv(\"Outlier_removed.csv\")\n frame = frame.drop('Price', axis=1)\n\n result['Journey_month'] = result['Departure_Date'].split('-')[1]\n result['Journey_day'] = result['Departure_Date'].split('-')[2]\n result.pop('submit')\n result.pop('Departure_Date')\n\n frame = frame.append(result, ignore_index=True)\n\n frame[['Journey_day', 'Journey_month']] = frame[['Journey_day', 'Journey_month']].astype('int64')\n frame['Total_Duration'] = frame['Total_Duration'].astype('float64')\n\n frame = pd.get_dummies(frame, drop_first=True)\n scaler = load(\"FeatureScaler.pkl\")\n result = frame.iloc[-1].values\n result = scaler.transform(np.reshape(result, (1, -1)))\n\n return result\n","sub_path":"featureSetting.py","file_name":"featureSetting.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"275887518","text":"\n\n#calss header\nclass _SCRAP():\n\tdef __init__(self,): \n\t\tself.name = \"SCRAP\"\n\t\tself.definitions = [u'to not continue with a system or plan: ', u'to get rid of something that is no longer useful or wanted, often using its parts in new ways: ', u'to have a fight or an argument']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_scrap.py","file_name":"_scrap.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"464387151","text":"\"\"\"\nSuperModule for high level training on Pytorch models\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\nimport math\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\n\n# local imports\nfrom ..datasets import TensorDataset\nfrom ..callbacks import CallbackModule, History, TQDM\nfrom ..constraints import ConstraintModule\nfrom ..regularizers import RegularizerModule\n\n\nclass SuperModule(nn.Module):\n\n def __init__(self, \n plot=False, \n module=None, \n use_gpu=torch.cuda.is_available()):\n \"\"\"\n SuperModule for high-level training of Pytorch models\n\n TODO:\n - allow metrics\n - e.g. for validation accuracy instead of loss\n \"\"\"\n super(SuperModule, self).__init__()\n \n self.plot = plot\n self._module = module\n self._use_gpu = use_gpu\n\n self.history = History()\n self._callbacks = [self.history]\n self._constraints = []\n self._regularizers = []\n self.stop_training = False\n\n def forward(self, *input):\n \"\"\"\n Defines the computation performed at every call.\n Should be overriden by all subclasses.\n \"\"\"\n if self._module:\n return self._module(*input)\n else:\n raise NotImplementedError('Must wrap existing module OR \\\n subclass must implement this method')\n\n def set_loss(self, loss):\n self._loss = loss\n\n def set_optimizer(self, optimizer, **kwargs):\n if 'parameters' in kwargs:\n parameters = kwargs['parameters']\n else:\n parameters = self.parameters()\n self._optimizer = optimizer(parameters, **kwargs)\n\n def set_regularizers(self, regularizers):\n self._regularizers = regularizers\n\n def set_constraints(self, constraints):\n self._constraints = constraints\n\n def set_callbacks(self, callbacks):\n self._callbacks += callbacks\n\n def fit(self,\n x, \n y,\n validation_data=None, \n nb_epoch=100, \n batch_size=32,\n cuda_device=None,\n verbose=1):\n \"\"\"\n Fit a model on torch tensors\n \"\"\"\n train_dataset = TensorDataset(x, y)\n train_loader = DataLoader(train_dataset, batch_size=batch_size)\n if validation_data is not None:\n test_dataset = TensorDataset(validation_data[0], validation_data[1])\n val_loader = DataLoader(test_dataset, batch_size=batch_size)\n else:\n val_loader = None\n self.fit_loader(loader=train_loader, val_loader=val_loader,\n nb_epoch=nb_epoch, cuda_device=cuda_device,\n verbose=verbose)\n\n def fit_on_batch(self, \n x, \n y, \n cuda_device=None):\n inputs = Variable(x)\n targets = Variable(y)\n if cuda_device is not None:\n inputs = inputs.cuda(cuda_device)\n targets = targets.cuda(cuda_device)\n\n # zero the gradients\n self._optimizer.zero_grad()\n # make forward pass\n outputs = self(inputs)\n # compute model loss\n loss = self._loss(outputs, targets)\n reg_loss = self._regularizers.compute_loss()\n total_loss = loss + reg_loss\n # make backward pass\n total_loss.backward()\n # make optimizer step to update weights\n self._optimizer.step()\n\n def fit_loader(self, \n loader, \n val_loader=None, \n nb_epoch=100,\n cuda_device=None,\n verbose=1):\n \"\"\"\n Fit a model on a DataLoader\n \"\"\"\n ## create regularizers\n if len(self._regularizers) > 0:\n regularizers = RegularizerModule(self._regularizers)\n regularizers.set_model(self)\n else:\n regularizers = None\n\n ## create constraints\n constraints = ConstraintModule(self._constraints)\n constraints.set_model(self)\n\n ## create callbacks\n if verbose > 0:\n self._callbacks += [TQDM()]\n callbacks = CallbackModule(self._callbacks)\n callbacks.set_model(self)\n\n callbacks.on_train_begin()\n\n for epoch_idx in range(nb_epoch):\n epoch_logs = {\n 'nb_batches': int(math.ceil(len(loader.dataset.inputs)/loader.batch_size)),\n 'nb_epoch': nb_epoch\n }\n callbacks.on_epoch_begin(epoch_idx, epoch_logs)\n\n for batch_idx,(x_batch, y_batch) in enumerate(loader):\n batch_logs = {\n 'batch_idx': batch_idx,\n 'batch_samples': len(x_batch)\n } \n callbacks.on_batch_begin(batch_idx, batch_logs)\n\n inputs = Variable(x_batch)\n targets = Variable(y_batch)\n if cuda_device is not None:\n inputs = inputs.cuda(cuda_device)\n targets = targets.cuda(cuda_device)\n\n\n self._optimizer.zero_grad()\n outputs = self(inputs)\n loss = self._loss(outputs, targets)\n \n if regularizers is not None:\n reg_loss = regularizers.compute_loss()\n loss += reg_loss\n batch_logs['reg_loss'] = reg_loss\n batch_logs['loss'] = loss.data[0]\n\n # make backward pass\n loss.backward()\n # make optimizer step to update weights\n self._optimizer.step()\n\n callbacks.on_batch_end(batch_idx, batch_logs)\n constraints.on_batch_end(batch_idx)\n\n if val_loader is not None:\n val_loss = self.evaluate_loader(val_loader, \n cuda_device=cuda_device)\n epoch_logs['val_loss'] = val_loss\n epoch_logs['loss'] = self.history.loss / self.history.samples_seen\n if regularizers is not None:\n epoch_logs['reg_loss'] = self.history.reg_loss / self.history.samples_seen\n\n callbacks.on_epoch_end(epoch_idx, epoch_logs)\n constraints.on_epoch_end(epoch_idx)\n if self.stop_training:\n break\n\n callbacks.on_train_end()\n\n def predict(self, \n x, \n batch_size=32,\n cuda_device=None, \n verbose=1):\n dataset = TensorDataset(x)\n loader = DataLoader(dataset, batch_size=batch_size)\n preds = self.predict_loader(loader, \n cuda_device=cuda_device,\n verbose=verbose)\n return preds\n\n def predict_loader(self,\n loader,\n cuda_device=None,\n verbose=1):\n self.eval()\n preds = []\n for batch_idx, batch in enumerate(loader):\n if loader.dataset.has_target:\n batch = batch[0]\n x_batch = Variable(batch)\n if cuda_device is not None:\n x_batch = x_batch.cuda(cuda_device)\n batch_pred = self(x_batch)\n preds.append(batch_pred.data)\n self.train()\n return Variable(torch.cat(preds))\n\n def predict_on_batch(self, \n x, \n cuda_device=None):\n self.eval()\n x = Variable(x)\n if cuda_device is not None:\n x = x.cuda(cuda_device)\n preds = self(x)\n self.train()\n return preds\n\n def evaluate(self, \n x, \n y, \n batch_size=32,\n cuda_device=None, \n verbose=1):\n dataset = TensorDataset(x,y)\n loader = DataLoader(dataset, batch_size=batch_size)\n loss = self.evaluate_loader(loader, \n cuda_device=cuda_device)\n return loss\n\n def evaluate_loader(self, \n loader, \n cuda_device=None):\n self.eval()\n total_loss = 0.\n total_samples = 0.\n for batch_idx, (x_batch, y_batch) in enumerate(loader):\n x_batch = Variable(x_batch)\n y_batch = Variable(y_batch)\n if cuda_device is not None:\n x_batch = x_batch.cuda(cuda_device)\n y_batch = y_batch.cuda(cuda_device)\n\n y_pred = self(x_batch)\n loss = self._loss(y_pred, y_batch)\n total_loss += loss.data[0]*len(x_batch)\n total_samples += len(x_batch)\n self.train()\n return total_loss / total_samples\n\n def evaluate_on_batch(self, \n x, \n y, \n cuda_device=None):\n self.eval()\n x = Variable(x)\n y = Variable(y)\n if cuda_device is not None:\n x = x.cuda(cuda_device)\n y = y.cuda(cuda_device)\n y_pred = self(y)\n loss = self._loss(y_pred, y)\n self.train()\n return loss.data[0]\n\n def save_state_dict(self, file):\n \"\"\"\n Save a model parameters to disk\n \"\"\"\n # model parameters -> ordered dict\n state_dict = self.state_dict()\n torch.save(state_dict, file)\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"torchsample/modules/super_module.py","file_name":"super_module.py","file_ext":"py","file_size_in_byte":9528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"473250643","text":"import os\nimport json\nfrom pathlib import Path\nfrom subprocess import PIPE, Popen\nfrom enum import Enum\n\n\nclass KomodoType(Enum):\n UNKNOWN = 0 # Probably a test\n REAL = 1\n SHIM = 2\n VENV = 3\n\n\nclass Context(object):\n def __init__(self, srcpath, dstpath=None):\n self.srcpath = Path(srcpath)\n self.dstpath = dstpath\n self.dry_run = False\n\n bin_python = self.srcpath / \"root\" / \"bin\" / \"python\"\n if not bin_python.exists():\n # Probably constructed in a test. Ignore this until sometime later\n # in the process when we will inevitably fail.\n self.type = KomodoType.UNKNOWN\n return\n\n # Get python version_info\n script = b\"import sys,json;print(json.dumps(sys.version_info[:]))\"\n env = {\"LD_LIBRARY_PATH\": \"{0}/lib:{0}/lib64\".format(self.srcpath / \"root\")}\n self.version_info = json.loads(self.invoke_srcpython(script=script, env=env))\n\n # Get python sys.path\n script = b\"import sys,json;print(json.dumps(sys.path))\"\n env = {\"LD_LIBRARY_PATH\": \"{0}/lib:{0}/lib64\".format(self.srcpath / \"root\")}\n self.src_python_paths = json.loads(\n self.invoke_srcpython(script=script, env=env)\n )\n\n # Existence of libexec suggests that this is a libexec-shim komodo release\n libexec_python = self.srcpath / \"root\" / \"libexec\" / \"python\"\n if libexec_python.exists():\n self.type = KomodoType.SHIM\n return\n\n # Existence of any libpythons suggests that this is a normal Python\n # install (compiled from sources)\n for libdir in \"lib\", \"lib64\":\n for suffix in \"\", \"m\", \"dm\":\n name = \"libpython{}.{}{}.so\".format(\n self.version_info[0], self.version_info[1], suffix\n )\n\n if (self.srcpath / \"root\" / libdir / name).exists():\n self.type = KomodoType.REAL\n return\n\n # Otherwise this is most likely a virtualenv\n self.type = KomodoType.VENV\n\n def invoke_srcpython(self, args=None, env=None, script=None):\n pyexec = self.srcpath / \"root\" / \"bin\" / \"python\"\n return self.invoke_python(pyexec, args, env, script)\n\n def invoke_dstpython(self, args=None, env=None, script=None):\n pyexec = self.dstpath / \"root\" / \"bin\" / \"python\"\n return self.invoke_python(pyexec, args, env, script)\n\n def invoke_python(self, python_executable, args=None, env=None, script=None):\n if args is None:\n args = []\n if env is None:\n env = {}\n if script is not None:\n # Prepend '-' to tell Python to read from stdin\n args = [\"-\"] + args\n\n python_executable = Path(python_executable)\n\n env[\"PATH\"] = \"{}:{}\".format(\n python_executable.parent.absolute(), os.environ[\"PATH\"]\n )\n env[\"LD_LIBRARY_PATH\"] = \"{0}/lib:{0}/lib64\".format(str(self.srcpath / \"root\"))\n\n args = [python_executable] + args\n proc = Popen(map(str, args), stdin=PIPE, stdout=PIPE, env=env)\n stdout, _ = proc.communicate(script)\n\n return stdout\n\n @property\n def src_python_path(self):\n return self.srcpath / \"root\" / \"bin\" / \"python\"\n\n @property\n def dst_python_libpath(self):\n libdir = \"python{}.{}\".format(self.version_info[0], self.version_info[1])\n return self.dstpath / \"root\" / \"lib\" / libdir\n","sub_path":"komodoenv/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":3466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"386650695","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 24 11:22:15 2018\n\n@author: melisandezonta\n\"\"\"\n\n\nimport os\nimport cv2\nfrom matplotlib import pyplot as plt\nfrom Functions import *\nimport numpy as np\n\n\nos.chdir(\"/Users/melisandezonta/Documents/Documents/GTL_courses_second_semester/Computer-Vision/PS1-all/PS1-images/\")\n\n\n# Load noisy image\nimg_noisy = cv2.imread(\"ps1-input1.jpg\")\nimg_noisy_gray = cv2.cvtColor(img_noisy, cv2.COLOR_BGR2GRAY)\n\n\n# Gaussian smoothing\n\nimage_noisy_smoothed = cv2.GaussianBlur(img_noisy_gray, (3,3), 5)\n\n# Gradient Calculation\n\ngxx=cv2.Sobel(image_noisy_smoothed,cv2.CV_32FC1,1,0);\ngyy=cv2.Sobel(image_noisy_smoothed,cv2.CV_32FC1,0,1);\ntheta_test=cv2.phase(gxx,gyy,angleInDegrees=True);\n\n\n\n# Apply the Canny edge detector on the smoothed noisy image\n\nedges_noisy_smoothed_image = cv2.Canny(image_noisy_smoothed, 60, 100)\n\n\n# Calculation of the accumulator\n\n[rows, cols] = edges_noisy_smoothed_image.shape\nr_min = 20\nr_max = 30\na_min = floor(1 - r_max)\na_max = floor(rows + r_max)\nb_min = floor(1 - r_max)\nb_max = floor(cols + r_max)\na_len = a_max - a_min\nb_len = b_max - b_min\nH = Hough_Circles(edges_noisy_smoothed_image, r_min, r_max,1, a_min, a_max, b_min, b_max, a_len, b_len,theta_test)\n\n# Search for the maximums\n\nthreshold = 0.45\nmax_points = find_max(H,threshold)\nnumber_max_points = len(max_points[1])\nprint('the number of max_points is :', number_max_points)\n\n# Move back in the polar domain\n\n[rows, cols] = edges_noisy_smoothed_image.shape\nr_len = r_max -r_min\nr_hough = []\na_hough = []\nb_hough = []\ndistance = 5\nfor i in range(0,number_max_points):\n a_hough.append(int(round(a_min + max_points[0][i] * (a_max - a_min) / a_len)))\n b_hough.append(int(round(b_min + max_points[1][i] * (b_max - b_min) / b_len)))\n r_hough.append(int(round(r_min + max_points[2][i] * (r_max - r_min) / r_len)))\na_new_hough, b_new_hough, r_new_hough = filter_circles(a_hough,b_hough,r_hough,40.0)\ncircles = zip(a_new_hough,b_new_hough,r_new_hough)\n\n# Draw the circles on the image\n\nimg_circles = cv2.cvtColor(image_noisy_smoothed, cv2.COLOR_GRAY2BGR)\nfor a,b,r in circles:\n cv2.circle(img_circles, (a, b), r, (0,255,127), 2)\n\n# Diverse plots\n\nplt.subplot(2,2,1)\nplt.imshow(image_noisy_smoothed, cmap='gray')\nplt.draw()\ncv2.imwrite(\"ps1-5-image-noisy-smoothed.png\", image_noisy_smoothed)\n\n\nplt.subplot(2,2,2)\nplt.imshow(edges_noisy_smoothed_image, cmap='gray')\nplt.draw()\ncv2.imwrite(\"ps1-5-edges-image-noisy.png\", edges_noisy_smoothed_image)\n\nplt.subplot(2,2,3)\nplt.imshow(cv2.cvtColor(img_circles, cv2.COLOR_BGR2RGB))\nplt.draw()\ncv2.imwrite(\"ps1-5-circles.png\", img_circles)\n\nplt.show()\n","sub_path":"PS1-all/PS1-code/ps1-5.py","file_name":"ps1-5.py","file_ext":"py","file_size_in_byte":2642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"258818105","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom PySide import QtGui, QtCore\nimport sys\nimport windows\nimport runScripts\nfrom vars import * \n\n\n\nclass MainWindow(QtGui.QMainWindow):\n\n def __init__(self, titile, pos_x, pos_y, \\\n width=DEFAULT_M_WINDOW_WIDTH, hight=DEFAULT_M_WINDOW_HIGHT):\n super(MainWindow, self).__init__()\n\n self.__title = titile\n self.__pos_x = pos_x\n self.__pos_y = pos_y\n self.__width = width\n self.__hight = hight\n\n self.__editConfWindow = None\n self.__netSettingsWindow = None\n \n self.initUI()\n self.createMenu()\n\n\n def initUI(self):\n self.setGeometry(\n self.__pos_x, \n self.__pos_y, \n self.__width, \n self.__hight\n )\n\n self.__textEdit = QtGui.QTextEdit()\n self.setCentralWidget(self.__textEdit)\n\n self.setWindowTitle(self.__title)\n\n\n\n def createMenu(self):\n \n self.__action_open_file = QtGui.QAction(\"open file\", self)\n self.__action_close_file = QtGui.QAction(\"close file\", self)\n self.__action_save_file = QtGui.QAction(\"save file as\", self)\n self.__action_close_app = QtGui.QAction(\"Exit\", self)\n self.__action_edit_conf = QtGui.QAction(\"edit config\", self)\n self.__action_run_scripts = QtGui.QAction(\"run this current configure\", self)\n self.__action_set_font = QtGui.QAction(\"font\", self)\n self.__action_get_settings_and_run_scripts = QtGui.QAction(\"get settings and run\", self) \n\n self.__action_edit_conf.triggered.connect(self.edit_conf)\n self.__action_run_scripts.triggered.connect(self.run_scripts)\n self.__action_get_settings_and_run_scripts.triggered.connect(self.get_settings_and_run_scripts)\n self.__action_open_file.triggered.connect(self.read_file)\n self.__action_close_file.triggered.connect(self.close_file)\n self.__action_save_file.triggered.connect(self.save_file)\n self.__action_close_app.triggered.connect(self.close_window)\n self.__action_set_font.triggered.connect(self.set_font)\n\n \n self.__menubar = self.menuBar()\n\n\n self.__file = self.__menubar.addMenu(\"File\") \n self.__edit_conf = self.__menubar.addMenu(\"Edit\")\n self.__view = self.__menubar.addMenu(\"View\")\n self.__run_scripts = self.__menubar.addMenu(\"Run\")\n\n\n self.__file.addAction(self.__action_open_file)\n self.__file.addAction(self.__action_close_file)\n self.__file.addAction(self.__action_save_file)\n self.__file.addAction(self.__action_close_app)\n self.__edit_conf.addAction(self.__action_edit_conf)\n self.__view.addAction(self.__action_set_font)\n self.__run_scripts.addAction(self.__action_run_scripts)\n self.__run_scripts.addAction(self.__action_get_settings_and_run_scripts)\n \n\n\n\n def edit_conf(self):\n if self.__editConfWindow is None:\n self.__editConfWindow = windows.WindowEditConf(\"the edit window\", 300, 300)\n \n self.__editConfWindow.show_window()\n\n\n def run_scripts(self):\n runScripts.runExecTasks()\n\n\n def get_settings_and_run_scripts(self):\n if self.__netSettingsWindow is None:\n self.__netSettingsWindow = windows.WindowNetSettings(\"the net settings window\", 300, 300)\n\n self.__netSettingsWindow.show_window()\n\n\n\n def read_file(self):\n fname = self.getWorkFileName()\n\n with open(fname, 'r') as file:\n text = file.read().decode(\"utf-8\")\n self.__textEdit.setText(text)\n \n\n\n def close_file(self):\n self.__textEdit.setText(\"\")\n\n\n\n def save_file(self):\n text = self.__textEdit.toPlainText()\n fname = self.getWorkFileName()\n\n with open(fname, 'w') as file:\n file.write(text)\n \n\n\n def getWorkFileName(self):\n fname, _ = QtGui.QFileDialog.getOpenFileName(self, 'Open file', '../config/reports')\n return fname\n \n\n def set_font(self):\n font, ok = QtGui.QFontDialog.getFont()\n if ok:\n self.__textEdit.setFont(font)\n\n\n def show_window(self):\n self.show()\n\n \n def close_window(self):\n QtCore.QCoreApplication.instance().quit()\n\n\n \n\n\ndef main():\n app = QtGui.QApplication(sys.argv)\n \n mWindow = MainWindow(\n MAIN_WINDOW_TITLE,\n DEFAULT_M_WINDOW_POS_X, \n DEFAULT_M_WINDOW_POS_Y\n )\n\n mWindow.show_window() \n \n sys.exit(app.exec_())\n\n\nif __name__ == '__main__':\n main()","sub_path":"GUI/mainWindow.py","file_name":"mainWindow.py","file_ext":"py","file_size_in_byte":4682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"263458259","text":"import tensorflow as tf\nimport glob\nimport cv2\nimport random\nimport numpy as np\nimport os\nimport ctypes\nimport time\n\ndef new_weights_conv(name,shape):\n return tf.get_variable(name, shape=shape, dtype=tf.float32,\n initializer=tf.contrib.layers.xavier_initializer_conv2d())\n\ndef new_weights_fc(name,shape):\n return tf.get_variable(name, shape=shape, dtype=tf.float32,\n initializer=tf.contrib.layers.xavier_initializer())\n \ndef new_biases(length):\n return tf.Variable(tf.constant(0.05, shape=[length], dtype=tf.float32), dtype=tf.float32)\n\ndef new_conv_layer(name,input, # The previous layer.\n num_input_channels, # Num. channels in prev. layer.\n filter_size, # Width and height of each filter.\n num_filters, # Number of filters.\n use_pooling=True): # Use 2x2 max-pooling.\n\n shape = [filter_size, filter_size, num_input_channels, num_filters]\n\n # Create new weights aka. filters with the given shape.\n weights = new_weights_conv(name,shape)\n\n # Create new biases, one for each filter.\n biases = new_biases(length=num_filters)\n layer = tf.nn.conv2d(input=input,\n filter=weights,\n strides=[1, 1, 1, 1],\n padding='SAME')\n\n layer += biases\n\n # Use pooling to down-sample the image resolution?\n if use_pooling:\n layer = tf.nn.max_pool(value=layer,\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding='SAME')\n layer = tf.nn.relu(layer)\n return layer, weights\n \ndef flatten_layer(layer):\n # Get the shape of the input layer.\n layer_shape = layer.get_shape()\n num_features = layer_shape[1:4].num_elements()\n layer_flat = tf.reshape(layer, [-1, num_features])\n return layer_flat, num_features\n\n\ndef new_fc_layer(name,input, # The previous layer.\n num_inputs, # Num. inputs from prev. layer.\n num_outputs, use_nonlinear):\n weights = new_weights_fc(name,[num_inputs, num_outputs])\n biases = new_biases(length=num_outputs)\n\n layer = tf.matmul(input, weights) + biases\n if use_nonlinear:\n layer = tf.nn.relu(layer)\n\n return layer, weights\n\n\n# Convolutional Layer 1.\nfilter_size1 = 3\nnum_filters1 = 32\nnum_filters2 = 64\nnum_filters3 = 128\n\n\nn_classes = 15\nbatch_size = 256\nimgSize = 64\n\nx = tf.placeholder(tf.float32, [None, imgSize, imgSize])\nx_image = tf.reshape(x, [-1, imgSize, imgSize, 1])\ny = tf.placeholder(tf.float32)\nkeep_prob = tf.placeholder(tf.float32)\n\nlayer_conv1a, weights_conv1a = \\\n new_conv_layer(\"conv1a\",input=x_image,\n num_input_channels=1,\n filter_size=filter_size1,\n num_filters=num_filters1,\n use_pooling=False)\n\nlayer_conv1a1, weights_conv1a1 = \\\n new_conv_layer(\"conv1a1\",input=layer_conv1a,\n num_input_channels=num_filters1,\n filter_size=filter_size1,\n num_filters=num_filters1,\n use_pooling=True)\n\nlayer_conv1b, weights_conv1b = \\\n new_conv_layer(\"conv1b\",input=layer_conv1a1,\n num_input_channels=num_filters1,\n filter_size=filter_size1,\n num_filters=num_filters1,\n use_pooling=False)\n\nlayer_conv1b1, weights_conv1b1 = \\\n new_conv_layer(\"conv1b1\",input=layer_conv1b,\n num_input_channels=num_filters1,\n filter_size=filter_size1,\n num_filters=num_filters1,\n use_pooling=True)\n\nlayer_conv1c, weights_conv1c = \\\n new_conv_layer(\"conv1c\",input=layer_conv1b1,\n num_input_channels=num_filters1,\n filter_size=filter_size1,\n num_filters=num_filters1,\n use_pooling=False)\n\nlayer_conv1c1, weights_conv1c1 = \\\n new_conv_layer(\"conv1c1\",input=layer_conv1c,\n num_input_channels=num_filters1,\n filter_size=filter_size1,\n num_filters=num_filters1,\n use_pooling=True)\n\nlayer_flat, num_features = flatten_layer(layer_conv1c1)\n\nlayer_f, weights_f = new_fc_layer(\"fc\",input=layer_flat,\n num_inputs=num_features,\n num_outputs=n_classes,\n use_nonlinear=False)\n\ny_pred = tf.nn.softmax(layer_f)\ny_pred_cls = tf.argmax(y_pred, dimension=1)\n\nprint(layer_conv1a)\nprint(layer_flat)\nprint(layer_f)\n\n\n\ncorrect = tf.equal(tf.argmax(layer_f, 1), tf.argmax(y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct, 'float'))\n\n\nsaver = tf.train.Saver()\nsave_dir = 'final_model_15_16/'\nif not os.path.exists(save_dir):\n os.makedirs(save_dir)\nsave_path = os.path.join(save_dir, 'best_model')\n\n\n\n\n\n\n\n# direct inputs\n# source to this solution and code:\n# http://stackoverflow.com/questions/14489013/simulate-python-keypresses-for-controlling-a-game\n# http://www.gamespp.com/directx/directInputKeyboardScanCodes.html\n\n\n\nSendInput = ctypes.windll.user32.SendInput\n\n\nW = 0x11\nA = 0x1E\nS = 0x1F\nD = 0x20\n\n# C struct redefinitions \nPUL = ctypes.POINTER(ctypes.c_ulong)\nclass KeyBdInput(ctypes.Structure):\n _fields_ = [(\"wVk\", ctypes.c_ushort),\n (\"wScan\", ctypes.c_ushort),\n (\"dwFlags\", ctypes.c_ulong),\n (\"time\", ctypes.c_ulong),\n (\"dwExtraInfo\", PUL)]\n\nclass HardwareInput(ctypes.Structure):\n _fields_ = [(\"uMsg\", ctypes.c_ulong),\n (\"wParamL\", ctypes.c_short),\n (\"wParamH\", ctypes.c_ushort)]\n\nclass MouseInput(ctypes.Structure):\n _fields_ = [(\"dx\", ctypes.c_long),\n (\"dy\", ctypes.c_long),\n (\"mouseData\", ctypes.c_ulong),\n (\"dwFlags\", ctypes.c_ulong),\n (\"time\",ctypes.c_ulong),\n (\"dwExtraInfo\", PUL)]\n\nclass Input_I(ctypes.Union):\n _fields_ = [(\"ki\", KeyBdInput),\n (\"mi\", MouseInput),\n (\"hi\", HardwareInput)]\n\nclass Input(ctypes.Structure):\n _fields_ = [(\"type\", ctypes.c_ulong),\n (\"ii\", Input_I)]\n\n# Actuals Functions\n\ndef PressKey(hexKeyCode):\n extra = ctypes.c_ulong(0)\n ii_ = Input_I()\n ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )\n x = Input( ctypes.c_ulong(1), ii_ )\n ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))\n\ndef ReleaseKey(hexKeyCode):\n extra = ctypes.c_ulong(0)\n ii_ = Input_I()\n ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )\n x = Input( ctypes.c_ulong(1), ii_ )\n ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))\n\ndef sliding():\n PressKey(0x38)\n PressKey(0x0F)\n time.sleep(1)\n ReleaseKey(0x0F)\n\n ret, image_np = cap.read()\n \n cv2.imshow('object detection', cv2.resize(image_np, (400,300)))\n gray_image = cv2.cvtColor(cv2.resize(image_np, (imgSize,imgSize)), cv2.COLOR_BGR2GRAY)\n t2 = time.time()\n\n result = np.argmax(y_pred.eval({x:[gray_image]})) + 1\n\n while result == 5:\n\t PressKey(0x0F)\n\t time.sleep(1)\n\t ReleaseKey(0x0F)\n\t ret, image_np = cap.read()\n\t cv2.imshow('object detection', cv2.resize(image_np, (400,300)))\n\t gray_image = cv2.cvtColor(cv2.resize(image_np, (imgSize,imgSize)), cv2.COLOR_BGR2GRAY)\n\n\t result = np.argmax(y_pred.eval({x:[gray_image]})) + 1\n\t print(result)\n\n PressKey(0x1C)\n ReleaseKey(0x38)\n ReleaseKey(0x1C)\n time.sleep(1)\n return None\n\n\ngestures = ['None', 'fist', 'thumb up', 'thumb down', \\\n 'stop', 'catch', 'swing', 'phone', 'victory', \\\n 'C', 'okay', '2 fingers', '2 fingers horiz', \\\n 'rock&roll', 'rock&roll horiz']\n\nliste = glob.glob('./image/**')\ncap = cv2.VideoCapture(0)\nt = time.time()\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n saver.restore(sess=sess, save_path=save_path)\n for elm in liste[::-10]:\n ret, image_np = cap.read()\n image_np = cv2.imread(elm)\n cv2.imshow('object detection', cv2.resize(image_np, (400,300)))\n gray_image = cv2.cvtColor(cv2.resize(image_np, (imgSize,imgSize)), cv2.COLOR_BGR2GRAY)\n t2 = time.time()\n gray_image = cv2.equalizeHist(gray_image)\n result = np.argmax(y_pred.eval({x:[gray_image]}))\n\n print(gestures[result], 1/(time.time() - t), 1/(time.time() - t2))\n \n t = time.time()\n if cv2.waitKey(50) & 0xFF == ord('q'):\n cv2.destroyAllWindows()\n break","sub_path":"testModel.py","file_name":"testModel.py","file_ext":"py","file_size_in_byte":8584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"129752047","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom math import sqrt\r\n\r\nsin = np.sin\r\ncos = np.cos\r\n\r\ndef floats(str):\r\n return list(map(float, str.split()))\r\n\r\nv_init = float(input(\"Velocidad Inicial (m/s): \"))\r\nang = float(input(\"Ángulo de disparo (radianes): \"))\r\n\r\nif v_init <= 0:\r\n print(\"Ingrese una velocidad válida para tiro parabólico.\")\r\n exit()\r\n# Parámetros iniciales.\r\n\r\nvx0 = v_init * cos(ang)\r\n# Velocidad inicial en X\r\nvy0 = v_init * sin(ang)\r\n# Velocidad inicial en Y\r\n\r\nh_fin = input(\"\"\"\r\nSi la altura final supera a la inicial, especifíquela. \\\r\nDe lo contrario, presione ENTER: \"\"\")\r\n\r\nif h_fin != '':\r\n h_init = 0\r\n h_max = vy0 ** 2 / 19.62\r\n # Altura máxima del proyectil tomando la altura inicial como 0\r\n h_fin = float(h_fin)\r\n if h_fin > h_max:\r\n print(f\"La altura final supera la altura máxima de {h_max} m.\")\r\n exit()\r\nelse:\r\n h_init = float(input(\"\\nIngrese la altura inicial(m): \"))\r\n h_fin = 0\r\n h_max = vy0 ** 2 / 19.62 + h_init # Altura máxima.\r\n\r\n# Básicamente, lo que se quiere hacer con este condicional es que el eje X de\r\n# nuestro sistema de referencia coincida con el nivel de la altura más baja.\r\n# La primera parte es el caso donde la altura final supera a la inicial, y la\r\n# segunda parte es el caso contrario.\r\n\r\ndisc = vy0 ** 2 - 19.62 * (h_fin - h_init)\r\nt_floor = (vy0 + sqrt(disc)) / 9.81\r\n# Tiempo que tarda el proyectil en caer al piso.\r\nreach = vx0 * t_floor\r\n# Alcance horizontal del proyectil.\r\n\r\ninterval = floats(input(f\"\"\"\r\nEl proyectil cae al suelo tras {t_floor} segundos. \\\r\nIndique un tiempo final menor o igual a éste.\r\nIngrese el intervalo [t0, tf] como t0 tf: \"\"\"))\r\n# No tendría sentido graficar más allá de este punto.\r\n\r\nt0 = interval[0]\r\ntf = interval[1]\r\n\r\nif t0 < 0 or tf < 0 or tf > t_floor:\r\n print(\"Ingrese tiempos válidos.\")\r\n exit()\r\n# Intervalo de tiempo a graficar\r\n\r\nt = np.linspace(t0, tf)\r\nlenght = range(len(t))\r\n\r\npos_x = vx0 * t\r\nvel_x = np.array([vx0 for i in lenght])\r\nacc_x = np.array([0 for i in lenght])\r\n# Movimiento en la coordenada X. (Se asume que no hay aceleración horizontal).\r\n\r\npos_y = -9.81 * t ** 2 / 2 + vy0 * t + h_init\r\nvel_y = -9.81 * t + h_init\r\nacc_y = np.array([-9.81 for i in lenght])\r\n# Movimiento en la coordenada Y. (Uniformemente acelerado por la gravedad).\r\n\r\nwith open('movimiento_x.csv', 'w') as f:\r\n f.write('Tiempo,Posición,Velocidad,Aceleración\\n')\r\n f.write('\\n'.join('{},{},{},{}'.format(t[i], pos_x[i], vel_x[i], acc_x[i])\r\n for i in lenght))\r\n# Datos del movimiento en el eje X\r\n\r\nwith open('movimiento_y.csv', 'w') as f:\r\n f.write('Tiempo,Posición,Velocidad,Aceleración\\n')\r\n f.write('\\n'.join('{},{},{},{}'.format(t[i], pos_y[i], vel_y[i], acc_y[i])\r\n for i in lenght))\r\n# Datos del movimiento en el eje Y\r\n\r\nwith open('trayectoria.csv', 'w') as f:\r\n f.write('Posición_X,Posición_Y\\n')\r\n f.write('\\n'.join('{},{}'.format(pos_x[i], pos_y[i]) for i in lenght))\r\n# Datos de la posición en X vs posición en Y.\r\n\r\nprint(f\"\"\"\r\nAltura máxima: {h_max} m.\r\nTiempo de vuelo: {t_floor} s.\r\nAlcance horizontal: {reach} m.\r\n\"\"\")\r\n# Información relevante del tiro parabólico\r\n\r\nfig1, (ax1, ax2) = plt.subplots(nrows=1, ncols=2)\r\n# Figura para el movimiento de cada coordenada respecto al tiempo. Ambas\r\n# graficas están en una sola figura.\r\nfig2, ax3 = plt.subplots()\r\n# Figura para la trayectoria del proyectil.\r\n\r\nax1.plot(t, pos_x, color='#222288', label='Posición (m)')\r\nax1.plot(t, vel_x, color='#ffd700', linestyle='-.', label='Velocidad (m/s)')\r\nax1.plot(t, acc_x, color='#329932', linestyle='--', label='Aceleración (m/s²)')\r\n# Datos graficados del movimiento en X\r\n\r\nax1.set_xlabel(\"Tiempo\")\r\nax1.set_ylabel(\"Unidades respectivas\")\r\nax1.set_title(\"Movimiento en la Coordenada X\")\r\n\r\nax1.legend()\r\n\r\nax2.plot(t, pos_y, color='#222288', label='Posición (m)')\r\nax2.plot(t, vel_y, color='#ffd700', linestyle='-.', label='Velocidad (m/s)')\r\nax2.plot(t, acc_y, color='#329932', linestyle='--', label='Aceleración (m/s²)')\r\n# Datos graficados del movimiento en Y\r\n\r\nax2.set_xlabel(\"Tiempo\")\r\nax2.set_title(\"Movimiento en la Coordenada Y\")\r\n\r\nax2.legend()\r\n\r\nax3.plot(pos_x, pos_y, color='#222288', label='Posición (m)')\r\n# Grafica de la trayectoria.\r\n\r\nax3.set_xlabel(\"Desplazamiento horizontal (m)\")\r\nax3.set_ylabel(\"Altura (m)\")\r\nax3.set_title(\"Trayectoria\")\r\n\r\nax3.legend()\r\n\r\nplt.tight_layout()\r\n\r\nplt.show()\r\n\r\nfig1.savefig('Movimiento.png')\r\nfig2.savefig('Trayectoria.png')\r\n","sub_path":"Python_Scripts/Ejercicios/12/parabolico.py","file_name":"parabolico.py","file_ext":"py","file_size_in_byte":4525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"313834684","text":"from sklearn.naive_bayes import MultinomialNB\n\n# sudo pip install virtualenv\n# virtualenv ENV\n# pip install numpy scipy scikit-learn\n# python classificacao.py\n\n# perna curta, rabo comprido, peludo, gordinho\nporco1 = [1, 0, 0, 1]\nporco2 = [0, 0, 1, 1]\nporco3 = [1, 0, 1, 1]\nporco4 = [1, 0, 0, 0]\ngato1 = [0, 1, 1, 0]\ngato2 = [0, 1, 0, 1]\ngato3 = [1, 1, 0, 0]\ngato4 = [0, 0, 1, 0]\n\ndados = [porco1, porco2, porco3, porco4, gato1, gato2, gato3, gato4]\nclasses = [0, 0, 0, 0, 1, 1, 1, 1]\n\nmodelo = MultinomialNB()\nmodelo.fit(dados, classes)\n\nmisterioso1 = [1, 1, 1, 0] # gato\nmisterioso2 = [1, 0, 1, 0] # porco\nmisterioso3 = [0, 0, 0, 1] # porco\ntestes = [misterioso1, misterioso2, misterioso3]\nclasses_teste = [1, 0, 0]\nanimais_teste = [\"gato\" if i == 1 else \"porco\" for i in classes_teste]\n\nresultado = modelo.predict(testes)\nanimais_resultado = [\"gato\" if i == 1 else \"porco\" for i in resultado]\n\nprint(\"Resposta correta = \" + str(classes_teste).ljust(60, ' '))\nprint(\"Animais da resposta correta = \" + str(animais_teste).ljust(60, ' ') + \"\\n\")\nprint(\"Resultado = \" + str(resultado).ljust(60, ' '))\nprint(\"Animais = \" + str(animais_resultado).ljust(60, ' '))\n\n# Calculo da taxa de acerto\ndiferencas = resultado - classes_teste\nacertos = [d for d in diferencas if d==0]\ntotal_de_acertos = len(acertos)\ntotal_de_elementos = len(testes)\n\ntaxa_de_acerto = 100.0 * total_de_acertos / total_de_elementos\nprint(\"\\nTaxa de acerto = \" + str(taxa_de_acerto))","sub_path":"classificacao.py","file_name":"classificacao.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"209280552","text":"from flask import (flash, redirect, render_template, request, url_for, abort,\n jsonify, Blueprint, Response)\nfrom flask_login import current_user\nfrom functools import wraps\nfrom urllib.parse import parse_qsl\n\nimport app.service.user_service as user_service\nfrom app import db, constants, app\nfrom app.decorators import require_role, require_membership\nfrom app.forms import init_form\nfrom app.forms.custom_form import AddRegistrationForm\nfrom app.forms.custom_form import CreateForm\nfrom app.models.custom_form import CustomForm, CustomFormResult\nfrom app.roles import Roles\nfrom app.service import role_service, custom_form_service\nfrom app.utils import copernica\nfrom app.utils.forms import flash_form_errors\nfrom app.utils.pagination import Pagination\nfrom app.utils.serialize_sqla import serialize_sqla\n\nblueprint = Blueprint('custom_form', __name__, url_prefix='/forms')\n\n\ndef require_form_access(f):\n \"\"\"\n Check whether the user has access to the form.\n\n NOTE: Assumes that the form_id is the first parameter in the view function.\n \"\"\"\n\n @wraps(f)\n def wrapper(form_id=None, *args, **kwargs):\n if form_id:\n custom_form_service. \\\n check_user_can_access_form(form_id, current_user)\n return f(form_id, *args, **kwargs)\n\n return wrapper\n\n\n@blueprint.route('/', methods=['GET', 'POST'])\n@blueprint.route('//', methods=['GET', 'POST'])\n@require_role(Roles.ACTIVITY_WRITE)\ndef view(page_nr=1):\n followed_forms = custom_form_service. \\\n get_active_followed_forms_by_user(current_user)\n active_forms = custom_form_service. \\\n get_active_unfollowed_by_user(current_user)\n archived_forms = custom_form_service. \\\n get_inactive_forms_by_user(current_user)\n\n archived_paginate = Pagination(page_nr, 10, len(archived_forms),\n archived_forms)\n\n can_write = role_service.user_has_role(current_user, Roles.ACTIVITY_WRITE)\n return render_template('custom_form/overview.htm',\n followed_forms=followed_forms,\n active_forms=active_forms,\n archived_paginate=archived_paginate,\n page_nr=page_nr,\n can_write=can_write)\n\n\n@blueprint.route('/view/', methods=['GET', 'POST'])\n@require_role(Roles.ACTIVITY_WRITE)\n@require_form_access\ndef view_single(form_id=None):\n custom_form = custom_form_service.get_form_by_form_id(form_id)\n\n results = []\n entries = custom_form_service.get_form_entries_by_form_id(form_id)\n\n from urllib.parse import unquote_plus\n from urllib.parse import parse_qs\n\n attendants = 0\n for entry in entries:\n # Hide form entries from non existing users\n data = parse_qs(entry.data)\n\n # Add the entry date\n time = entry.created.strftime(constants.DT_FORMAT) if \\\n entry.created is not None else \"\"\n\n # Get the total number of attendants including extra attendees\n attendants = attendants + 1 + entry.introductions\n\n # Append the results with a single entry\n results.append({\n 'id': entry.id,\n 'owner': entry.owner,\n 'data': data,\n 'has_paid': entry.has_paid,\n 'time': time,\n 'introductions': entry.introductions,\n 'is_reserve': attendants > custom_form.max_attendants\n })\n\n custom_form.results = results\n\n can_update_paid = role_service.\\\n user_has_role(current_user, Roles.FINANCIAL_ADMIN)\n\n add_registration_form = AddRegistrationForm()\n\n return render_template('custom_form/view_results.htm',\n add_registration_form=add_registration_form,\n custom_form=custom_form,\n xps=CustomForm.exports,\n unquote_plus=unquote_plus,\n can_update_paid=can_update_paid)\n\n\n@blueprint.route('/export//', methods=['POST'])\n@require_role(Roles.ACTIVITY_WRITE)\n@require_form_access\ndef export(form_id):\n # Create the headers\n xp = CustomForm.exports\n xp_names = list(xp.keys())\n names = list(request.form.keys())\n\n form = custom_form_service.get_form_by_form_id(form_id)\n\n # First create a list of key based dictionaries to gather\n # all the different keys in the form\n csv_rows = []\n for r in form.custom_form_results:\n\n data = {}\n\n for name in xp_names:\n if name not in names:\n continue\n\n # Split the custom part of the form in different columns\n if name is 'form':\n # Data from the custom form is saved in querystring format\n export = xp[name]['export'](r)\n qs_dict = dict(parse_qsl(export, keep_blank_values=True))\n data.update(qs_dict)\n continue\n else:\n export = xp[name]['export']\n data.update({name: export(r)})\n\n csv_rows.append(data)\n\n # Calculate all the labels in the csv_rows\n label_set = set()\n for i in csv_rows:\n label_set.update(list(i.keys()))\n\n from io import StringIO\n from csv import DictWriter\n\n # Write all the values to the io field\n str_io = StringIO()\n wrt = DictWriter(str_io, fieldnames=label_set)\n wrt.writeheader()\n wrt.writerows(csv_rows)\n\n def generate():\n yield str_io.getvalue()\n\n return Response(generate(), mimetype='text/csv')\n\n\n@blueprint.route('/create/', methods=['GET', 'POST'])\n@blueprint.route('/edit/', methods=['GET', 'POST'])\n@require_role(Roles.ACTIVITY_WRITE)\n@require_form_access\ndef create(form_id=None):\n if form_id:\n custom_form = custom_form_service.get_form_by_form_id(form_id)\n prev_max = custom_form.max_attendants\n else:\n custom_form = CustomForm()\n\n form = init_form(CreateForm, obj=custom_form)\n\n if request.method == 'POST':\n custom_form.name = form.name.data\n custom_form.origin = form.origin.data\n custom_form.group = form.group.data\n custom_form.html = form.html.data\n custom_form.msg_success = form.msg_success.data\n custom_form.max_attendants = form.max_attendants.data\n custom_form.introductions = form.introductions.data\n if form.price.data is None:\n form.price.data = 0.0\n custom_form.price = form.price.data\n custom_form.terms = form.terms.data\n custom_form.requires_direct_payment = form.requires_direct_payment.data\n\n if form_id:\n flash('You\\'ve updated a form successfully.', 'success')\n cur_max = int(custom_form.max_attendants)\n # print(\"Current maximum: \" + cur_max)\n # print(\"Previous maximum: \" + prev_max)\n # print(\"Current submissions: \" + len(all_sub))\n if cur_max > prev_max:\n all_sub = CustomFormResult.query.filter(\n CustomFormResult.form_id == form_id\n ).all()\n # Update for users that were on the reserve list that they\n # can now attend.\n if prev_max < len(all_sub):\n for x in range(prev_max, min(cur_max, len(all_sub))):\n sub = all_sub[x]\n copernica_data = {\n \"Reserve\": \"Nee\"\n }\n copernica.update_subprofile(\n app.config['COPERNICA_ACTIVITEITEN'], sub.owner_id,\n sub.form_id, copernica_data)\n elif cur_max < prev_max:\n all_sub = CustomFormResult.query.filter(\n CustomFormResult.form_id == form_id\n ).all()\n if cur_max < len(all_sub):\n for x in range(cur_max, max(prev_max, len(all_sub) - 1)):\n sub = all_sub[x]\n copernica_data = {\n \"Reserve\": \"Ja\"\n }\n copernica.update_subprofile(\n app.config['COPERNICA_ACTIVITEITEN'], sub.owner_id,\n sub.form_id, copernica_data)\n\n db.session.add(custom_form)\n db.session.commit()\n\n if form_id is None:\n flash('You\\'ve created a form successfully.', 'success')\n custom_form_service.follow_form(\n form=custom_form, user_id=current_user.id)\n\n return redirect(url_for('custom_form.view'))\n else:\n flash_form_errors(form)\n\n return render_template('custom_form/create.htm', form=form)\n\n\n@blueprint.route('/remove///', methods=['POST'])\n@require_role(Roles.ACTIVITY_WRITE)\n@require_form_access\ndef remove_response(form_id=None, submission_id=None):\n\n response = \"success\"\n\n # Test if user already signed up\n submission = custom_form_service.\\\n get_form_submission_by_id(form_id, submission_id)\n\n form_id = submission.form_id\n max_attendants = submission.form.max_attendants\n\n db.session.delete(submission)\n db.session.commit()\n\n all_sub = custom_form_service.get_form_entries_by_form_id(form_id)\n\n if max_attendants <= len(all_sub):\n from_list = all_sub[max_attendants - 1]\n copernica_data = {\n \"Reserve\": \"Nee\"\n }\n copernica.update_subprofile(\n app.config['COPERNICA_ACTIVITEITEN'], from_list.owner_id,\n from_list.form_id, copernica_data)\n\n return response\n\n\n# Ajax method\n@blueprint.route('/submit/', methods=['POST'])\n@require_membership\ndef submit(form_id=-1):\n # TODO make sure custom_form rights are set on server\n response = \"success\"\n\n custom_form = custom_form_service.find_form_by_form_id(form_id)\n if not custom_form:\n return \"error\", 404\n\n print(custom_form.submittable_by(current_user))\n if not custom_form.submittable_by(current_user):\n return \"error\", 403\n\n if role_service.user_has_role(current_user, Roles.ACTIVITY_WRITE) and \\\n 'user_id' in request.form:\n user_id = int(request.form['user_id'])\n user = user_service.find_by_id(user_id)\n else:\n user = current_user\n\n # These fields might be there\n try:\n if request.form['phone_nr']:\n user.phone_nr = request.form['phone_nr']\n\n if request.form['noodnummer']:\n user.emergency_phone_nr = request.form['noodnummer']\n\n if request.form['shirt_maat']:\n user.shirt_size = request.form['shirt maat']\n\n if request.form['dieet[]']:\n user.diet = ', '.join(request.form['dieet[]'])\n\n if request.form['allergie/medicatie']:\n user.allergy = request.form['allergie/medicatie']\n\n if request.form['geslacht']:\n user.gender = request.form['geslacht']\n except Exception:\n pass\n\n # Test if current user already signed up\n duplicate_test = custom_form_service.find_form_submission_by_user_id(\n form_id, user.id)\n\n if duplicate_test:\n result = duplicate_test\n result.data = request.form['data']\n response = \"edit\"\n else:\n entries = custom_form_service.get_form_entries_by_form_id(form_id)\n num_attendants = sum(entry.introductions + 1 for entry in entries)\n num_introduce = min(int(request.form.get('introductions', 0)),\n custom_form.introductions)\n\n result = CustomFormResult(user.id, form_id,\n request.form['data'],\n has_paid=False,\n introductions=num_introduce)\n\n # Check if number attendants allows another registration\n if num_attendants >= custom_form.max_attendants:\n # Create \"Reserve\" signup\n response = \"reserve\"\n elif num_introduce > custom_form.introductions:\n response = \"edit\"\n else:\n copernica_data = {\n \"Naam\": custom_form.name,\n \"Betaald\": result.has_paid,\n \"Bedrag\": custom_form.price,\n \"viaductID\": form_id,\n \"Reserve\": \"Ja\" if response is \"reserve\" else \"Nee\",\n }\n copernica.add_subprofile(app.config['COPERNICA_ACTIVITEITEN'],\n user.id, copernica_data)\n\n db.session.add(user)\n db.session.commit()\n\n db.session.add(result)\n db.session.commit()\n\n return response\n\n\n@blueprint.route('/follow//', methods=['GET', 'POST'])\n@blueprint.route('/follow///',\n methods=['GET', 'POST'])\n@require_role(Roles.ACTIVITY_WRITE)\n@require_form_access\ndef follow(form_id, page_nr=1):\n following = custom_form_service.toggle_form_follow(\n form_id=form_id, user_id=current_user.id)\n\n if following:\n flash('Formulier gevolgd', 'success')\n else:\n flash('Formulier ontvolgd', 'success')\n return redirect(url_for('custom_form.view', page_nr=page_nr))\n\n\n@blueprint.route('/archive//', methods=['GET', 'POST'])\n@blueprint.route('/archive///',\n methods=['GET', 'POST'])\n@require_role(Roles.ACTIVITY_WRITE)\n@require_form_access\ndef archive(form_id, page_nr=1):\n custom_form_service.form_set_archive_status(form_id, True)\n\n flash('Formulier gearchiveerd', 'success')\n\n return redirect(url_for('custom_form.view', page_nr=page_nr))\n\n\n@blueprint.route('/unarchive//', methods=['GET', 'POST'])\n@blueprint.route('/unarchive///',\n methods=['GET', 'POST'])\n@require_role(Roles.ACTIVITY_WRITE)\n@require_form_access\ndef unarchive(form_id, page_nr=1):\n custom_form_service.form_set_archive_status(form_id, False)\n\n flash('Formulier gede-archiveerd', 'success')\n\n return redirect(url_for('custom_form.view', page_nr=page_nr))\n\n\n# Ajax endpoint\n@blueprint.route('/has_paid///',\n methods=['POST'])\n@require_role(Roles.FINANCIAL_ADMIN)\n@require_form_access\ndef has_paid(form_id=None, submission_id=None):\n\n custom_form_service.toggle_form_submission_paid(form_id, submission_id)\n\n return \"success\"\n\n\n@blueprint.route('/loader//', methods=['GET'])\ndef loader(current):\n try:\n current = int(current)\n except ValueError:\n return abort(404)\n\n return jsonify(forms=serialize_sqla(CustomForm.aslist(current)))\n","sub_path":"app/views/custom_form.py","file_name":"custom_form.py","file_ext":"py","file_size_in_byte":14613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"329955494","text":"\"\"\"\n Implementation of tractable approximation to the posterior covariance composed\n of tractable circulant and diagonal matrix operations only.\n\"\"\"\n\nfrom common import *\nfrom mvn import *\nimport gpvi\nimport cov, gpexact\nimport autograd.numpy as np\nimport matplotlib.pyplot as plt\nimport autograd.numpy.random as rng\nfrom cg_muq import ConjugateGradients as cg\n\nfrom optalg import GradientAscent, AdaGrad, AdaDelta, Adam\nfrom autograd import grad\nfrom DataStream import DataStream\nfrom DataGrid import DataGrid\nfrom scipy.linalg import cholesky as chol\nfrom scipy.linalg import solve_triangular as solve_tri\nimport copy\n\n\n\n# Compute initial variational parameters. M is the number of pseudo-data.\n#\n# Inputs:\n# M - the number of pseudo-data.\n# phi_h - existing dictionary of parameters. Created if not provided.\n#\n# Outputs:\n# phi_h - dictionary of parameters, transformed to be real-valued.\n#\ndef InitVariationalParameters(M, phi_h={}):\n phi_h['m_q'] = np.zeros(M)\n phi_h['w_h'] = BoundedToReal(0.99 * np.ones(M), lb=0.0, ub=1.0)\n phi_h['eps_h'] = BoundedToReal(1e-4 * np.ones(1), lb=0.0)\n return phi_h\n\n\n\n# Compute the parameters.\n#\n# Inputs:\n# phi - dictionary of parameters. Should be unbounded.\n#\n# Outputs:\n# m_q - mean of approximate posterior distribution.\n# w - diagonal of de-correlation matrix.\n# eps - auxilliary noise parameter.\n#\ndef ComputeVariationalParameters(phi_h):\n return phi_h['m_q'],\\\n RealToBounded(phi_h['w_h'], lb=0.0, ub=1.0),\\\n RealToBounded(phi_h['eps_h'], lb=0.0)\n\n\n\n# Compute the gradient w.r.t. the mean mu_q.\n#\n# Inputs:\n# phi_h - transformed variational parameters.\n# Z_grid - inducing point locations object.\n# datastream - DataStream object to provide access to mini-batches.\n# fcov - covariance function.\n# s2n_h - noise parameter s2n := log(1 + exp(s2nh)). (scalar)\n#\n# Outputs:\n# dmu_q - grad w.r.t. mu_q.\n#\ndef gradmuq(phi_h, Z_grid, datastream, fcov, s2n_h):\n\n # Get nex inputs and outputs from the data-stream object.\n Z, M, N = Z_grid.data, Z_grid.M, datastream.N\n X, y, L = datastream.GetNextMiniBatch()\n\n # Pre-compute invariant qtts.\n m_q = phi_h['m_q']\n eps = RealToBounded(phi_h['eps_h'], lb=0.0)\n Gamma = ComputeSpectrum(fcov, Z) + eps\n s2n = RealToBounded(s2n_h, lb=0.0)\n K0, KXZ = fcov(np.zeros(1)).flatten(), fcov(X, Z)\n\n # Compute gradient.\n tmp = np.real(fft(ifft(m_q) / Gamma))\n R = N / np.float64(L)\n delta = np.real(y - np.dot(KXZ, fft(ifft(m_q) / Gamma)))\n out = R * np.real(fft(ifft(np.dot(KXZ.T, delta)) / Gamma) / s2n) - tmp\n\n return { 'm_q' : out }\n\n\n\n# Compute the gradient w.r.t. the mean mu_q in Fourier domain. Hopefully this\n# will result in information sharing between inputs, resulting in more stable\n# convergence under optimisation. It's also faster at inference time as it\n# requires a couple fewer FFT operations.\n#\n# Inputs:\n# phi_h - transformed variational parameters.\n# Z_grid - inducing point locations object.\n# datastream - DataStream object to provide access to mini-batches.\n# fcov - covariance function.\n# s2n_h - noise parameter s2n := log(1 + exp(s2nh)). (scalar)\n#\n# Outputs:\n# dmu_q - grad w.r.t. mu_q.\n#\ndef gradmuqtilde(phi_h, Z_grid, datastream, fcov, s2n_h):\n\n # Get nex inputs and outputs from the data-stream object.\n Z, M, N = Z_grid.data, Z_grid.M, datastream.N\n X, y, L = datastream.GetNextMiniBatch()\n\n # Pre-compute invariant qtts.\n m_q = phi_h['m_q']\n eps = RealToBounded(phi_h['eps_h'], lb=0.0)\n Gamma = ComputeSpectrum(fcov, Z) + eps\n s2n = RealToBounded(s2n_h, lb=0.0)\n K0, KXZ = fcov(np.zeros(1)).flatten(), fcov(X, Z)\n\n # Compute gradient.\n R = N / np.float64(L)\n delta = y - np.dot(KXZ, np.real(fft(m_q / Gamma)))\n out = R * (fft(np.dot(KXZ.T, delta)) / s2n - m_q) / Gamma\n return { 'm_q' : out }\n\n\n# Compute the elbo given mean in fourier domain.\ndef elbo_mu_tilde(phi_h, Z_grid, datastream, fcov, s2n_h, check=False):\n phi_h_2 = copy.deepcopy(phi_h)\n phi_h_2['m_q'] = fft(phi_h['m_q'])\n return elbo_mu(phi_h_2, Z_grid, datastream, fcov, s2n_h, check=False)\n\n\n# Compute the elbo (lower bound on the log marginal probability). See\n# dissertation for explanation of the various opaquely-named quantities.\n#\n# Inputs:\n# phi_h - transformed variational parameters.\n# datastream - DataStream object to provide access to data.\n# Z_grid - inducing point locations. (M)\n# fcov - covariance function handle. (handle)\n# s2n_h - noise parameter s2n := log(1 + exp(s2nh)). (scalar)\n#\n# Outputs:\n# elbo - noisy estimate of the elbo.\n#\ndef elbo_mu(phi_h, Z_grid, datastream, fcov, s2n_h, check=False):\n\n # Get nex inputs and outputs from the data-stream object.\n Z, M, N = Z_grid.data, Z_grid.M, datastream.N\n X, y, L = datastream.GetNextMiniBatch()\n\n # Pre-compute invariant qtts.\n m_q, w, eps = ComputeVariationalParameters(phi_h)\n Gamma = ComputeSpectrum(fcov, Z) + eps\n s2n = RealToBounded(s2n_h, lb=0.0)\n K0, KXZ = fcov(np.zeros(1)).flatten(), fcov(X, Z)\n\n # Add likelihood expectation term using the last draws.\n mu = np.dot(KXZ, fft(ifft(m_q) / Gamma))\n elbo = lpdfDiagNormal(y, mu, np.array([s2n]), L) * N / np.float(L)\n\n # Subtract KL-divergence term.\n elbo -= 0.5 * np.sum(sqrabs(ifft(m_q)) / Gamma)\n return elbo\n\n\n\n# Compute the elbo (lower bound on the log marginal probability). See\n# dissertation for explanation of the various opaquely-named quantities.\n#\n# Inputs:\n# phi_h - transformed variational parameters.\n# datastream - DataStream object to provide access to data.\n# Z_grid - inducing point locations. (M)\n# fcov - covariance function handle. (handle)\n# s2n_h - noise parameter s2n := log(1 + exp(s2nh)). (scalar)\n#\n# Outputs:\n# elbo - noisy estimate of the elbo.\n#\ndef elbo(phi_h, Z_grid, datastream, fcov, s2n_h):\n\n # Get nex inputs and outputs from the data-stream object.\n Z, M, N = Z_grid.data, Z_grid.M, datastream.N\n X, y, L = datastream.GetNextMiniBatch()\n\n # Pre-compute invariant qtts.\n m_q, w, eps = ComputeVariationalParameters(phi_h)\n Gamma = ComputeSpectrum(fcov, Z) + eps\n s2n = RealToBounded(s2n_h, lb=0.0)\n K0, KXZ = fcov(np.zeros(1)).flatten(), fcov(X, Z)\n\n # Draw sample from approximate posterior.\n u_tilde = ifft(m_q + w * rndCircNormal(0.0, Gamma))\n\n # Add on cross-ent term.\n M = Z.shape[0]\n elbo = lpdfDiagNormal(u_tilde, 0.0, Gamma, M)\n\n # Add likelihood expectation term using the last draws.\n mu = np.dot(KXZ, fft(ifft(m_q) / Gamma))\n elbo += lpdfDiagNormal(y, mu, np.array([s2n]), L) * N / L\n\n # Subtract trace term - Monte Carlo approximation used.\n Q = rng.randn(L, 1)\n GammaT = np.reshape(Gamma, [M, 1])\n R = ifft(np.reshape(w, [M, 1]) * fft(ifft(np.dot(KXZ.T, Q)) / GammaT))\n elbo -= 0.5 * N * np.sum(np.sum(sqrabs(R), 1) * Gamma) / (s2n * L)\n\n # Subtract penalty trace term.\n cov_power = N * np.sum(sqrabs(fft(KXZ, axis=1)), 0) / L\n elbo -= 0.5 * (N * K0 - np.sum(cov_power / Gamma)) / s2n\n\n # Compute tractable bit of the elbo (entropy of r).\n elbo += HDiagNormal(Gamma) + np.sum(np.log(w))\n return elbo\n\n\n\n# Compute the root mean squared error (rmse) between the outputs from the\n# observation pairs in (X,y) and the posterior predictive mean under the\n# circulant approximation.\n#\n# Inputs:\n# phi_h - transformed variational parameters.\n# datastream - DataStream object to provide access to data.\n# Z_grid - inducing point locations. (M)\n# fcov - covariance function handle. (handle)\n# s2n_h - noise parameter s2n := log(1 + exp(s2nh)). (scalar)\n#\n# Outputs:\n# rmse - the root mean squared error. (scalar)\n#\ndef rmse_circ(phi_h, Z_grid, datastream, fcov):\n\n # Get next inputs and outputs from the data-stream object.\n Z = Z_grid.data\n X, y, L = datastream.GetNextMiniBatch()\n\n # Pre-compute invariant qtts.\n m_q, w, eps = ComputeVariationalParameters(phi_h)\n Gamma = ComputeSpectrum(fcov, Z) + eps\n\n # Compute mean predictions and compare with observation outputs.\n mu = np.dot(fcov(X, Z), np.real(fft(ifft(m_q) / Gamma)))\n return rmse(y, mu)\n\n\n\n# Compute the posterior mean and marginal variance at each input in X.\n#\n# Inputs:\n# phi_h - transformed variational parameters.\n# Z_grid - DataGrid object containing pseudo-data inputs.\n# X - inputs. (N)\n# fcov - covariance function handle. (handle)\n#\n# Outputs:\n# mu - posterior mean estimates at X.\n# s2 - posterior variance estimates at X.\n#\ndef posterior(phi_h, Z_grid, X, fcov):\n\n # Pre-compute invariant qtts.\n m_q, w, eps = ComputeVariationalParameters(phi_h)\n Gamma = ComputeSpectrum(fcov, Z_grid.data) + eps\n Ktilde, Kself = ifft(fcov(Z_grid.data, X)), fcov(np.zeros(1), diag=True)\n\n # Compute posterior mean.\n mu = np.real(np.dot(np.conj(Ktilde.T), ifft(m_q) / Gamma))\n\n # Compute marginal posterior variance.\n M, N = Z_grid.data.shape[0], X.shape[0]\n GammaT, wT = np.reshape(Gamma, [-1, 1]), np.reshape(w, [-1, 1])\n s2 = Kself - np.sum(sqrabs(Ktilde) / GammaT, 0) +\\\n np.sum(sqrabs(ifft(wT * fft(Ktilde / GammaT))) * GammaT, 0)\n return mu, s2\n\n\n\n# Knowing the kernel parameters, infer distribution over latent variables.\n#\n# Inputs:\n# fcov - covariance function, implicit parameters.\n# data_stream - DataStream object that containing the data.\n# Z_grid - DataGrid object containing the pseudo-data input locations.\n# phi_h - initial variational parameters. See InitVariationalParameters for\n# requirements.\n# s2n_h - observation noise. (1), (>0)\n# iters - number of iterations.\n# infalg - inference algorithm function handle.\n# collect_delta - number of iterations to wait between collecting elbo.\n# qtt_dict - dictionary mapping to function handles which compute scalar\n# quantities of interest as a function of the model parameters.\n#\n# Outputs:\n# elbos - logged elbos.\n#\ndef infer_mu(fcov, datastream, Z_grid, phi_h, iters, inf_alg, collect_delta,\\\n qtt_dict):\n\n # Define objective function and inference routine.\n dL = lambda phi_h : gradmuq(phi_h, Z_grid, datastream, fcov, phi_h['s2n_h'])\n inf_obj = inf_alg(dL, phi_h)\n\n # Define object to collect quantities of interest throughout iteration.\n out_dict = {}\n J, j = iters / collect_delta, 0\n for key in qtt_dict.keys():\n out_dict[key] = np.empty(J)\n\n # Iterate for the specified amount of time.\n updates = dict({'m_q' : None })\n elbos = np.empty(J)\n for itr in range(iters):\n inf_obj.update(phi_h, updates)\n if itr % collect_delta == 0:\n for key in qtt_dict.keys():\n out_dict[key][j] = qtt_dict[key](phi_h)\n print(str(j) + '/' + str(J))\n j += 1\n return out_dict\n\n\n\ndef main():\n\n # Define pseudo-data.\n lb, ub, N, s2n = 0.0, 10.0, 750, 1e-3\n extend, M, collect_delta = 5.0, 75, 25\n Z = DataGrid(lb - extend, ub + extend, M)\n\n # Define the covariance matrix.\n print('Define covariance function.')\n pars = cov.init_eq(s2=1.0, l2=1.0)\n delta = (ub - lb + 2 * extend)\n fcov = cov.circ_factory(cov.eq, delta, pars)\n\n # Generate some data and define streaming object.\n print('Generate toy data.')\n rng.seed(15485863)\n X1 = rng.uniform(low=lb, high=ub * 3.0/10.0, size=N / 2)\n X2 = rng.uniform(low=ub * 5.0/10.0, high=ub, size=N / 2)\n X = rng.permutation(np.hstack([X1, X2]))\n y = rndFullNormal(np.zeros(N), fcov(X, X) + s2n * np.eye(N))\n D = DataStream(N, X, y)\n\n # Define initial variational parameters and inference routine.\n print('Define variational parameters and inference.')\n phi_h = InitVariationalParameters(M)\n phi_h['s2n_h'] = BoundedToReal(s2n, lb=0.0)\n\n # Define dictionary of quantities to compute throughout inference.\n qtt_dict = {}\n qtt_dict['rmse'] = lambda phi_h : rmse_circ(phi_h, Z, D, fcov)\n qtt_dict['elbo'] = lambda phi_h : elbo_mu(phi_h, Z, D, fcov, phi_h['s2n_h'])\n\n # Perform inference.\n print('Perform inference.')\n phi_h_2 = copy.deepcopy(phi_h)\n D_ag = DataStream(25, X, y)\n df = lambda phi_h : gradmuq(phi_h, Z, D_ag, fcov, phi_h['s2n_h'])\n opt = AdaGrad(df, 2.0, phi_h)\n out_dict_ag = gradopt(phi_h, opt, 3000, 10, qtt_dict, updates={'m_q' : None})\n \"\"\"out_dict_ag =\\\n infer_mu(fcov, D_ag, Z, phi_h, 1000, inf_alg, 10, qtt_dict)\"\"\"\n out_dict_cg = cg(phi_h_2, Z.data, D, fcov, 100, 1, qtt_dict)\n\n # Plot rmse.\n plt.plot(out_dict_cg['rmse'], 'b', out_dict_ag['rmse'], 'g')\n plt.title('rmse')\n plt.figure()\n plt.plot(out_dict_cg['elbo'], 'b', out_dict_ag['elbo'], 'g')\n plt.title('elbo')\n\n # Define locations at which to make posterior predictions and compute under\n # circular structured posterior.\n Xhat = np.linspace(lb - extend, ub + extend, 1500)\n mu_ag, s2_ag = posterior(phi_h, Z, Xhat, fcov)\n mu_cg, s2_cg = posterior(phi_h_2, Z, Xhat, fcov)\n\n # Compute posterior approximation exactly and check that gradient is 0 at the\n # optimum.\n eps, s2n_h = RealToBounded(phi_h['eps_h'], lb=0.0), phi_h['s2n_h']\n ex_mu_q, ex_Sigma_q, elbo = gpvi.ApproxPosterior(fcov, X, y, Z.data, s2n_h)\n mu_ex, s2_ex = gpvi.PostPredict(Z.data, ex_mu_q, ex_Sigma_q, Xhat, fcov)\n\n # Plot the data, approximate circulant posterior and true posterior via VFE.\n plt.figure()\n plt.plot(Xhat, mu_ag, 'g')\n plt.plot(Xhat, mu_cg, 'b')\n plt.plot(Xhat, mu_ex, 'r')\n plt.plot(X, y, 'kx')\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"exp/circgp/optimise_mean.py","file_name":"optimise_mean.py","file_ext":"py","file_size_in_byte":13025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"99945335","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\n\nfrom django.contrib.sites.models import Site\nfrom django.db.models import Q\n\nfrom machina.core.db.models import get_model\nfrom machina.core.loading import get_class\n\n\nPost = get_model('forum_conversation', 'Post')\nNotificationEmail = get_class('forum_member.emails', 'NotificationEmail')\n\n\ndef send_notifications(email_class=None, context=None):\n \"\"\"\n Send notification on email to the user that subscribe on topics.\n \"\"\"\n email_class = email_class or NotificationEmail\n email = email_class()\n\n if not context:\n context = {}\n\n posts = Post.objects.filter(\n approved=True,\n notifications_sent=False,\n ).select_related('topic__forum')\n for post in posts:\n users = post.topic.subscribers.filter(\n ~Q(id=post.poster_id),\n forum_profile__notify_subscribed_topics=True,\n email__isnull=False\n )\n\n for user in users:\n email_context = context.copy()\n email_context.update({\n 'user': user,\n 'post': post,\n 'topic': post.topic,\n 'current_site': Site.objects.get_current(),\n })\n email.send([user.email], email_context)\n\n post.notifications_sent = True\n post.save()\n","sub_path":"machina/apps/forum_member/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"527960515","text":"import os\nimport time\nimport pickle\nimport cv2\nimport threading\n\nimport tensorflow as tf\ntf.logging.set_verbosity(tf.logging.ERROR)\n\nimport threading\nimport grpc\nfrom tensorflow_serving.apis import prediction_service_pb2_grpc\n\nimport sys\nsys.path.append('/home/yitao/Documents/fun-project/tensorflow-related/video-captioning-serving/')\n\nfrom modules_video_cap.video_cap_vgg16_rim import CapVGG16\nfrom modules_video_cap.video_cap_alexnet_rim import CapAlexnet\nfrom modules_video_cap.video_cap_s2vt_rim import CapS2VT\n\nvgg = CapVGG16()\nvgg.Setup()\n\nalexnet = CapAlexnet()\nalexnet.Setup()\n\n# first = vgg\nfirst = alexnet\n\ns2vt =CapS2VT()\ns2vt.Setup()\n\nichannel = grpc.insecure_channel(\"localhost:8500\")\nistub = prediction_service_pb2_grpc.PredictionServiceStub(ichannel)\n\nvideo_path = \"/home/yitao/Documents/fun-project/tensorflow-related/video-captioning-serving/inputs/vid264.mp4\"\nreader = cv2.VideoCapture(video_path)\n\nframe_id = 1\n\nfeatures_fc7 = []\nmy_lock = threading.Lock()\n\ntotal = 0.0\ncount = 0\n\nwhile (frame_id < 250):\n start = time.time()\n\n _, image = reader.read()\n\n request = dict()\n\n request[\"client_input\"] = image\n\n first.PreProcess(request = request, istub = istub, features_fc7 = features_fc7, my_lock = my_lock, grpc_flag = False)\n first.Apply()\n next_request = first.PostProcess(grpc_flag = False)\n\n # print(next_request[\"vgg_output\"])\n\n s2vt.PreProcess(request = next_request, istub = istub, grpc_flag = False)\n s2vt.Apply()\n next_request = s2vt.PostProcess(grpc_flag = False)\n\n # if (next_request[\"FINAL\"] != \"None\"):\n # print(next_request[\"FINAL\"])\n\n end = time.time()\n\n duration = end - start\n print(\"duration = %f\" % duration)\n if (frame_id > 5):\n count += 1\n total += duration\n\n frame_id += 1\n\nprint(\"on average, it takes %f sec per frame\" % (total / count))","sub_path":"tomTest/cap_rim.py","file_name":"cap_rim.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"159124513","text":"'''\n色彩空间之间的颜色互换\n'''\nimport cv2 as cv\nimport numpy as np\n'''\ndef extrace_obj_demo():\n capture=cv.VideoCapture(\"../data/vedo1.mp4\")\n while True:\n ret,frame=capture.read()\n if ret==False:\n break;\n hsv=cv.cvtColor(frame,cv.COLOR_BGR2HSV)\n lower_hsv=np.array([37,43,46])\n upper_hsv=np.array([77,255,255])\n mask=cv.inRange(hsv,lowerb=lower_hsv,upperb=upper_hsv)\n cv.bitwise_and(frame,frame,mask=mask)\n cv.imshow(\"video\",frame)\n cv.imshow(\"mask\",mask)\n c=cv.waitKey(40)\n if c==27:\n break;\n'''\ndef color_dpace_demo(image):\n gray=cv.cvtColor(image,cv.COLOR_BGR2GRAY)\n cv.imshow(\"gray\",gray)\n hsv= cv.cvtColor(image, cv.COLOR_BGR2HSV)\n cv.imshow(\"hav\", hsv)\n yuv = cv.cvtColor(image, cv.COLOR_BGR2YUV)\n cv.imshow(\"yuv\", yuv)\n Ycrcb= cv.cvtColor(image, cv.COLOR_BGR2YCrCb)\n cv.imshow(\"Ycrcb\", Ycrcb)\n\n\nprint(\"**\"*20)\n\nsrc=cv.imread(\"../data/5.jpg\")\ncv.namedWindow(\"input image\",cv.WINDOW_AUTOSIZE)\ncv.imshow(\"input image\",src)\nprint(src.shape)\nt1=cv.getTickCount()\ncolor_dpace_demo(src)\nt2=cv.getTickCount()\n\ntime=(t2-t1)/cv.getTickFrequency()\n\nprint(\"time:%s ms\"%(time*1000))\n\ncv.waitKey(0)\n\ncv.destroyAllWindows()","sub_path":"lq-Project/lq17.py","file_name":"lq17.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"581770006","text":"from unittest.mock import MagicMock\n\nfrom src import quotes\nfrom src.data_provider import DataProvider\n\n\ndef test_quote_should_be_none_for_empty_list():\n empty_data = DataProvider('')\n empty_data.get_all = MagicMock(return_value=[])\n quote = quotes.random_quote(empty_data)\n assert quote is None\n\n\ndef test_quote_should_be_in_array():\n fake_data = DataProvider('')\n qts = ['quote' + str(x) for x in range(5)]\n fake_data.get_all = MagicMock(return_value=qts)\n quote = quotes.random_quote(fake_data)\n assert quote in qts\n","sub_path":"tests/test_unit_quotes.py","file_name":"test_unit_quotes.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"78764106","text":"#Thomas Thorpe\r\n#08/01/15\r\n#Lists Stretch and Challenge Task 1\r\n\r\ndef option_one (band_names):\r\n item = input(\"Please enter the band to add: \")\r\n print (\" \")\r\n band_names.append(item)\r\n return band_names\r\n \r\ndef option_two (band_names):\r\n item = \"oisdfhoahiefnowifnehoiwdnfheowa\"\r\n while item not in band_names:\r\n item = input(\"Please enter the band to delete: \")\r\n print (\" \")\r\n band_names.remove(item)\r\n return band_names\r\n \r\ndef option_three (band_names):\r\n position = -1\r\n while position < 1 or position > len(band_names):\r\n position = int(input(\"Please enter the number of item to delete: \"))\r\n print (\" \")\r\n band_names.pop(position - 1)\r\n return band_names\r\n\r\ndef option_four (band_names):\r\n item = input(\"Please enter the band to add: \")\r\n position = int(input(\"Please enter the number to insert before: \"))\r\n print (\" \")\r\n band_names.insert(position - 1, item)\r\n return band_names\r\n\r\ndef option_five (band_names):\r\n position = -1\r\n while position < 1 or position > len(band_names):\r\n position = int(input(\"Please enter the number to change: \"))\r\n item = input(\"Please enter the band to change to: \")\r\n print (\" \")\r\n band_names[position - 1] = item\r\n return band_names\r\n\r\ndef display_options ():\r\n print (\"1. Add an item to th end of the list\")\r\n print (\"2. Delete an item by name\")\r\n print (\"3. Delete an item by list position\")\r\n print (\"4. Insert a new item\")\r\n print (\"5. Amend an item\")\r\n print (\"9. Exit\")\r\n\r\ndef choose_option ():\r\n choice = -1\r\n while choice not in [1,2,3,4,5,9]:\r\n choice = int(input(\"Please enter the menu choice: \"))\r\n return choice\r\n\r\ndef display_list(band_names):\r\n print (\"Current List:\")\r\n for count in range(0,len(band_names)):\r\n number = str(count + 1)\r\n print (\"{0}. {1}\".format(number,band_names[count]))\r\n print (\" \")\r\n\r\n\r\n\r\ndef main():\r\n band_names = [\"Fit For An Autospy\", \"Lorna Shore\", \"Motionless In White\", \"Suicide Silence\", \"Make Them Suffer\"]\r\n choice = -1\r\n while choice != 9:\r\n display_list(band_names)\r\n display_options()\r\n choice = choose_option()\r\n if choice == 1:\r\n band_names = option_one(band_names)\r\n elif choice == 2:\r\n band_names = option_two(band_names)\r\n elif choice == 3:\r\n band_names = option_three(band_names)\r\n elif choice == 4:\r\n band_names = option_four(band_names)\r\n elif choice == 5:\r\n band_names = option_five(band_names)\r\n \r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"Lists Strech and Challenge Task 1.py","file_name":"Lists Strech and Challenge Task 1.py","file_ext":"py","file_size_in_byte":2628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"521053791","text":"\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\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\"\"\"\nimport oneflow as flow\nimport oneflow.typing as oft\nimport numpy as np\nimport os\nimport unittest\n\n\n@unittest.skipIf(os.getenv(\"ONEFLOW_TEST_CPU_ONLY\"), \"only test cpu cases\")\ndef test_1n1c(test_case):\n dcgan = DCGAN()\n dcgan.compare_with_tf(1)\n\n\n@unittest.skipIf(os.getenv(\"ONEFLOW_TEST_CPU_ONLY\"), \"only test cpu cases\")\ndef test_1n4c(test_case):\n dcgan = DCGAN()\n dcgan.compare_with_tf(4)\n\n\nclass DCGAN:\n def __init__(self):\n self.lr = 1e-4\n self.z_dim = 100\n self.batch_size = 32\n\n def compare_with_tf(self, gpu_num, result_dir=\"/dataset/gan_test/dcgan/\"):\n flow.config.gpu_device_num(gpu_num)\n func_config = flow.FunctionConfig()\n func_config.default_data_type(flow.float)\n func_config.default_logical_view(flow.scope.consistent_view())\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def test_generator(\n z: oft.Numpy.Placeholder((self.batch_size, self.z_dim)),\n label1: oft.Numpy.Placeholder((self.batch_size, 1)),\n ):\n g_out = self.generator(z, trainable=True, const_init=True)\n g_logits = self.discriminator(g_out, trainable=False, const_init=True)\n g_loss = flow.nn.sigmoid_cross_entropy_with_logits(\n flow.ones_like(g_logits),\n g_logits,\n name=\"Gloss_sigmoid_cross_entropy_with_logits\",\n )\n\n flow.optimizer.SGD(\n flow.optimizer.PiecewiseConstantScheduler([], [self.lr]), momentum=0\n ).minimize(g_loss)\n return g_loss\n\n @flow.global_function(type=\"train\", function_config=func_config)\n def test_discriminator(\n z: oft.Numpy.Placeholder((self.batch_size, 100)),\n images: oft.Numpy.Placeholder((self.batch_size, 1, 28, 28)),\n label1: oft.Numpy.Placeholder((self.batch_size, 1)),\n label0: oft.Numpy.Placeholder((self.batch_size, 1)),\n ):\n g_out = self.generator(z, trainable=False, const_init=True)\n g_logits = self.discriminator(g_out, trainable=True, const_init=True)\n d_loss_fake = flow.nn.sigmoid_cross_entropy_with_logits(\n flow.zeros_like(g_logits),\n g_logits,\n name=\"Dloss_fake_sigmoid_cross_entropy_with_logits\",\n )\n\n d_logits = self.discriminator(\n images, trainable=True, reuse=True, const_init=True\n )\n d_loss_real = flow.nn.sigmoid_cross_entropy_with_logits(\n flow.ones_like(d_logits),\n d_logits,\n name=\"Dloss_real_sigmoid_cross_entropy_with_logits\",\n )\n d_loss = d_loss_fake + d_loss_real\n flow.optimizer.SGD(\n flow.optimizer.PiecewiseConstantScheduler([], [self.lr]), momentum=0\n ).minimize(d_loss)\n\n return d_loss\n\n check_point = flow.train.CheckPoint()\n check_point.init()\n\n z = np.load(os.path.join(result_dir, \"z.npy\"))\n imgs = np.load(os.path.join(result_dir, \"img.npy\")).transpose(0, 3, 1, 2)\n label1 = np.ones((self.batch_size, 1)).astype(np.float32)\n label0 = np.zeros((self.batch_size, 1)).astype(np.float32)\n g_loss = test_generator(z, label1).get()\n d_loss = test_discriminator(z, imgs, label1, label0).get()\n tf_g_loss = np.load(os.path.join(result_dir, \"g_loss.npy\"))\n tf_d_loss = np.load(os.path.join(result_dir, \"d_loss.npy\"))\n\n if gpu_num == 1: # multi-gpu result can not pass\n assert np.allclose(\n g_loss.numpy(), tf_g_loss, rtol=1e-2, atol=1e-1\n ), \"{}-{}\".format(g_loss.ndarray().mean(), tf_g_loss.mean())\n assert np.allclose(\n d_loss.numpy(), tf_d_loss, rtol=1e-2, atol=1e-1\n ), \"{}-{}\".format(d_loss.ndarray().mean(), tf_d_loss.mean())\n\n def generator(self, z, const_init=False, trainable=True):\n # (n, 256, 7, 7)\n h0 = layers.dense(\n z, 7 * 7 * 256, name=\"g_fc1\", const_init=const_init, trainable=trainable\n )\n h0 = layers.batchnorm(h0, axis=1, name=\"g_bn1\")\n h0 = flow.nn.leaky_relu(h0, 0.3)\n h0 = flow.reshape(h0, (-1, 256, 7, 7))\n # (n, 128, 7, 7)\n h1 = layers.deconv2d(\n h0,\n 128,\n 5,\n strides=1,\n name=\"g_deconv1\",\n const_init=const_init,\n trainable=trainable,\n )\n h1 = layers.batchnorm(h1, name=\"g_bn2\")\n h1 = flow.nn.leaky_relu(h1, 0.3)\n # (n, 64, 14, 14)\n h2 = layers.deconv2d(\n h1,\n 64,\n 5,\n strides=2,\n name=\"g_deconv2\",\n const_init=const_init,\n trainable=trainable,\n )\n h2 = layers.batchnorm(h2, name=\"g_bn3\")\n h2 = flow.nn.leaky_relu(h2, 0.3)\n # (n, 1, 28, 28)\n out = layers.deconv2d(\n h2,\n 1,\n 5,\n strides=2,\n name=\"g_deconv3\",\n const_init=const_init,\n trainable=trainable,\n )\n out = flow.math.tanh(out)\n return out\n\n def discriminator(self, img, const_init=False, trainable=True, reuse=False):\n # (n, 1, 28, 28)\n h0 = layers.conv2d(\n img,\n 64,\n 5,\n name=\"d_conv1\",\n const_init=const_init,\n trainable=trainable,\n reuse=reuse,\n )\n h0 = flow.nn.leaky_relu(h0, 0.3)\n # h0 = flow.nn.dropout(h0, rate=0.3)\n # (n, 64, 14, 14)\n h1 = layers.conv2d(\n h0,\n 128,\n 5,\n name=\"d_conv2\",\n const_init=const_init,\n trainable=trainable,\n reuse=reuse,\n )\n h1 = flow.nn.leaky_relu(h1, 0.3)\n # h1 = flow.nn.dropout(h1, rate=0.3)\n # (n, 128 * 7 * 7)\n out = flow.reshape(h1, (self.batch_size, -1))\n # (n, 1)\n out = layers.dense(\n out, 1, name=\"d_fc\", const_init=const_init, trainable=trainable, reuse=reuse\n )\n return out\n\n\nclass layers:\n @classmethod\n def deconv2d(\n cls,\n input,\n filters,\n size,\n name,\n strides=2,\n trainable=True,\n reuse=False,\n const_init=False,\n use_bias=False,\n ):\n name_ = name if reuse == False else name + \"_reuse\"\n # weight : [in_channels, out_channels, height, width]\n weight_shape = (input.shape[1], filters, size, size)\n output_shape = (\n input.shape[0],\n input.shape[1],\n input.shape[2] * strides,\n input.shape[3] * strides,\n )\n\n weight = flow.get_variable(\n name + \"-weight\",\n shape=weight_shape,\n dtype=input.dtype,\n initializer=flow.random_normal_initializer(stddev=0.02)\n if not const_init\n else flow.constant_initializer(0.002),\n trainable=trainable,\n reuse=reuse,\n )\n\n output = flow.nn.conv2d_transpose(\n input,\n weight,\n strides=[strides, strides],\n output_shape=output_shape,\n padding=\"SAME\",\n data_format=\"NCHW\",\n name=name_,\n )\n\n if use_bias:\n bias = flow.get_variable(\n name + \"-bias\",\n shape=(filters,),\n dtype=input.dtype,\n initializer=flow.constant_initializer(0.0),\n trainable=trainable,\n reuse=reuse,\n )\n\n output = flow.nn.bias_add(output, bias, \"NCHW\")\n return output\n\n @classmethod\n def conv2d(\n cls,\n input,\n filters,\n size,\n name,\n strides=2,\n padding=\"same\",\n trainable=True,\n reuse=False,\n const_init=False,\n use_bias=True,\n ):\n name_ = name if reuse == False else name + \"_reuse\"\n\n # (output_dim, k_h, k_w, input.shape[3]) if NHWC\n weight_shape = (filters, input.shape[1], size, size)\n weight = flow.get_variable(\n name + \"-weight\",\n shape=weight_shape,\n dtype=input.dtype,\n initializer=flow.random_normal_initializer(stddev=0.02)\n if not const_init\n else flow.constant_initializer(0.002),\n trainable=trainable,\n reuse=reuse,\n )\n\n output = flow.nn.compat_conv2d(\n input,\n weight,\n strides=[strides, strides],\n padding=padding,\n data_format=\"NCHW\",\n name=name_,\n )\n\n if use_bias:\n bias = flow.get_variable(\n name + \"-bias\",\n shape=(filters,),\n dtype=input.dtype,\n initializer=flow.constant_initializer(0.0),\n trainable=trainable,\n reuse=reuse,\n )\n\n output = flow.nn.bias_add(output, bias, \"NCHW\")\n return output\n\n @classmethod\n def dense(\n cls,\n input,\n units,\n name,\n use_bias=False,\n trainable=True,\n reuse=False,\n const_init=False,\n ):\n name_ = name if reuse == False else name + \"_reuse\"\n\n in_shape = input.shape\n in_num_axes = len(in_shape)\n assert in_num_axes >= 2\n\n inputs = flow.reshape(input, (-1, in_shape[-1])) if in_num_axes > 2 else input\n\n weight = flow.get_variable(\n name=\"{}-weight\".format(name),\n shape=(units, inputs.shape[1]),\n dtype=inputs.dtype,\n initializer=flow.random_normal_initializer(stddev=0.02)\n if not const_init\n else flow.constant_initializer(0.002),\n trainable=trainable,\n model_name=\"weight\",\n reuse=reuse,\n )\n\n out = flow.matmul(a=inputs, b=weight, transpose_b=True, name=name_ + \"matmul\",)\n\n if use_bias:\n bias = flow.get_variable(\n name=\"{}-bias\".format(name),\n shape=(units,),\n dtype=inputs.dtype,\n initializer=flow.random_normal_initializer()\n if not const_init\n else flow.constant_initializer(0.002),\n trainable=trainable,\n model_name=\"bias\",\n reuse=reuse,\n )\n out = flow.nn.bias_add(out, bias, name=name_ + \"_bias_add\")\n\n out = flow.reshape(out, in_shape[:-1] + (units,)) if in_num_axes > 2 else out\n return out\n\n @classmethod\n def batchnorm(cls, input, name, axis=1, reuse=False):\n name_ = name if reuse == False else name + \"_reuse\"\n return flow.layers.batch_normalization(input, axis=axis, name=name_)\n","sub_path":"oneflow/python/test/models/test_dcgan.py","file_name":"test_dcgan.py","file_ext":"py","file_size_in_byte":11473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"613400479","text":"# [MAC]SSL Certificate FAIL 這句是MAC電腦才要加的\n# import ssl\n# ssl._create_default_https_context = ssl._create_unverified_context\n# 上面兩行都是MAC要加的\nfrom urllib.request import urlopen, urlretrieve\nimport json\nimport os\nyears = [\"2018\", \"2019\"]\nfor y in years:\n for m in range(12):\n url = \"https://www.google.com/doodles/json/\" + str(y) + \"/\" + str(m + 1) + \"?hl=zh_TW\"\n response = urlopen(url)\n # print(response.read()) read讀完就會去掉裡面的資料,若讀第二次就是空的\n doodles = json.load(response) # 轉成python格式\n for d in doodles:\n url = \"https:\" + d[\"url\"]\n # print(d[\"title\"], url)\n # print(url.split(\"/\")[-1]) # 把url分割然後只取最後一段\n dirname = \"doodles/\" + str(y) + \"/\" + str(m + 1) + \"/\"\n path = dirname + url.split(\"/\")[-1]\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n urlretrieve(url, path) # 下載\n\n","sub_path":"practice/doodles.py","file_name":"doodles.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"625934105","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 7 13:25:57 2018\n\n@author: zhan\n\n需要第三方包:python-kafka, scikit learn\n\"\"\"\n\nimport cluster \nfrom sklearn.externals import joblib\nimport argparse\nfrom kafka import KafkaConsumer\n\n\ndef _get_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('-p', '--pkl', required=True, help='path to pkl file') \n parser.add_argument('-H', '--host', help='host ip for database')\n parser.add_argument('-P', '--port', help='port for database', default='8086')\n parser.add_argument('-u', '--user', help='user name for database', default='root')\n parser.add_argument('-w', '--password', help='password for database', default='root') \n parser.add_argument('-s', '--source', help='broker that data is from,like kafka', default='localhost:9092') \n parser.add_argument('-t', '--topic', required=True, help='topic from kafka')\n args = parser.parse_args()\n return args\n\n\n#model = joblib.load(r\"C:/zhanghan/wzw/aiops/data/a.log.pkl\")\n#print(\"len_std=\", model.len_std)\n#print(\"len_mean=\", model.len_mean)\n#print(\"ratio_std=\", model.ratio_std) \n#print(\"ratio_mean=\", model.ratio_mean)\n\n#\n#log='{\"log\":\"bird: BGP: Unexpected connect from unknown address 10.252.21.153 (port 27467)\\n\",\"stream\":\"stdout\",\"hostname\":\"core-cmhadoop5-2\",\"container_log_file\":\"calico-node-lmcsz_kube-system_calico-node-d3fcbf92d8c09506a8493dfffeedd730543ec50b4e31564921444ef65ebd0a71\"}'\n#log='{\"log\":\"2018-06-01 01:00:05.229 [INFO][176] health.go 150: Overall health summary=&health.HealthReport{Live:true, Ready:true}\\n\",\"stream\":\"stdout\",\"hostname\":\"core-cmhadoop5-2\",\"container_log_file\":\"calico-node-lmcsz_kube-system_calico-node-d3fcbf92d8c09506a8493dfffeedd730543ec50b4e31564921444ef65ebd0a71\"}'\n#log='{\"log\":\"2018-06-01 01:00:07.282 [INFO][176] int_dataplane.go 690: Applying dataplane updates\\n\",\"stream\":\"stdout\",\"hostname\":\"core-cmhadoop5-2\",\"container_log_file\":\"calico-node-lmcsz_kube-system_calico-node-d3fcbf92d8c09506a8493dfffeedd730543ec50b4e31564921444ef65ebd0a71\"}'\n#df = cluster.import_sample_json(log)\n#print(df)\n#df = cluster.extract_feature(df, cluster.TXT_REF)\n#X,df = cluster.make_X(df, \n# len_mean=model.len_mean, \n# len_std=model.len_std,\n# ratio_mean=model.ratio_mean, \n# ratio_std=model.ratio_std)\n#print(\"***********\")\n#print(X)\n#labels = model.predict(X)\n#df[\"label\"] = labels\n#print(df)\n \n#'123.206.41.161:9092'\n\nif __name__ == '__main__':\n args = _get_args() \n model = joblib.load(args.pkl)\n \n \n print(\"len_std=\", model.len_std)\n print(\"len_mean=\", model.len_mean)\n print(\"ratio_std=\", model.ratio_std) \n print(\"ratio_mean=\", model.ratio_mean) \n \n print(\"start\")\n consumer = KafkaConsumer(args.topic, bootstrap_servers=[args.source])\n print(\"receiving\")\n for msg in consumer:\n print (msg.value.decode())\n df = cluster.import_sample_json(msg.value.decode())\n df = cluster.extract_feature(df, cluster.TXT_REF)\n X,df = cluster.make_X(df, \n len_mean=model.len_mean, \n len_std=model.len_std,\n ratio_mean=model.ratio_mean, \n ratio_std=model.ratio_std)\n print(\"***********\")\n print(X)\n labels = model.predict(X)\n df[\"label\"] = labels\n \n try:\n if args.host != None:\n print(\"save to database\")\n df[\"log\"] = df[\"log\"].str.replace('\"', r'\\\"' )\n cluster.save_to_db(df, host=args.host, port=args.port, table_name=\"log_cluster\",\n user=args.user, password=args.password) \n print(df)\n except Exception as e:\n print(str(e))","sub_path":"1/predict-kafka.py","file_name":"predict-kafka.py","file_ext":"py","file_size_in_byte":3839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"166972392","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\n\nimport os\n\nfrom eduid_common.config.parsers.ini import IniConfigParser\ntry:\n # Do not force applications that does not use EtcdConfigParser to have yaml and etcd installed\n from eduid_common.config.parsers.etcd import EtcdConfigParser\nexcept ImportError:\n EtcdConfigParser = None\nfrom eduid_common.config.parsers.exceptions import ParserException\n\n__author__ = 'lundberg'\n\n\nclass ConfigParser(object):\n \"\"\"\n Load config based on environment variable\n \"\"\"\n\n def __new__(cls, **kwargs):\n \"\"\"\n Load the type of config parser based on environment variables EDUID_CONFIG_NS or\n EDUID_INI_FILE_NAME.\n\n EDUID_CONFIG_NS initilizes EtcdConfigParser\n EDUID_CONFIG_FILE_NAME initializes IniConfigParser\n \"\"\"\n ns = os.environ.get('EDUID_CONFIG_NS')\n ini_file_name = os.environ.get('EDUID_INI_FILE_NAME')\n if ns:\n return EtcdConfigParser(ns, **kwargs)\n elif ini_file_name:\n return IniConfigParser(ini_file_name, **kwargs)\n raise ParserException('No environment variable for config initialization found')\n\n def read_configuration(self):\n \"\"\"\n :return: Configuration\n :rtype: dict\n \"\"\"\n raise NotImplementedError()\n","sub_path":"src/eduid_common/config/parsers/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"428926911","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jul 27 16:20:29 2019\r\n\r\n@author: pitonhik\r\n\"\"\"\r\nimport os\r\nimport pandas as pd\r\nimport math\r\nimport statistics as st\r\nr ={}\r\nmark_mas=[]\r\nsvodka = {}\r\nw1 = 1\r\nw2 = 1\r\nw3 =1\r\nw4 =1\r\nw5 =1\r\nw6 =1\r\nw7 =1\r\ndef per(xm1,ym1,xmax1,ymax1,xm2,ym2,xmax2,ymax2):\r\n left = max(xm1,xm2)\r\n top = min(ymax1,ymax2)\r\n right= min(xmax1,xmax2)\r\n bot = max(ym1,ym2)\r\n wight = right - left\r\n h = top - bot\r\n #print(wight<0)\r\n #print(h<0)\r\n if wight < 0 or h < 0 :\r\n #print(wight < 0 or h < 0)\r\n return 'false'\r\n return wight * h\r\ndef mark(xm1,ym1,xmax1,ymax1,xm2,ym2,xmax2,ymax2):\r\n p = per(xm1,ym1,xmax1,ymax1,xm2,ym2,xmax2,ymax2)\r\n if p == 'false':\r\n return 0\r\n elif p == 5:\r\n return 1\r\n s2 = (max(xmax2,xm2) - min(xmax2,xm2))*(max(ymax2,ym2) - min(ymax2,ym2))\r\n s1 = (max(xmax1,xm1) - min(xmax1,xm1))*(max(ymax1,ym1) - min(ymax1,ym1))\r\n s = s1+s2 - p\r\n if s ==0:\r\n return 1\r\n mark = p / s\r\n return mark\r\ntr_data =pd.read_csv('train_data.csv',sep=',')\r\ntr_ans = pd.read_csv('train_answers.csv',sep=',')\r\nid_ob = [] #объект уникальных id обьектов \r\nfor i in range(len(tr_data)):\r\n if not (tr_data['itemId'][i] in id_ob):\r\n id_ob.append(tr_data['itemId'][i])\r\nid_p =[] #объект уникальных id людей из тестовых выборок\r\nfor j in range(len(tr_data)):\r\n if not (tr_data['userId'][j] in id_p):\r\n id_p.append(tr_data['userId'][j])\r\nts = pd.read_csv('test_data.csv',sep=',')\r\n#loc[] обращение по индексу\r\ndp ={}\r\ncl_p =[]\r\ndef sred_rast(mas):\r\n #med = st.median(mas)\r\n mas.sort()\r\n rast = []\r\n sr = 0\r\n if len(mas)==1:\r\n return 0\r\n for i in range(len(mas)-1):\r\n \r\n rast.append(mas[i+1]-mas[i])\r\n \r\n \r\n sr = sred(rast)\r\n #print(sr)\r\n med = st.median(mas)\r\n #print(med)\r\n return 1 - (sr / med)\r\ndef dlina(mas):\r\n d = len(mas)\r\n d = 1 / d\r\n return 1 - d\r\ndef sred(a):\r\n s =0 \r\n for i in range(len(a)):\r\n s = s+ a[i]\r\n res = s/ len(a)\r\n return(res)\r\ndef newrad(mas):\r\n nm =[]\r\n res = []\r\n mas.sort()\r\n if len(mas)==1:\r\n res.append(mas)\r\n return res\r\n for i in range(len(mas)-1):\r\n nm.append(mas[i+1]-mas[i])\r\n \r\n m = sred(nm)\r\n q=0\r\n for i in range(len(nm)):\r\n if nm[i]> m :\r\n \r\n newm = []\r\n newm = mas[q:i+1]\r\n q = i+1\r\n res.append(newm)\r\n del(newm)\r\n res.append(mas[q:len(mas)])\r\n return res\r\ndef naib_v(mas):\r\n m = newrad(mas)\r\n r = 0\r\n l = 0\r\n le = []\r\n s = 0\r\n for i in range(len(m)): \r\n le.append(len(m[i]))\r\n ma = max(le)\r\n if len(mas)==1:\r\n return mas[0]\r\n elif le.count(ma)==1:\r\n return sred(m[le.index(ma)])\r\n else:\r\n kol = le.count(ma)\r\n for i in range(kol):\r\n s = s + sred(m[le.index(ma)])\r\n m.remove(m[le.index(ma)])\r\n le.remove(ma)\r\n return s / kol\r\ndef srez(df,name):\r\n cl = []\r\n for i in range(len(df)):\r\n idf = df.index[i]\r\n \r\n cl.append(df[name].loc[idf])\r\n return cl\r\ndef my_print(ids):\r\n print('/-/-/-/-/-/-/-/-/')\r\n data = tr_data[tr_data['itemId']==ids]\r\n print(data)\r\n print('--------')\r\n data = tr_ans[tr_ans['itemId']==ids]\r\n print(data)\r\n \r\ndef new_pipl_filt():\r\n #print('/--/')\r\n c =[]\r\n for i in range(len(id_p)):\r\n \r\n pipl = id_p[i]\r\n pa = tr_data[tr_data['userId']==pipl]\r\n m = []\r\n for j in range(len(pa)):\r\n ind = pa.index[j]\r\n xm1 = pa['Xmin'].loc[ind]\r\n ym1 = pa['Ymin'].loc[ind]\r\n xmax1 = pa['Xmax'].loc[ind]\r\n ymax1 = pa['Ymax'].loc[ind]\r\n otv = tr_ans[tr_ans['itemId']==pa['itemId'].loc[ind]]\r\n #print(otv)\r\n ind2 = otv['Xmin_true'].index[0]\r\n xm2=otv['Xmin_true'].loc[ind2]\r\n ym2=otv['Ymin_true'].loc[ind2]\r\n xmax2=otv['Xmax_true'].loc[ind2]\r\n ymax2=otv['Ymax_true'].loc[ind2]\r\n mar = mark(xm1,ym1,xmax1,ymax1,xm2,ym2,xmax2,ymax2)\r\n m.append(mar)\r\n rez = {}\r\n rez['id']=pipl\r\n rez['mas']=m\r\n rez['sred']=sred(m)\r\n rez['med']=st.median(m)\r\n rez['min']= min(m)\r\n rez['max']= max(m)\r\n c.append(rez)\r\n del(rez)\r\n \r\n return c\r\ndef pipl_metrik():\r\n global pip\r\n global w1\r\n global w2\r\n global w3\r\n global w4\r\n w1= 0\r\n for i in range(len(pip)):\r\n dlin = dlina(pip[i]['mas'])\r\n mi = pip[i]['min']\r\n #print(pip[i]['mas'])\r\n ver = naib_v(pip[i]['mas'])\r\n med = pip[i]['med']\r\n metrika = w1*dlin + 1*mi + 2*ver + 1 * med\r\n pip[i]['metr']=metrika / 3\r\npip = new_pipl_filt()\r\npipl_metrik()\r\ndef new_sr_sr():\r\n if True:\r\n global svodka\r\n global mark_mas\r\n global r\r\n global id_ob\r\n global tr_ans\r\n global id_p\r\n global pip\r\n for i in range(len(id_ob)):\r\n ot = [0,0,0,0]\r\n ob = id_ob[i]\r\n t = tr_data[tr_data['itemId']==ob]\r\n work = []\r\n work.append(srez(t,'userId'))\r\n work.append([ob])\r\n work.append(srez(t,'Xmin'))\r\n work.append(srez(t,'Ymin'))\r\n work.append(srez(t,'Xmax'))\r\n work.append(srez(t,'Ymax'))\r\n work_test = []\r\n work_test.append(srez(t,'Xmin'))\r\n work_test.append(srez(t,'Ymin'))\r\n work_test.append(srez(t,'Xmax'))\r\n work_test.append(srez(t,'Ymax'))\r\n w8=1\r\n obl_x = newrad(work[2])\r\n obl_y = newrad(work[3])\r\n obl_xm = newrad(work[4])\r\n obl_ym = newrad(work[5])\r\n mas_o_x = obl(obl_x,work[2],work[0])\r\n mas_o_y = obl(obl_y,work[3],work[0])\r\n mas_o_xm = obl(obl_xm,work[4],work[0])\r\n mas_o_ym = obl(obl_ym,work[5],work[0])\r\n \r\n #for j in range(len(best_x)):\r\n \r\n \r\n xe = oblast(mas_o_x,obl_x)\r\n ye = oblast(mas_o_y,obl_y)\r\n xme =oblast(mas_o_xm,obl_xm)\r\n yme =oblast(mas_o_ym,obl_ym)\r\n masp =[]\r\n for j in range(len(work[0])):\r\n if work[0][j] in id_p:\r\n masp.append(ret_pm(work[0][j]))\r\n if len(masp)==0:\r\n for i in range(len(work[0])):\r\n p ={}\r\n p['id']=work[0][i]\r\n p['metr']=0\r\n pip.append(p)\r\n del(p)\r\n elif len(masp)>0:\r\n for i in range(len(work[0])):\r\n if not(work[0][i] in id_ob):\r\n p ={}\r\n p['id']=work[0][i]\r\n p['metr']=sred(masp)\r\n pip.append(p)\r\n del(p)\r\n bp = max(masp)\r\n #print(masp)\r\n pind = masp.index(bp)\r\n bpx = work_test[0][pind]\r\n #print(bpx)\r\n bpy = work_test[1][pind]\r\n #print(bpy)\r\n bpxm = work_test[2][pind]\r\n bpym = work_test[3][pind]\r\n mark1 = mark(xe,ye,xme,yme,bpx,bpy,bpxm,bpym)\r\n #print(mark1)\r\n if mark1 > 0.9:\r\n ot[0]= xe\r\n ot[1]= ye\r\n ot[2]= xme\r\n ot[3]= yme\r\n \r\n \r\n else:\r\n ot[0]= bpx + xe\r\n ot[0] = int(ot[0]/2)\r\n ot[1]= bpy + ye\r\n ot[1] = int(ot[1]/2)\r\n ot[2]= bpxm + xme\r\n ot[2] = int(ot[2]/2)\r\n ot[3]= bpym + yme\r\n ot[3] = int(ot[3]/2)\r\n if len(work[0])< 4:\r\n ot[0]= xe\r\n ot[1]= ye\r\n ot[2]= xme\r\n ot[3]= yme\r\n ans = tr_ans[tr_ans['itemId']==ob]\r\n \r\n io = ans.index[0]\r\n \r\n x = ans['Xmin_true'].loc[io]\r\n \r\n y = ans['Ymin_true'].loc[io]\r\n xm = ans['Xmax_true'].loc[io]\r\n ym = ans['Ymax_true'].loc[io]\r\n mg = mark(ot[0],ot[1],ot[2],ot[3],x,y,xm,ym)\r\n \r\n \"\"\"if mg < 0.5:\r\n r[str(ob)]=mg\"\"\"\r\n mark_mas.append(mg)\r\n svodka[str(ob)]= {}\r\n svodka[str(ob)]['piple']=[work[0]]\r\n svodka[str(ob)]['xmin']=work_test[0]\r\n svodka[str(ob)]['ymin']=work_test[1]\r\n svodka[str(ob)]['xmax']=work_test[2]\r\n svodka[str(ob)]['ymax']=work_test[3]\r\n svodka[str(ob)]['X_grup']= obl_x\r\n svodka[str(ob)]['Y_grup']= obl_y\r\n svodka[str(ob)]['Xm_grup']= obl_xm\r\n svodka[str(ob)]['Ym_grup']= obl_ym\r\n svodka[str(ob)]['xmin_v']=ot[0]\r\n svodka[str(ob)]['ymin_v']=ot[1]\r\n svodka[str(ob)]['xmax_v']=ot[2]\r\n svodka[str(ob)]['ymax_v']=ot[3]\r\n svodka[str(ob)]['ver']=mg\r\n svodka[str(ob)]['xmin_v_TRUE']=x\r\n svodka[str(ob)]['ymin_v_TRUE']=y\r\n svodka[str(ob)]['xmax_v_TRUE']=xm\r\n svodka[str(ob)]['ymax_v_TRUE']=ym\r\n pi_m =[]\r\n for j in range(len(work[0])):\r\n pi_m.append(ret_pm_inf(work[0][j]))\r\n svodka[str(ob)]['piple_ym']=pi_m\r\n del(pi_m)\r\n if mg < 0.5 and mg > 0.4:\r\n r[str(ob)] = mg\r\n \r\n del(work)\r\n del(work_test)\r\ndef oblast(mas_o_x,obl_x):\r\n best_x = newrad_2(mas_o_x)\r\n sre = 0\r\n sre_i = 0\r\n for j in range(len(best_x)):\r\n if sred(best_x[j]) > sre:\r\n sre = sred(best_x[j])\r\n sre_i = j\r\n if len(best_x) == 1:\r\n mac = max(best_x[0])\r\n mas_in = mas_o_x.index(mac)\r\n obx = obl_x[mas_in]\r\n return sred(obx)\r\n if len(best_x[sre_i])==1:\r\n mas_in = mas_o_x.index(best_x[sre_i])\r\n obx = obl_x[mas_in]\r\n else:\r\n \r\n obx = []\r\n for j in range(len(best_x[sre_i])):\r\n mas_in = mas_o_x.index(best_x[sre_i][j])\r\n for g in range(len(obl_x[mas_in])):\r\n \r\n obx.append(obl_x[mas_in][g])\r\n #print('---') \r\n return sred(obx)\r\n \r\ndef obl(mas_obl,mas,mas_p):\r\n global pip\r\n global w5\r\n global w6\r\n global w7\r\n \r\n rez =[]\r\n j = 0\r\n for i in range(len(mas_obl)):\r\n dlin = dlina(mas_obl[i])\r\n #print(mas_obl[i])\r\n sr_r = sred_rast(mas_obl[i])\r\n sum_p = 0\r\n \r\n for j in range(len(mas_obl[i])):\r\n ind = mas.index(mas_obl[i][j])\r\n piple = mas_p[ind]\r\n #print(piple)\r\n sum_p = sum_p + ret_pm(piple)\r\n sum_p = sum_p / len(mas_obl[i])\r\n metrika = 1*dlin + 2*sr_r + 0.5*sum_p\r\n rez.append(metrika)\r\n return rez\r\n \r\n \r\ndef ret_pm(a):\r\n global pip\r\n for i in range(len(pip)):\r\n if pip[i]['id']==a:\r\n return pip[i]['metr']\r\ndef ret_pm_inf(a):\r\n global pip\r\n for i in range(len(pip)):\r\n if pip[i]['id']==a:\r\n return pip[i]\r\n'''trem = [0,0,0,0,0,0,0,0]\r\nfor i1 in range(10):\r\n #w1=1 * (i1+1)\r\n for i2 in range(10):\r\n #w2=0.6 * (i2+1)\r\n for i3 in range(10):\r\n #w3=5 * (i3 +1)\r\n for i4 in range(10):\r\n #w4=0.4 * (i4+1)\r\n for i5 in range(10):\r\n #w5=0.5 * (i5 +1)\r\n for i6 in range(10):\r\n \r\n for i7 in range(10):\r\n \r\n w4=w4 +0.1\r\n pip = new_pipl_filt()\r\n pipl_metrik()\r\n new_sr_sr()\r\n print(sred(mark_mas))\r\n print(w4)\r\n if sred(mark_mas)>trem[0]:\r\n trem[0]=sred(mark_mas)\r\n trem[1]=w1\r\n trem[2]=w2\r\n trem[3]=w3\r\n trem[4]=w4\r\n trem[5]=w5\r\n trem[6]=w6\r\n trem[7]=w7\r\n \r\n #print(trem)\r\n print(trem)\r\n print(trem)\r\n \r\n print(trem)\r\n \r\nprint(trem) ''' \r\ndef newrad_2(mas):\r\n nm =[]\r\n res = []\r\n mase = []\r\n for i in range(len(mas)):\r\n mase.append(mas[i])\r\n mase.sort()\r\n if len(mase)==1:\r\n res.append(mase)\r\n return res\r\n for i in range(len(mase)-1):\r\n nm.append(mase[i+1]-mase[i])\r\n \r\n m = sred(nm)\r\n q=0\r\n for i in range(len(nm)):\r\n if nm[i]> m :\r\n \r\n newm = []\r\n newm = mase[q:i+1]\r\n q = i+1\r\n res.append(newm)\r\n del(newm)\r\n res.append(mase[q:len(mase)])\r\n return res\r\nnew_sr_sr()\r\nprint(sred(mark_mas)) ","sub_path":"metriks.py","file_name":"metriks.py","file_ext":"py","file_size_in_byte":11873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"538743885","text":"import numpy as np \r\nimport cv2\r\n\r\n#start cam and haar cascade\r\ncam = cv2.VideoCapture(0)\r\nface_cas = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml') #create a haar-cascade object for face detection. haarcascade has features that it extracts. we are not extracting the features rn tho, just using the algorithm. \r\nfont = cv2.FONT_HERSHEY_SIMPLEX\r\n\r\nf_01 = np.load('face_01.npy').reshape((20, 50*50*3)) #linearising into one matrix\r\nf_02 = np.load('face_02.npy').reshape((12, 50*50*3))\r\nf_03 = np.load('face_03.npy').reshape((20, 50*50*3))\r\n\r\nprint (f_01.shape, f_02.shape, f_03.shape)\r\n\r\nnames = {\r\n 0: 'Pratyush',\r\n 1: 'Ankita',\r\n 2: 'Anju', \r\n}\r\n\r\nlabels = np.zeros((52,1))\r\nlabels[:20, : ] = 0.0\r\nlabels[20:32, :] = 1.0\r\nlabels[32:, :] = 2.0\r\n\r\ndata = np.concatenate([f_01, f_02, f_03])\r\nprint(data.shape,labels.shape)\r\n\r\ndef distance(x1,x2):\r\n return np.sqrt(((x1-x2)**2).sum())\r\n\r\ndef knn(x, train, targets,k=5): \r\n m = train.shape[0]\r\n dist = []\r\n \r\n for ix in range(m): \r\n dist.append(distance(x, train[ix]))\r\n \r\n dist = np.asarray(dist)\r\n # Lets us pick up top K values\r\n indx = np.argsort(dist)\r\n sorted_labels = labels[indx][:k]\r\n counts = np.unique(sorted_labels, return_counts = True)\r\n \r\n return counts[0][np.argmax(counts[1])]\r\n\r\n\r\n\r\nwhile True:\r\n #get each frame\r\n ret, frame = cam.read()\r\n # convert to grayscale and get faces\r\n if ret == True:\r\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n faces = face_cas.detectMultiScale(gray, 1.3, 5)\r\n # for each frame\r\n for(x,y,w,h) in faces:\r\n face_component = frame[y:y+h, x:x+w, :]\r\n fc = cv2.resize(face_component, (50,50))\r\n\r\n # after processing the image and rescaling\r\n # convert to linear vector using flatten()\r\n # and pass to knn along with data\r\n\r\n lab = knn(fc.flatten(), data, labels) #flatten converts a matrix to linear vector\r\n text = names[int(lab)] # convert this label to int and get corresponding name\r\n cv2.putText(frame, text, (x,y), font, 1, (255,255,0), 2) #onts width, colour etc\r\n\r\n cv2.rectangle(frame, (x,y), (x+w,y+h), (0,0,255),2)\r\n cv2.imshow('frame', frame)\r\n\r\n if cv2.waitKey(1) == 27:\r\n break \r\n else:\r\n print(\"error\")","sub_path":"FaceRecogFinal.py","file_name":"FaceRecogFinal.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"500884485","text":"balance = 320000\nannualInterestRate = 0.2\ncalceval = 1\nmonth = 0\nprebalance = balance\nincrease = .01\ninterest = annualInterestRate / 12\nnobalance = False\nlowerbound = prebalance / 12\nupperbound = (prebalance + (annualInterestRate * prebalance)) // 12\nmiddlebound = (upperbound + lowerbound) // 2\n\n\ndef monthcalc(prebalance, payment, month):\n while month < 12:\n prebalance = prebalance - payment\n prebalance = prebalance + (interest * prebalance)\n month = month + 1\n return prebalance\n\n\nwhile calceval !=0:\n calceval = monthcalc(prebalance, middlebound, month)\n if calceval < 0:\n middlebound = (middlebound + lowerbound) // 2\n elif calceval > 0:\n middlebound = (middlebound + upperbound) // 2\n\nprint(\"Lowest Payment: \", round(middlebound, 2))","sub_path":"creditcard_fixed.py","file_name":"creditcard_fixed.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"203560197","text":"# -- -- -- -- -- -- -- -- -- -- -- -- --\n# ICT CAT Term 4, 2019\n# Category A - Problem 4: Alphabet Values (Difficulty: ****)\n# https://github.com/mikejzx/py-ictcat\n#\n# -- -- -- -- -- -- -- -- -- -- -- -- --\n# If A = 1, B = 2, C = 3, and so on, we \n# can find the number value of a word. For \n# example “ROBOT” = 18 + 15 + 2 + 15 + 20 = 70. \n# Write a program that prints the number value \n# of an input word. (Hint: ord('A'.lower())-96 = 1).\n# -- -- -- -- -- -- -- -- -- -- -- -- --\n\n# Constants\nVALID_CHARS = \"abcdefghijklmnopqrstuvwxyz\"\n\n# Get x's position in the alphabet from 1-26.\ndef get_alphabet_pos(x):\n # Bit-masking an ASCII value with 0x1F gives us\n # Only the bits we are interested in.\n # In binary it appears: 0001 1111\n # Bit-wise operations are faster to run on \n # CPU than a subtraction. (Or should be at least...)\n return ord(x) & 0x1F\n\n# Get the alphabet position sum of each character in data.\ndef get_word_value(data):\n # Compute the sum.\n sum = 0\n for i in data:\n # Check that this letter is in the alphabet.\n if i not in VALID_CHARS:\n # If not, just skip this iteration.\n continue\n\n # Get the number at this position and add to sum.\n sum += get_alphabet_pos(i)\n return sum\n\n# Get input, compute sum, and print.\nprint(\"-- Alphabet Values --\")\nwhile True:\n print(\"Value: \", get_word_value(input(\"Enter a string you wish to get the value of.\\n\").lower()))","sub_path":"a4_alpha_vals.py","file_name":"a4_alpha_vals.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"469913289","text":"from .doc import Doc\nfrom .vocab import Vocab\nfrom .underscore import Underscore\n\nfrom syft.generic.object import AbstractObject\nfrom syft.workers.base import BaseWorker\nfrom syft.generic.string import String\n\nimport pickle\nfrom typing import List, Union\n\n\nclass TokenMeta(object):\n \"\"\"This class holds some meta data about a token from the text held by a Doc object.\n This allows to create a Token object when needed.\n \"\"\"\n\n def __init__(self, start_pos: int, end_pos: int, space_after: bool, is_space: bool):\n \"\"\"Initializes a TokenMeta object\n\n Args:\n start_pos (int): The start index of the token in the Doc text.\n end_pos (int): The end index of the token in the Doc text (the end index is\n part of the token).\n space_after (bool): Whether the token is followed by a single white \n space (True) or not (False).\n is_space (bool): Whether the token itself is composed of only white \n spaces (True) or not (false).\n\n \"\"\"\n\n self.start_pos = start_pos\n self.end_pos = end_pos\n self.space_after = space_after\n self.is_space = is_space\n\n # Initialize the Underscore object (inspired by spaCy)\n # This object will hold all the custom attributes set\n # using the `self.set_attribute` method\n self._ = Underscore()\n\n\nclass Tokenizer(AbstractObject):\n def __init__(\n self,\n vocab: Union[Vocab, str],\n id: int = None,\n owner: BaseWorker = None,\n client_id: str = None,\n tags: List[str] = None,\n description: str = None,\n ):\n \"\"\"Initialize the Tokenizer object\n \n Args:\n vocab (str or Vocab object) : If str, this should be the name of the language model \n to build the Vocab object from. such as 'en_core_web_lg' . This is useful when\n the Tokenizer object is sent to a remote worker. So it can rebuild\n its Vocab object from scratch instead of send the Vocab object to\n the remote worker which might take too much network traffic.\n \n id (int) : The id of the Tokenizer object.\n owner (BaseWorker) : The worker on which the Tokenizer object lives.\n client_id (str) : The id of the worker on which the Language object using this\n Tokenizer lives.\n tags (list of str) : Tags to attach to the current Tokenizer.\n description (str) : A description of this Tokenizer object.\n \"\"\"\n\n if isinstance(vocab, Vocab):\n self.vocab = vocab\n else:\n self.vocab = Vocab(model_name=vocab)\n\n # If the client id is not specified, then it should be the same as the owner id.\n # This means that the tokenizer and the Language objects live on the same\n # worker.\n if client_id:\n self.client_id = client_id\n else:\n self.client_id = owner.id\n\n super(Tokenizer, self).__init__(\n id=id, owner=owner, tags=tags, description=description\n )\n\n def __call__(self, text: Union[String, str] = None, text_id: int = None):\n \"\"\"The real tokenization procedure takes place here.\n\n As in the spaCy library. This is not exactly equivalent to \n text.split(' '). Because tokens can be whitle spaces if two or\n more consecutive white spaces are found.\n\n Exampele:\n 'I love apples' gives three tokens: 'I', 'love', 'apples'\n 'I love apples ' gives four tokens: 'I', ' ', 'love', 'apples'\n ' I love ' gives three tokens: ' ', 'I', 'love' (yes a single white space\n at the beginning is considered a token)\n\n Tokenizing this ways helps reconstructing the original string\n without loss of white spaces.\n I think that reconstructing the original string might be a good way\n to blindly verify the sanity of the blind tokenization process.\n\n\n Args:\n text (Syft String or str) : The text to be tokenized\n text_id (int) : the text id to be tokenized. The id can be used to get the object\n from the worker registery\n\n \"\"\"\n\n # Either the `text` or the `text_id` should be specified, they cannot be both None\n assert (\n text is not None or text_id is not None\n ), \"`text` and `text_id` cannot be both None\"\n\n # Create a document that will hold meta data of tokens\n # By meta data I mean the start and end positions of each token\n # in the original text, if the token is followed by a white space,\n # if the token itself is composed of white spaces or not, etc ...\n\n # If the text is not specified, then get the text using its id\n if text is None:\n text = self.owner.get_obj(text_id)\n\n doc = Doc(self.vocab, text, owner=self.owner)\n\n # The number of characters in the text\n text_size = len(text)\n\n # Initialize a pointer to the position of the first character of 'text'\n pos = 0\n\n # This is a flag to indicate whether the character we are comparing\n # to is a white space or not\n is_space = text[0].isspace()\n\n # Start tokenization\n for i, char in enumerate(text):\n\n # We are looking for a character that is the opposite of 'is_space'\n # if 'is_space' is True, then we want to find a character that is\n # not a space. and vice versa. This event marks the end of a token.\n is_current_space = char.isspace()\n if is_current_space != is_space:\n\n # Create the TokenMeta object that can be later used to retrieve the token\n # from the text\n token_meta = TokenMeta(\n start_pos=pos,\n end_pos=i - 1,\n space_after=is_current_space,\n is_space=is_space,\n )\n\n # Append the token to the document\n doc.container.append(token_meta)\n\n # Adjust the position 'pos' against which\n # we compare the currently visited chararater\n if is_current_space:\n pos = i + 1\n else:\n pos = i\n\n # Update the character type of which we are searching\n # the opposite (space vs. not space).\n # prevent 'pos' from being out of bound\n if pos < text_size:\n is_space = text[pos].isspace()\n\n # Create the last token if the end of the string is reached\n if i == text_size - 1 and pos <= i:\n\n # Create the TokenMeta object that can be later used to retrieve the token\n # from the text\n token_meta = TokenMeta(\n start_pos=pos,\n end_pos=None, # text[pos:None] ~ text[pos:]\n space_after=is_current_space,\n is_space=is_space,\n )\n\n # Append the token to the document\n doc.container.append(token_meta)\n\n # If the Language object using this tokenizer lives on a different worker\n # (self.client_id != self.owner.id)\n # Then return a DocPointer to the generated doc object\n if self.client_id != self.owner.id:\n\n # Register the Doc in the current worker\n self.owner.register_obj(obj=doc)\n\n # Create a pointer to the above Doc object\n doc_pointer = Doc.create_pointer(\n doc,\n location=self.owner,\n id_at_location=doc.id,\n garbage_collect_data=False,\n )\n\n return doc_pointer\n\n return doc\n\n def send(self, location: BaseWorker):\n \"\"\"Sends this tokenizer object to the worker specified by 'location'. \n and returns a pointer to that tokenizer as a TokenizerPointer object.\n\n Args:\n location: The BaseWorker object to which the tokenizer is to be sent.\n Note that this is never actually the BaseWorker but instead\n a class which inherits the BaseWorker abstraction.\n\n Returns:\n A TokenizerPointer objects to self.\n\n \"\"\"\n\n ptr = self.owner.send(self, location)\n\n return ptr\n\n @staticmethod\n def create_pointer(\n tokenizer,\n location: BaseWorker = None,\n id_at_location: (str or int) = None,\n register: bool = False,\n owner: BaseWorker = None,\n ptr_id: (str or int) = None,\n garbage_collect_data: bool = True,\n ):\n \"\"\"Creates a TokenizerPointer object that points to a Tokenizer object\n living in the worker 'location'.\n\n Returns:\n a TokenizerPointer object\n \"\"\"\n\n # I put the import here in order to avoid circular imports\n from .pointers.tokenizer_pointer import TokenizerPointer\n\n if id_at_location is None:\n id_at_location = tokenizer.id\n\n if owner is None:\n owner = tokenizer.owner\n\n tokenizer_pointer = TokenizerPointer(\n location=location,\n id_at_location=id_at_location,\n owner=owner,\n id=ptr_id,\n garbage_collect_data=garbage_collect_data,\n )\n\n return tokenizer_pointer\n\n @staticmethod\n def simplify(worker, tokenizer: \"Tokenizer\"):\n \"\"\"This method is used to reduce a `Tokenizer` object into a list of simpler objects that can be\n serialized.\n \"\"\"\n\n # Simplify attributes\n client_id = pickle.dumps(tokenizer.client_id)\n tags = [pickle.dumps(tag) for tag in tokenizer.tags] if tokenizer.tags else None\n description = pickle.dumps(tokenizer.description)\n model_name = pickle.dumps(tokenizer.vocab.model_name)\n\n return (tokenizer.id, client_id, tags, description, model_name)\n\n @staticmethod\n def detail(worker: BaseWorker, simple_obj: tuple):\n \"\"\"Create an object of type Tokenizer from the reduced representation in `simple_obj`.\n\n Args:\n worker (BaseWorker) : The worker on which the new Tokenizer object is to be created.\n simple_obj (tuple) : A tuple resulting from the serialized then deserialized returned tuple\n from the `_simplify` static method above.\n\n Returns:\n tokenizer (Tokenizer) : a Tokenizer object\n \"\"\"\n\n # Get the tuple elements\n id, client_id, tags, description, model_name = simple_obj\n\n # Unpickle\n client_id = pickle.loads(client_id)\n tags = [pickle.loads(tag) for tag in tags] if tags else None\n description = pickle.loads(description)\n model_name = pickle.loads(model_name)\n\n # Create the tokenizer object\n tokenizer = Tokenizer(\n vocab=model_name,\n id=id,\n owner=worker,\n client_id=client_id,\n tags=tags,\n description=description,\n )\n\n return tokenizer\n","sub_path":"syfertext/tokenizer.py","file_name":"tokenizer.py","file_ext":"py","file_size_in_byte":11283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"462448777","text":"import os\nimport time\nimport common\nimport subprocess\nimport pytest\n\nfrom common import client, random_labels, volume_name # NOQA\nfrom common import core_api, apps_api, pod # NOQA\nfrom common import SIZE, EXPAND_SIZE\nfrom common import check_device_data, write_device_random_data\nfrom common import check_volume_data, write_volume_random_data\nfrom common import get_self_host_id, volume_valid\nfrom common import iscsi_login, iscsi_logout\nfrom common import wait_for_volume_status\nfrom common import wait_for_volume_delete\nfrom common import wait_for_snapshot_purge\nfrom common import generate_volume_name\nfrom common import get_volume_endpoint, get_volume_engine\nfrom common import check_volume_endpoint\nfrom common import activate_standby_volume, check_volume_last_backup\nfrom common import create_pv_for_volume, create_pvc_for_volume\nfrom common import create_and_wait_pod, delete_and_wait_pod\nfrom common import delete_and_wait_pvc, delete_and_wait_pv\nfrom common import CONDITION_STATUS_FALSE, CONDITION_STATUS_TRUE\nfrom common import RETRY_COUNTS, RETRY_INTERVAL, RETRY_COMMAND_COUNT\nfrom common import cleanup_volume, create_and_check_volume, create_backup\nfrom common import DEFAULT_VOLUME_SIZE\nfrom common import Gi, Mi\nfrom common import wait_for_volume_detached\nfrom common import create_pvc_spec\nfrom common import generate_random_data, write_volume_data\nfrom common import VOLUME_RWTEST_SIZE\nfrom common import write_pod_volume_data\nfrom common import find_backup\nfrom common import wait_for_backup_completion\nfrom common import create_storage_class\nfrom common import wait_for_backup_restore_completed\nfrom common import wait_for_volume_restoration_completed\nfrom common import read_volume_data\nfrom common import pvc_name # NOQA\nfrom common import storage_class # NOQA\nfrom common import pod_make, csi_pv, pvc # NOQA\nfrom common import create_snapshot\nfrom common import expand_attached_volume\nfrom common import wait_for_dr_volume_expansion\nfrom common import check_block_device_size\nfrom common import wait_for_volume_expansion\nfrom common import fail_replica_expansion, wait_for_expansion_failure\nfrom common import wait_for_volume_creation, wait_for_volume_restoration_start\nfrom common import write_pod_volume_random_data, get_pod_data_md5sum\nfrom common import prepare_pod_with_data_in_mb\nfrom common import crash_replica_processes\nfrom common import wait_for_volume_condition_scheduled\nfrom common import wait_for_volume_condition_toomanysnapshots\nfrom common import wait_for_volume_degraded, wait_for_volume_healthy\nfrom common import VOLUME_FRONTEND_BLOCKDEV, VOLUME_FRONTEND_ISCSI\nfrom common import VOLUME_CONDITION_SCHEDULED\nfrom common import MESSAGE_TYPE_ERROR\nfrom common import DATA_SIZE_IN_MB_1\nfrom common import SETTING_REPLICA_NODE_SOFT_ANTI_AFFINITY\nfrom common import CONDITION_REASON_SCHEDULING_FAILURE\nfrom common import delete_backup\nfrom common import delete_backup_volume\nfrom common import BACKUP_BLOCK_SIZE\nfrom common import assert_backup_state\nfrom common import wait_for_backup_delete\nfrom common import VOLUME_FIELD_ROBUSTNESS, VOLUME_FIELD_READY\nfrom common import VOLUME_ROBUSTNESS_HEALTHY, VOLUME_ROBUSTNESS_FAULTED\nfrom common import DATA_SIZE_IN_MB_2, DATA_SIZE_IN_MB_3\nfrom common import wait_for_backup_to_start\n\nfrom backupstore import backupstore_corrupt_backup_cfg_file\nfrom backupstore import backupstore_delete_volume_cfg_file\nfrom backupstore import backupstore_cleanup\nfrom backupstore import backupstore_count_backup_block_files\nfrom backupstore import backupstore_create_dummy_in_progress_backup\nfrom backupstore import backupstore_delete_dummy_in_progress_backup\nfrom backupstore import backupstore_create_file\nfrom backupstore import backupstore_delete_file\nfrom backupstore import set_random_backupstore # NOQA\nfrom backupstore import backupstore_get_backup_volume_prefix\nfrom backupstore import backupstore_wait_for_lock_expiration\n\n\n\n@pytest.mark.coretest # NOQA\ndef test_hosts(client): # NOQA\n \"\"\"\n Check node name and IP\n \"\"\"\n hosts = client.list_node()\n for host in hosts:\n assert host.name is not None\n assert host.address is not None\n\n host_id = []\n for i in range(0, len(hosts)):\n host_id.append(hosts.data[i].name)\n\n host0_from_i = {}\n for i in range(0, len(hosts)):\n if len(host0_from_i) == 0:\n host0_from_i = client.by_id_node(host_id[0])\n else:\n assert host0_from_i.name == \\\n client.by_id_node(host_id[0]).name\n assert host0_from_i.address == \\\n client.by_id_node(host_id[0]).address\n\n\n@pytest.mark.coretest # NOQA\ndef test_settings(client): # NOQA\n \"\"\"\n Check input for settings\n \"\"\"\n\n setting_names = [common.SETTING_BACKUP_TARGET,\n common.SETTING_BACKUP_TARGET_CREDENTIAL_SECRET,\n common.SETTING_STORAGE_OVER_PROVISIONING_PERCENTAGE,\n common.SETTING_STORAGE_MINIMAL_AVAILABLE_PERCENTAGE,\n common.SETTING_DEFAULT_REPLICA_COUNT]\n settings = client.list_setting()\n\n settingMap = {}\n for setting in settings:\n settingMap[setting.name] = setting\n\n for name in setting_names:\n assert settingMap[name] is not None\n assert settingMap[name].definition.description is not None\n\n for name in setting_names:\n setting = client.by_id_setting(name)\n assert settingMap[name].value == setting.value\n\n old_value = setting.value\n\n if name == common.SETTING_STORAGE_OVER_PROVISIONING_PERCENTAGE:\n with pytest.raises(Exception) as e:\n client.update(setting, value=\"-100\")\n assert \"with invalid \"+name in \\\n str(e.value)\n with pytest.raises(Exception) as e:\n client.update(setting, value=\"testvalue\")\n assert \"with invalid \"+name in \\\n str(e.value)\n setting = client.update(setting, value=\"200\")\n assert setting.value == \"200\"\n setting = client.by_id_setting(name)\n assert setting.value == \"200\"\n elif name == common.SETTING_STORAGE_MINIMAL_AVAILABLE_PERCENTAGE:\n with pytest.raises(Exception) as e:\n client.update(setting, value=\"300\")\n assert \"with invalid \"+name in \\\n str(e.value)\n with pytest.raises(Exception) as e:\n client.update(setting, value=\"-30\")\n assert \"with invalid \"+name in \\\n str(e.value)\n with pytest.raises(Exception) as e:\n client.update(setting, value=\"testvalue\")\n assert \"with invalid \"+name in \\\n str(e.value)\n setting = client.update(setting, value=\"30\")\n assert setting.value == \"30\"\n setting = client.by_id_setting(name)\n assert setting.value == \"30\"\n elif name == common.SETTING_BACKUP_TARGET:\n with pytest.raises(Exception) as e:\n client.update(setting, value=\"testvalue$test\")\n assert \"with invalid \"+name in \\\n str(e.value)\n setting = client.update(setting, value=\"nfs://test\")\n assert setting.value == \"nfs://test\"\n setting = client.by_id_setting(name)\n assert setting.value == \"nfs://test\"\n elif name == common.SETTING_BACKUP_TARGET_CREDENTIAL_SECRET:\n setting = client.update(setting, value=\"testvalue\")\n assert setting.value == \"testvalue\"\n setting = client.by_id_setting(name)\n assert setting.value == \"testvalue\"\n elif name == common.SETTING_DEFAULT_REPLICA_COUNT:\n with pytest.raises(Exception) as e:\n client.update(setting, value=\"-1\")\n assert \"with invalid \"+name in \\\n str(e.value)\n with pytest.raises(Exception) as e:\n client.update(setting, value=\"testvalue\")\n assert \"with invalid \"+name in \\\n str(e.value)\n with pytest.raises(Exception) as e:\n client.update(setting, value=\"21\")\n assert \"with invalid \"+name in \\\n str(e.value)\n setting = client.update(setting, value=\"2\")\n assert setting.value == \"2\"\n setting = client.by_id_setting(name)\n assert setting.value == \"2\"\n\n setting = client.update(setting, value=old_value)\n assert setting.value == old_value\n\n\ndef volume_rw_test(dev):\n assert volume_valid(dev)\n data = write_device_random_data(dev)\n check_device_data(dev, data)\n\n\n@pytest.mark.coretest # NOQA\ndef test_volume_basic(client, volume_name): # NOQA\n \"\"\"\n Test basic volume operations:\n\n 1. Check volume name and parameter\n 2. Create a volume and attach to the current node, then check volume states\n 3. Check soft anti-affinity rule\n 4. Write then read back to check volume data\n \"\"\"\n volume_basic_test(client, volume_name)\n\n\ndef volume_basic_test(client, volume_name, base_image=\"\"): # NOQA\n num_hosts = len(client.list_node())\n num_replicas = 3\n\n with pytest.raises(Exception):\n volume = client.create_volume(name=\"wrong_volume-name-1.0\", size=SIZE,\n numberOfReplicas=2)\n volume = client.create_volume(name=\"wrong_volume-name\", size=SIZE,\n numberOfReplicas=2)\n volume = client.create_volume(name=\"wrong_volume-name\", size=SIZE,\n numberOfReplicas=2,\n frontend=\"invalid_frontend\")\n\n volume = create_and_check_volume(client, volume_name, num_replicas, SIZE,\n base_image)\n assert volume.restoreRequired is False\n\n def validate_volume_basic(expected, actual):\n assert actual.name == expected.name\n assert actual.size == expected.size\n assert actual.numberOfReplicas == expected.numberOfReplicas\n assert actual.frontend == VOLUME_FRONTEND_BLOCKDEV\n assert actual.baseImage == base_image\n assert actual.state == expected.state\n assert actual.created == expected.created\n\n volumes = client.list_volume().data\n assert len(volumes) == 1\n validate_volume_basic(volume, volumes[0])\n\n volumeByName = client.by_id_volume(volume_name)\n validate_volume_basic(volume, volumeByName)\n\n lht_hostId = get_self_host_id()\n volume.attach(hostId=lht_hostId)\n volume = common.wait_for_volume_healthy(client, volume_name)\n assert volume.restoreRequired is False\n\n volumeByName = client.by_id_volume(volume_name)\n validate_volume_basic(volume, volumeByName)\n check_volume_endpoint(volumeByName)\n\n # validate soft anti-affinity\n hosts = {}\n for replica in volume.replicas:\n id = replica.hostId\n assert id != \"\"\n hosts[id] = True\n if num_hosts >= num_replicas:\n assert len(hosts) == num_replicas\n else:\n assert len(hosts) == num_hosts\n\n volumes = client.list_volume().data\n assert len(volumes) == 1\n assert volumes[0].name == volume.name\n assert volumes[0].size == volume.size\n assert volumes[0].numberOfReplicas == volume.numberOfReplicas\n assert volumes[0].state == volume.state\n assert volumes[0].created == volume.created\n check_volume_endpoint(volumes[0])\n\n volume = client.by_id_volume(volume_name)\n volume_rw_test(get_volume_endpoint(volume))\n\n volume.detach()\n volume = common.wait_for_volume_detached(client, volume_name)\n assert volume.restoreRequired is False\n\n client.delete(volume)\n wait_for_volume_delete(client, volume_name)\n\n volumes = client.list_volume().data\n assert len(volumes) == 0\n\n\ndef test_volume_iscsi_basic(client, volume_name): # NOQA\n \"\"\"\n Test basic volume operations with iscsi frontend\n\n 1. Create and attach a volume with iscsi frontend\n 2. Check the volume endpoint and connect it using the iscsi\n initator on the node.\n 3. Write then read back volume data for validation\n\n \"\"\"\n volume_iscsi_basic_test(client, volume_name)\n\n\ndef volume_iscsi_basic_test(client, volume_name, base_image=\"\"): # NOQA\n host_id = get_self_host_id()\n volume = create_and_check_volume(client, volume_name, 3, SIZE, base_image,\n VOLUME_FRONTEND_ISCSI)\n volume.attach(hostId=host_id)\n volume = common.wait_for_volume_healthy(client, volume_name)\n\n volumes = client.list_volume().data\n assert len(volumes) == 1\n assert volumes[0].name == volume.name\n assert volumes[0].size == volume.size\n assert volumes[0].numberOfReplicas == volume.numberOfReplicas\n assert volumes[0].state == volume.state\n assert volumes[0].created == volume.created\n assert volumes[0].frontend == VOLUME_FRONTEND_ISCSI\n endpoint = get_volume_endpoint(volumes[0])\n\n try:\n dev = iscsi_login(endpoint)\n volume_rw_test(dev)\n finally:\n iscsi_logout(endpoint)\n\n cleanup_volume(client, volume)\n\n\n@pytest.mark.coretest # NOQA\ndef test_snapshot(client, volume_name, base_image=\"\"): # NOQA\n \"\"\"\n Test snapshot operations\n\n 1. Create a volume and attach to the node\n 2. Create the empty snapshot `snap1`\n 3. Generate and write data `snap2_data`, then create `snap2`\n 4. Generate and write data `snap3_data`, then create `snap3`\n 5. List snapshot. Validate the snapshot chain relationship\n 6. Mark `snap3` as removed. Make sure volume's data didn't change\n 7. List snapshot. Make sure `snap3` is marked as removed\n 8. Detach and reattach the volume in maintenance mode.\n 9. Make sure the volume frontend is still `blockdev` but disabled\n 10. Revert to `snap2`\n 11. Detach and reattach the volume with frontend enabled\n 12. Make sure volume's data is `snap2_data`\n 13. List snapshot. Make sure `volume-head` is now `snap2`'s child\n 14. Delete `snap1` and `snap2`\n 15. Purge the snapshot.\n 16. List the snapshot, make sure `snap1` and `snap3`\n are gone. `snap2` is marked as removed.\n 17. Check volume data, make sure it's still `snap2_data`.\n \"\"\"\n snapshot_test(client, volume_name, base_image)\n\n\ndef snapshot_test(client, volume_name, base_image): # NOQA\n volume = create_and_check_volume(client, volume_name,\n base_image=base_image)\n\n lht_hostId = get_self_host_id()\n volume = volume.attach(hostId=lht_hostId)\n volume = common.wait_for_volume_healthy(client, volume_name)\n\n volume = client.by_id_volume(volume_name)\n positions = {}\n\n snap1 = create_snapshot(client, volume_name)\n\n snap2_data = write_volume_random_data(volume, positions)\n snap2 = create_snapshot(client, volume_name)\n\n snap3_data = write_volume_random_data(volume, positions)\n snap3 = create_snapshot(client, volume_name)\n\n snapshots = volume.snapshotList()\n snapMap = {}\n for snap in snapshots:\n snapMap[snap.name] = snap\n\n assert snapMap[snap1.name].name == snap1.name\n assert snapMap[snap1.name].removed is False\n assert snapMap[snap2.name].name == snap2.name\n assert snapMap[snap2.name].parent == snap1.name\n assert snapMap[snap2.name].removed is False\n assert snapMap[snap3.name].name == snap3.name\n assert snapMap[snap3.name].parent == snap2.name\n assert snapMap[snap3.name].removed is False\n\n volume.snapshotDelete(name=snap3.name)\n check_volume_data(volume, snap3_data)\n\n snapshots = volume.snapshotList(volume=volume_name)\n snapMap = {}\n for snap in snapshots:\n snapMap[snap.name] = snap\n\n assert snapMap[snap1.name].name == snap1.name\n assert snapMap[snap1.name].removed is False\n assert snapMap[snap2.name].name == snap2.name\n assert snapMap[snap2.name].parent == snap1.name\n assert snapMap[snap2.name].removed is False\n assert snapMap[snap3.name].name == snap3.name\n assert snapMap[snap3.name].parent == snap2.name\n assert len(snapMap[snap3.name].children) == 1\n assert \"volume-head\" in snapMap[snap3.name].children.keys()\n assert snapMap[snap3.name].removed is True\n\n snap = volume.snapshotGet(name=snap3.name)\n assert snap.name == snap3.name\n assert snap.parent == snap3.parent\n assert len(snap3.children) == 1\n assert len(snap.children) == 1\n assert \"volume-head\" in snap3.children.keys()\n assert \"volume-head\" in snap.children.keys()\n assert snap.removed is True\n\n volume.detach()\n volume = common.wait_for_volume_detached(client, volume_name)\n\n volume.attach(hostId=lht_hostId, disableFrontend=True)\n common.wait_for_volume_healthy_no_frontend(client, volume_name)\n\n volume = client.by_id_volume(volume_name)\n assert volume.disableFrontend is True\n assert volume.frontend == VOLUME_FRONTEND_BLOCKDEV\n check_volume_endpoint(volume)\n\n volume.snapshotRevert(name=snap2.name)\n\n volume.detach()\n volume = common.wait_for_volume_detached(client, volume_name)\n\n volume.attach(hostId=lht_hostId, disableFrontend=False)\n common.wait_for_volume_healthy(client, volume_name)\n\n volume = client.by_id_volume(volume_name)\n assert volume.disableFrontend is False\n assert volume.frontend == VOLUME_FRONTEND_BLOCKDEV\n\n check_volume_data(volume, snap2_data)\n\n snapshots = volume.snapshotList(volume=volume_name)\n snapMap = {}\n for snap in snapshots:\n snapMap[snap.name] = snap\n\n assert snapMap[snap1.name].name == snap1.name\n assert snapMap[snap1.name].removed is False\n assert snapMap[snap2.name].name == snap2.name\n assert snapMap[snap2.name].parent == snap1.name\n assert \"volume-head\" in snapMap[snap2.name].children.keys()\n assert snap3.name in snapMap[snap2.name].children.keys()\n assert snapMap[snap2.name].removed is False\n assert snapMap[snap3.name].name == snap3.name\n assert snapMap[snap3.name].parent == snap2.name\n assert len(snapMap[snap3.name].children) == 0\n assert snapMap[snap3.name].removed is True\n\n volume.snapshotDelete(name=snap1.name)\n volume.snapshotDelete(name=snap2.name)\n\n volume.snapshotPurge()\n volume = wait_for_snapshot_purge(client, volume_name, snap1.name,\n snap3.name)\n\n snapshots = volume.snapshotList(volume=volume_name)\n snapMap = {}\n for snap in snapshots:\n snapMap[snap.name] = snap\n assert snap1.name not in snapMap\n assert snap3.name not in snapMap\n\n # it's the parent of volume-head, so it cannot be purged at this time\n assert snapMap[snap2.name].name == snap2.name\n assert snapMap[snap2.name].parent == \"\"\n assert \"volume-head\" in snapMap[snap2.name].children.keys()\n assert snapMap[snap2.name].removed is True\n check_volume_data(volume, snap2_data)\n\n cleanup_volume(client, volume)\n\n\ndef test_backup_status_for_unavailable_replicas(client, volume_name): # NOQA\n \"\"\"\n Test backup status for unavailable replicas\n\n Context:\n\n We want to make sure that we do not try to retrieve the backup status\n of no longer valid replicas (offline, deleted, etc). The reason for\n this is that trying to establish a tcp connection with an old replica\n address `(tcp://ip:port)` could block the engine retrieval process,\n since we will wait upto 1 minute for each individual backup status.\n When this happens for a lot of different statuses the manager will\n terminate the started engine retrieval process since the process would\n not have returned in the maximum allowed time. This would then lead\n to no longer being able to show newly created backups in the UI.\n\n Setup:\n\n 1. Create a volume and attach to the current node\n 2. Run the test for all the available backupstores\n\n Steps:\n\n 1. Create a backup of volume\n 2. Find the replica for that backup\n 3. Disable scheduling on the node of that replica\n 4. Delete the replica\n 5. Wait for volume backup status state to go to error\n 6. Verify backup status error contains `unknown replica`\n 7. Create a new backup\n 8. Verify new backup was successful\n 9. Cleanup (delete backups, delete volume)\n \"\"\"\n backup_status_for_unavailable_replicas_test(client, volume_name, SIZE)\n\n\ndef backup_status_for_unavailable_replicas_test(client, volume_name, # NOQA\n size, base_image=\"\"): # NOQA\n volume = create_and_check_volume(client, volume_name, 2, size, base_image)\n\n lht_hostId = get_self_host_id()\n volume = volume.attach(hostId=lht_hostId)\n volume = common.wait_for_volume_healthy(client, volume_name)\n\n setting = client.by_id_setting(common.SETTING_BACKUP_TARGET)\n # test backupTarget for multiple settings\n backupstores = common.get_backupstore_url()\n for backupstore in backupstores:\n if common.is_backupTarget_s3(backupstore):\n backupsettings = backupstore.split(\"$\")\n setting = client.update(setting, value=backupsettings[0])\n assert setting.value == backupsettings[0]\n\n credential = client.by_id_setting(\n common.SETTING_BACKUP_TARGET_CREDENTIAL_SECRET)\n credential = client.update(credential, value=backupsettings[1])\n assert credential.value == backupsettings[1]\n else:\n setting = client.update(setting, value=backupstore)\n assert setting.value == backupstore\n credential = client.by_id_setting(\n common.SETTING_BACKUP_TARGET_CREDENTIAL_SECRET)\n credential = client.update(credential, value=\"\")\n assert credential.value == \"\"\n\n # create a successful backup\n bv, b, _, _ = create_backup(client, volume_name)\n backup_id = b.id\n\n # find the replica for this backup\n volume = client.by_id_volume(volume_name)\n for status in volume.backupStatus:\n if status.id == backup_id:\n replica_name = status.replica\n assert replica_name\n\n # disable scheduling on that node\n volume = client.by_id_volume(volume_name)\n for r in volume.replicas:\n if r.name == replica_name:\n node = client.by_id_node(r.hostId)\n node = client.update(node, allowScheduling=False)\n common.wait_for_node_update(client, node.id,\n \"allowScheduling\", False)\n assert node\n\n # remove the replica with the backup\n volume.replicaRemove(name=replica_name)\n volume = common.wait_for_volume_degraded(client, volume_name)\n\n # now the backup status should be error unknown replica\n def backup_failure_predicate(b):\n return b.id == backup_id and \"unknown replica\" in b.error\n volume = common.wait_for_backup_state(client, volume_name,\n backup_failure_predicate)\n\n # re enable scheduling on the previously disabled node\n node = client.by_id_node(node.id)\n node = client.update(node, allowScheduling=True)\n common.wait_for_node_update(client, node.id,\n \"allowScheduling\", True)\n\n # delete the old backup\n delete_backup(client, bv.name, b.name)\n volume = wait_for_volume_status(client, volume_name,\n \"lastBackup\", \"\")\n assert volume.lastBackupAt == \"\"\n\n # check that we can create another successful backup\n bv, b, _, _ = create_backup(client, volume_name)\n\n # delete the new backup\n delete_backup(client, bv.name, b.name)\n volume = wait_for_volume_status(client, volume_name, \"lastBackup\", \"\")\n assert volume.lastBackupAt == \"\"\n\n cleanup_volume(client, volume)\n\n\ndef test_backup_block_deletion(set_random_backupstore, client, core_api, volume_name): # NOQA\n \"\"\"\n Test backup block deletion\n\n Context:\n\n We want to make sure that we only delete non referenced backup blocks,\n we also don't want to delete blocks while there other backups in progress.\n The reason for this is that we don't yet know which blocks are required by\n the in progress backup, so blocks deletion could lead to a faulty backup.\n\n Setup:\n\n 1. Setup minio as S3 backupstore\n\n Steps:\n\n 1. Create a volume and attach to the current node\n 2. Write 4 MB to the beginning of the volume (2 x 2MB backup blocks)\n 3. Create backup(1) of the volume\n 4. Overwrite the first of the backup blocks of data on the volume\n 5. Create backup(2) of the volume\n 6. Overwrite the first of the backup blocks of data on the volume\n 7. Create backup(3) of the volume\n 8. Verify backup block count == 4\n assert volume[\"DataStored\"] == str(BLOCK_SIZE * expected_count)\n assert count of *.blk files for that volume == expected_count\n 9. Create an artificial in progress backup.cfg file\n json.dumps({\"Name\": name, \"VolumeName\": volume, \"CreatedTime\": \"\"})\n 10. Delete backup(2)\n 11. Verify backup block count == 4 (because of the in progress backup)\n 12. Delete the artificial in progress backup.cfg file\n 13. Delete backup(1)\n 14. Verify backup block count == 2\n 15. Delete backup(3)\n 16. Verify backup block count == 0\n 17. Delete the backup volume\n 18. Cleanup the volume\n \"\"\"\n backupstore_cleanup(client)\n\n volume = create_and_check_volume(client, volume_name)\n host_id = get_self_host_id()\n volume = volume.attach(hostId=host_id)\n volume = common.wait_for_volume_healthy(client, volume_name)\n\n data0 = {'pos': 0,\n 'len': 2 * BACKUP_BLOCK_SIZE,\n 'content': common.generate_random_data(2 * BACKUP_BLOCK_SIZE)}\n\n bv0, backup0, _, _ = create_backup(client, volume_name, data0)\n\n data1 = {'pos': 0,\n 'len': BACKUP_BLOCK_SIZE,\n 'content': common.generate_random_data(BACKUP_BLOCK_SIZE)}\n\n bv1, backup1, _, _ = create_backup(client, volume_name, data1)\n\n data2 = {'pos': 0,\n 'len': BACKUP_BLOCK_SIZE,\n 'content': common.generate_random_data(BACKUP_BLOCK_SIZE)}\n\n bv2, backup2, _, _ = create_backup(client, volume_name, data2)\n\n backup_blocks_count = backupstore_count_backup_block_files(client,\n core_api,\n volume_name)\n assert backup_blocks_count == 4\n\n bvs = client.list_backupVolume()\n\n for bv in bvs:\n if bv['name'] == volume_name:\n assert bv['dataStored'] == \\\n str(backup_blocks_count * BACKUP_BLOCK_SIZE)\n\n backupstore_create_dummy_in_progress_backup(client, core_api, volume_name)\n delete_backup(client, volume_name, backup1.name)\n assert backupstore_count_backup_block_files(client,\n core_api,\n volume_name) == 4\n\n backupstore_delete_dummy_in_progress_backup(client, core_api, volume_name)\n\n delete_backup(client, volume_name, backup0.name)\n assert backupstore_count_backup_block_files(client,\n core_api,\n volume_name) == 2\n\n delete_backup(client, volume_name, backup2.name)\n assert backupstore_count_backup_block_files(client,\n core_api,\n volume_name) == 0\n\n delete_backup_volume(client, volume_name)\n\n\ndef test_backup_volume_list(set_random_backupstore ,client, core_api): # NOQA\n \"\"\"\n Test backup volume list\n Context:\n We want to make sure that an error when listing a single backup volume\n does not stop us from listing all the other backup volumes. Otherwise a\n single faulty backup can block the retrieval of all known backup volumes.\n Setup:\n 1. Setup minio as S3 backupstore\n Steps:\n 1. Create a volume(1,2) and attach to the current node\n 2. write some data to volume(1,2)\n 3. Create a backup(1) of volume(1,2)\n 4. request a backup list\n 5. verify backup list contains no error messages for volume(1,2)\n 6. verify backup list contains backup(1) for volume(1,2)\n 7. place a file named \"backup_1234@failure.cfg\"\n into the backups folder of volume(1)\n 8. request a backup list\n 9. verify backup list contains no error messages for volume(1,2)\n 10. verify backup list contains backup(1) for volume(1,2)\n 11. delete backup volumes(1 & 2)\n 12. cleanup\n \"\"\"\n backupstore_cleanup(client)\n\n # create 2 volumes.\n volume1_name, volume2_name = generate_volume_name(), generate_volume_name()\n\n volume1 = create_and_check_volume(client, volume1_name)\n volume2 = create_and_check_volume(client, volume2_name)\n\n host_id = get_self_host_id()\n volume1 = volume1.attach(hostId=host_id)\n volume1 = common.wait_for_volume_healthy(client, volume1_name)\n volume2 = volume2.attach(hostId=host_id)\n volume2 = common.wait_for_volume_healthy(client, volume2_name)\n\n bv1, backup1, snap1, _ = create_backup(client, volume1_name)\n bv2, backup2, snap2, _ = create_backup(client, volume2_name)\n\n def verify_no_err():\n '''\n request a backup list\n verify backup list contains no error messages for volume(1,2)\n verify backup list contains backup(1) for volume(1,2)\n '''\n for _ in range(RETRY_COUNTS):\n verified_bvs = set()\n backup_volume_list = client.list_backupVolume()\n for bv in backup_volume_list:\n if bv.name in (volume1_name, volume2_name):\n assert not bv['messages']\n for b in bv.backupList().data:\n if bv.name == volume1_name \\\n and b.name == backup1.name \\\n or bv.name == volume2_name \\\n and b.name == backup2.name:\n verified_bvs.add(bv.name)\n if len(verified_bvs) == 2:\n break\n time.sleep(RETRY_INTERVAL)\n assert len(verified_bvs) == 2\n\n verify_no_err()\n\n # place a bad named file into the backups folder of volume(1)\n prefix = \\\n backupstore_get_backup_volume_prefix(client, volume1_name) + \"/backups\"\n backupstore_create_file(client,\n core_api,\n prefix + \"/backup_1234@failure.cfg\")\n\n verify_no_err()\n\n backupstore_delete_file(client,\n core_api,\n prefix + \"/backup_1234@failure.cfg\")\n\n backupstore_cleanup(client)\n\n\ndef test_backup_metadata_deletion(set_random_backupstore, client, core_api, volume_name): # NOQA\n \"\"\"\n Test backup metadata deletion\n\n Context:\n\n We want to be able to delete the metadata (.cfg) files,\n even if they are corrupt or in a bad state (missing volume.cfg).\n\n Setup:\n\n 1. Setup minio as S3 backupstore\n 2. Cleanup backupstore\n\n Steps:\n\n 1. Create volume(1,2) and attach to the current node\n 2. write some data to volume(1,2)\n 3. Create backup(1,2) of volume(1,2)\n 4. request a backup list\n 5. verify backup list contains no error messages for volume(1,2)\n 6. verify backup list contains backup(1,2) information for volume(1,2)\n 7. corrupt backup(1) of volume(1)\n (overwrite) backup1_cfg.write(\"{corrupt: definitely\")\n 8. request a backup list\n 9. verify backup list contains no error messages for volume(1,2)\n 10. verify backup list contains backup(1,2) information for volume(1,2)\n 11. verify backup list backup(1) of volume(1) contains error message\n 12. delete backup(1) of volume(1,2)\n 10. request a backup list\n 11. verify backup list contains no error messages for volume(1,2)\n 12. verify backup list only contains backup(2) information for volume(1,2)\n 13. delete volume.cfg of volume(2)\n 14. request backup volume deletion for volume(2)\n 15. verify that volume(2) has been deleted in the backupstore.\n 16. request a backup list\n 17. verify backup list only contains volume(1) and no errors\n 18. verify backup list only contains backup(2) information for volume(1)\n 19. delete backup volume(1)\n 20. verify that volume(1) has been deleted in the backupstore.\n 21. cleanup\n \"\"\"\n backupstore_cleanup(client)\n\n volume1_name = volume_name + \"-1\"\n volume2_name = volume_name + \"-2\"\n\n host_id = get_self_host_id()\n\n volume1 = create_and_check_volume(client, volume1_name)\n volume2 = create_and_check_volume(client, volume2_name)\n\n volume1.attach(hostId=host_id)\n volume2.attach(hostId=host_id)\n\n volume1 = wait_for_volume_healthy(client, volume1_name)\n volume2 = wait_for_volume_healthy(client, volume2_name)\n\n v1bv, v1b1, _, _ = create_backup(client, volume1_name)\n v2bv, v2b1, _, _ = create_backup(client, volume2_name)\n _, v1b2, _, _ = create_backup(client, volume1_name)\n _, v2b2, _, _ = create_backup(client, volume2_name)\n\n bvs = client.list_backupVolume()\n\n for bv in bvs:\n backups = bv.backupList()\n for b in backups:\n assert b.messages is None\n\n v1b1_new = v1bv.backupGet(name=v1b1.name)\n assert_backup_state(v1b1, v1b1_new)\n\n v1b2_new = v1bv.backupGet(name=v1b2.name)\n assert_backup_state(v1b2, v1b2_new)\n\n v2b1_new = v2bv.backupGet(name=v2b1.name)\n assert_backup_state(v2b1, v2b1_new)\n\n v2b2_new = v2bv.backupGet(name=v2b2.name)\n assert_backup_state(v2b2, v2b2_new)\n\n backupstore_corrupt_backup_cfg_file(client,\n core_api,\n volume1_name,\n v1b1.name)\n\n bvs = client.list_backupVolume()\n\n for bv in bvs:\n if bv.name == volume1_name:\n backups = bv.backupList()\n for b in backups:\n if b.name == v1b1.name:\n assert b.messages is not None\n else:\n assert b.messages is None\n\n v1b2_new = v1bv.backupGet(name=v1b2.name)\n assert_backup_state(v1b2, v1b2_new)\n\n v2b1_new = v2bv.backupGet(name=v2b1.name)\n assert_backup_state(v2b1, v2b1_new)\n\n v2b2_new = v2bv.backupGet(name=v2b2.name)\n assert_backup_state(v2b2, v2b2_new)\n\n delete_backup(client, volume1_name, v1b1.name)\n delete_backup(client, volume2_name, v2b1.name)\n\n bvs = client.list_backupVolume()\n\n for bv in bvs:\n backups = bv.backupList()\n for b in backups:\n assert b.messages is None\n\n assert len(v1bv.backupList()) == 1\n assert len(v2bv.backupList()) == 1\n assert v1bv.backupList()[0].name == v1b2.name\n assert v2bv.backupList()[0].name == v2b2.name\n\n backupstore_delete_volume_cfg_file(client, core_api, volume2_name)\n\n delete_backup(client, volume2_name, v2b2.name)\n assert len(v2bv.backupList()) == 0\n\n delete_backup_volume(client, v2bv.name)\n assert backupstore_count_backup_block_files(client,\n core_api,\n volume2_name) == 0\n\n bvs = client.list_backupVolume()\n for bv in bvs:\n if bv.name == volume1_name:\n backups = bv.backupList()\n for b in backups:\n assert b.messages is None\n\n v1b2_new = v1bv.backupGet(name=v1b2.name)\n assert_backup_state(v1b2, v1b2_new)\n assert v1b2_new.messages == v1b2.messages is None\n\n delete_backup(client, volume1_name, v1b2.name)\n assert backupstore_count_backup_block_files(client,\n core_api,\n volume1_name) == 0\n\n\n@pytest.mark.coretest # NOQA\ndef test_backup(client, volume_name): # NOQA\n \"\"\"\n Test basic backup\n\n Setup:\n\n 1. Create a volume and attach to the current node\n 2. Run the test for all the available backupstores.\n\n Steps:\n\n 1. Create a backup of volume\n 2. Restore the backup to a new volume\n 3. Attach the new volume and make sure the data is the same as the old one\n 4. Detach the volume and delete the backup.\n 5. Wait for the restored volume's `lastBackup` to be cleaned (due to remove\n the backup)\n 6. Delete the volume\n \"\"\"\n backup_test(client, volume_name, SIZE)\n\n\ndef backup_test(client, volume_name, size, base_image=\"\"): # NOQA\n volume = create_and_check_volume(client, volume_name, 2, size, base_image)\n\n lht_hostId = get_self_host_id()\n volume = volume.attach(hostId=lht_hostId)\n volume = common.wait_for_volume_healthy(client, volume_name)\n\n setting = client.by_id_setting(common.SETTING_BACKUP_TARGET)\n # test backupTarget for multiple settings\n backupstores = common.get_backupstore_url()\n for backupstore in backupstores:\n if common.is_backupTarget_s3(backupstore):\n backupsettings = backupstore.split(\"$\")\n setting = client.update(setting, value=backupsettings[0])\n assert setting.value == backupsettings[0]\n\n credential = client.by_id_setting(\n common.SETTING_BACKUP_TARGET_CREDENTIAL_SECRET)\n credential = client.update(credential, value=backupsettings[1])\n assert credential.value == backupsettings[1]\n else:\n setting = client.update(setting, value=backupstore)\n assert setting.value == backupstore\n credential = client.by_id_setting(\n common.SETTING_BACKUP_TARGET_CREDENTIAL_SECRET)\n credential = client.update(credential, value=\"\")\n assert credential.value == \"\"\n\n backupstore_test(client, lht_hostId, volume_name, size)\n\n cleanup_volume(client, volume)\n\n\ndef backupstore_test(client, host_id, volname, size): # NOQA\n bv, b, snap2, data = create_backup(client, volname)\n\n # test restore\n restore_name = generate_volume_name()\n volume = client.create_volume(name=restore_name, size=size,\n numberOfReplicas=2,\n fromBackup=b.url)\n\n volume = common.wait_for_volume_restoration_completed(client, restore_name)\n volume = common.wait_for_volume_detached(client, restore_name)\n assert volume.name == restore_name\n assert volume.size == size\n assert volume.numberOfReplicas == 2\n assert volume.state == \"detached\"\n assert volume.restoreRequired is False\n\n volume = volume.attach(hostId=host_id)\n volume = common.wait_for_volume_healthy(client, restore_name)\n check_volume_data(volume, data)\n volume = volume.detach()\n volume = common.wait_for_volume_detached(client, restore_name)\n\n delete_backup(client, bv.name, b.name)\n volume = wait_for_volume_status(client, volume.name,\n \"lastBackup\", \"\")\n assert volume.lastBackupAt == \"\"\n\n client.delete(volume)\n volume = wait_for_volume_delete(client, restore_name)\n\n\n@pytest.mark.coretest # NOQA\ndef test_backup_labels(client, random_labels, volume_name): # NOQA\n \"\"\"\n Test that the proper Labels are applied when creating a Backup manually.\n\n 1. Create a volume\n 2. Run the following steps on all backupstores\n 3. Create a backup with some random labels\n 4. Get backup from backupstore, verify the labels are set on the backups\n \"\"\"\n backup_labels_test(client, random_labels, volume_name)\n\n\ndef backup_labels_test(client, random_labels, volume_name, size=SIZE, base_image=\"\"): # NOQA\n host_id = get_self_host_id()\n\n volume = create_and_check_volume(client, volume_name, 2, size, base_image)\n\n volume.attach(hostId=host_id)\n volume = common.wait_for_volume_healthy(client, volume_name)\n\n setting = client.by_id_setting(common.SETTING_BACKUP_TARGET)\n # test backupTarget for multiple settings\n backupstores = common.get_backupstore_url()\n for backupstore in backupstores:\n if common.is_backupTarget_s3(backupstore):\n backupsettings = backupstore.split(\"$\")\n setting = client.update(setting, value=backupsettings[0])\n assert setting.value == backupsettings[0]\n\n credential = client.by_id_setting(\n common.SETTING_BACKUP_TARGET_CREDENTIAL_SECRET)\n credential = client.update(credential, value=backupsettings[1])\n assert credential.value == backupsettings[1]\n else:\n setting = client.update(setting, value=backupstore)\n assert setting.value == backupstore\n credential = client.by_id_setting(\n common.SETTING_BACKUP_TARGET_CREDENTIAL_SECRET)\n credential = client.update(credential, value=\"\")\n assert credential.value == \"\"\n\n bv, b, _, _ = create_backup(client, volume_name, labels=random_labels)\n # If we're running the test with a BaseImage, check that this Label is\n # set properly.\n backup = bv.backupGet(name=b.name)\n if base_image:\n assert backup.labels.get(common.BASE_IMAGE_LABEL) == base_image\n # One extra Label from the BaseImage being set.\n assert len(backup.labels) == len(random_labels) + 1\n else:\n assert len(backup.labels) == len(random_labels)\n\n cleanup_volume(client, volume)\n\n\n@pytest.mark.coretest # NOQA\ndef test_restore_inc(client, core_api, volume_name, pod): # NOQA\n \"\"\"\n Test restore from disaster recovery volume (incremental restore)\n\n Run test against all the backupstores\n\n 1. Create a volume and attach to the current node\n 2. Generate `data0`, write to the volume, make a backup `backup0`\n 3. Create three DR(standby) volumes from the backup: `sb_volume0/1/2`\n 4. Wait for all three DR volumes to start the initial restoration\n 5. Verify DR volumes's `lastBackup` is `backup0`\n 6. Verify snapshot/pv/pvc/change backup target are not allowed as long\n as the DR volume exists\n 7. Activate standby `sb_volume0` and attach it to check the volume data\n 8. Generate `data1` and write to the original volume and create `backup1`\n 9. Make sure `sb_volume1`'s `lastBackup` field has been updated to\n `backup1`\n 10. Wait for `sb_volume1` to finish incremental restoration then activate\n 11. Attach and check `sb_volume1`'s data\n 12. Generate `data2` and write to the original volume and create `backup2`\n 13. Make sure `sb_volume2`'s `lastBackup` field has been updated to\n `backup1`\n 14. Wait for `sb_volume2` to finish incremental restoration then activate\n 15. Attach and check `sb_volume2`'s data\n 16. Create PV, PVC and Pod to use `sb_volume2`, check PV/PVC/POD are good\n\n FIXME: Step 16 works because the disk will be treated as a unformatted disk\n \"\"\"\n\n setting = client.by_id_setting(common.SETTING_BACKUP_TARGET)\n # test backupTarget for multiple settings\n backupstores = common.get_backupstore_url()\n for backupstore in backupstores:\n if common.is_backupTarget_s3(backupstore):\n backupsettings = backupstore.split(\"$\")\n setting = client.update(setting, value=backupsettings[0])\n assert setting.value == backupsettings[0]\n\n credential = client.by_id_setting(\n common.SETTING_BACKUP_TARGET_CREDENTIAL_SECRET)\n credential = client.update(credential, value=backupsettings[1])\n assert credential.value == backupsettings[1]\n else:\n setting = client.update(setting, value=backupstore)\n assert setting.value == backupstore\n credential = client.by_id_setting(\n common.SETTING_BACKUP_TARGET_CREDENTIAL_SECRET)\n credential = client.update(credential, value=\"\")\n assert credential.value == \"\"\n\n restore_inc_test(client, core_api, volume_name, pod)\n\n\ndef restore_inc_test(client, core_api, volume_name, pod): # NOQA\n std_volume = create_and_check_volume(client, volume_name, 2, SIZE)\n lht_host_id = get_self_host_id()\n std_volume.attach(hostId=lht_host_id)\n std_volume = common.wait_for_volume_healthy(client, volume_name)\n\n with pytest.raises(Exception) as e:\n std_volume.activate(frontend=VOLUME_FRONTEND_BLOCKDEV)\n assert \"already in active mode\" in str(e.value)\n\n data0 = {'len': 4 * 1024, 'pos': 0}\n data0['content'] = common.generate_random_data(data0['len'])\n bv, backup0, _, data0 = create_backup(\n client, volume_name, data0)\n\n sb_volume0_name = \"sb-0-\" + volume_name\n sb_volume1_name = \"sb-1-\" + volume_name\n sb_volume2_name = \"sb-2-\" + volume_name\n client.create_volume(name=sb_volume0_name, size=SIZE,\n numberOfReplicas=2, fromBackup=backup0.url,\n frontend=\"\", standby=True)\n client.create_volume(name=sb_volume1_name, size=SIZE,\n numberOfReplicas=2, fromBackup=backup0.url,\n frontend=\"\", standby=True)\n client.create_volume(name=sb_volume2_name, size=SIZE,\n numberOfReplicas=2, fromBackup=backup0.url,\n frontend=\"\", standby=True)\n wait_for_backup_restore_completed(client, sb_volume0_name, backup0.name)\n wait_for_backup_restore_completed(client, sb_volume1_name, backup0.name)\n wait_for_backup_restore_completed(client, sb_volume2_name, backup0.name)\n\n sb_volume0 = common.wait_for_volume_healthy_no_frontend(client,\n sb_volume0_name)\n sb_volume1 = common.wait_for_volume_healthy_no_frontend(client,\n sb_volume1_name)\n sb_volume2 = common.wait_for_volume_healthy_no_frontend(client,\n sb_volume2_name)\n\n for i in range(RETRY_COUNTS):\n client.list_backupVolume()\n sb_volume0 = client.by_id_volume(sb_volume0_name)\n sb_volume1 = client.by_id_volume(sb_volume1_name)\n sb_volume2 = client.by_id_volume(sb_volume2_name)\n sb_engine0 = get_volume_engine(sb_volume0)\n sb_engine1 = get_volume_engine(sb_volume1)\n sb_engine2 = get_volume_engine(sb_volume2)\n if sb_volume0.restoreRequired is False or \\\n sb_volume1.restoreRequired is False or \\\n sb_volume2.restoreRequired is False or \\\n not sb_engine0.lastRestoredBackup or \\\n not sb_engine1.lastRestoredBackup or \\\n not sb_engine2.lastRestoredBackup:\n time.sleep(RETRY_INTERVAL)\n else:\n break\n assert sb_volume0.standby is True\n assert sb_volume0.lastBackup == backup0.name\n assert sb_volume0.frontend == \"\"\n assert sb_volume0.restoreRequired is True\n sb_engine0 = get_volume_engine(sb_volume0)\n assert sb_engine0.lastRestoredBackup == backup0.name\n assert sb_engine0.requestedBackupRestore == backup0.name\n assert sb_volume1.standby is True\n assert sb_volume1.lastBackup == backup0.name\n assert sb_volume1.frontend == \"\"\n assert sb_volume1.restoreRequired is True\n sb_engine1 = get_volume_engine(sb_volume1)\n assert sb_engine1.lastRestoredBackup == backup0.name\n assert sb_engine1.requestedBackupRestore == backup0.name\n assert sb_volume2.standby is True\n assert sb_volume2.lastBackup == backup0.name\n assert sb_volume2.frontend == \"\"\n assert sb_volume2.restoreRequired is True\n sb_engine2 = get_volume_engine(sb_volume2)\n assert sb_engine2.lastRestoredBackup == backup0.name\n assert sb_engine2.requestedBackupRestore == backup0.name\n\n sb0_snaps = sb_volume0.snapshotList()\n assert len(sb0_snaps) == 2\n for s in sb0_snaps:\n if s.name != \"volume-head\":\n sb0_snap = s\n assert sb0_snaps\n with pytest.raises(Exception) as e:\n sb_volume0.snapshotCreate()\n assert \"cannot create snapshot for standby volume\" in str(e.value)\n with pytest.raises(Exception) as e:\n sb_volume0.snapshotRevert(name=sb0_snap.name)\n assert \"cannot revert snapshot for standby volume\" in str(e.value)\n with pytest.raises(Exception) as e:\n sb_volume0.snapshotDelete(name=sb0_snap.name)\n assert \"cannot delete snapshot for standby volume\" in str(e.value)\n with pytest.raises(Exception) as e:\n sb_volume0.snapshotBackup(name=sb0_snap.name)\n assert \"cannot create backup for standby volume\" in str(e.value)\n with pytest.raises(Exception) as e:\n sb_volume0.pvCreate(pvName=sb_volume0_name)\n assert \"cannot create PV for standby volume\" in str(e.value)\n with pytest.raises(Exception) as e:\n sb_volume0.pvcCreate(pvcName=sb_volume0_name)\n assert \"cannot create PVC for standby volume\" in str(e.value)\n setting = client.by_id_setting(common.SETTING_BACKUP_TARGET)\n with pytest.raises(Exception) as e:\n client.update(setting, value=\"random.backup.target\")\n assert \"cannot modify BackupTarget \" \\\n \"since there are existing standby volumes\" in str(e.value)\n with pytest.raises(Exception) as e:\n sb_volume0.activate(frontend=\"wrong_frontend\")\n assert \"invalid frontend\" in str(e.value)\n\n activate_standby_volume(client, sb_volume0_name)\n sb_volume0 = client.by_id_volume(sb_volume0_name)\n sb_volume0.attach(hostId=lht_host_id)\n sb_volume0 = common.wait_for_volume_healthy(client, sb_volume0_name)\n check_volume_data(sb_volume0, data0, False)\n\n zero_string = b'\\x00'.decode('utf-8')\n _, backup1, _, data1 = create_backup(\n client, volume_name,\n {'len': 2 * 1024, 'pos': 0, 'content': zero_string * 2 * 1024})\n # use this api to update field `last backup`\n client.list_backupVolume()\n check_volume_last_backup(client, sb_volume1_name, backup1.name)\n activate_standby_volume(client, sb_volume1_name)\n sb_volume1 = client.by_id_volume(sb_volume1_name)\n sb_volume1.attach(hostId=lht_host_id)\n sb_volume1 = common.wait_for_volume_healthy(client, sb_volume1_name)\n data0_modified = {\n 'len': data0['len'] - data1['len'],\n 'pos': data1['len'],\n 'content': data0['content'][data1['len']:],\n }\n check_volume_data(sb_volume1, data0_modified, False)\n check_volume_data(sb_volume1, data1)\n\n data2 = {'len': 1 * 1024 * 1024, 'pos': 0}\n data2['content'] = common.generate_random_data(data2['len'])\n _, backup2, _, data2 = create_backup(client, volume_name, data2)\n\n # HACK: #558 we use a side effect of the list call\n # to update the volumes last backup field\n client.list_backupVolume()\n check_volume_last_backup(client, sb_volume2_name, backup2.name)\n activate_standby_volume(client, sb_volume2_name)\n sb_volume2 = client.by_id_volume(sb_volume2_name)\n sb_volume2.attach(hostId=lht_host_id)\n sb_volume2 = common.wait_for_volume_healthy(client, sb_volume2_name)\n check_volume_data(sb_volume2, data2)\n\n # allocated this active volume to a pod\n sb_volume2.detach()\n sb_volume2 = common.wait_for_volume_detached(client, sb_volume2_name)\n\n create_pv_for_volume(client, core_api, sb_volume2, sb_volume2_name)\n create_pvc_for_volume(client, core_api, sb_volume2, sb_volume2_name)\n\n sb_volume2_pod_name = \"pod-\" + sb_volume2_name\n pod['metadata']['name'] = sb_volume2_pod_name\n pod['spec']['volumes'] = [{\n 'name': pod['spec']['containers'][0]['volumeMounts'][0]['name'],\n 'persistentVolumeClaim': {\n 'claimName': sb_volume2_name,\n },\n }]\n create_and_wait_pod(core_api, pod)\n\n sb_volume2 = client.by_id_volume(sb_volume2_name)\n k_status = sb_volume2.kubernetesStatus\n workloads = k_status.workloadsStatus\n assert k_status.pvName == sb_volume2_name\n assert k_status.pvStatus == 'Bound'\n assert len(workloads) == 1\n for i in range(RETRY_COUNTS):\n if workloads[0].podStatus == 'Running':\n break\n time.sleep(RETRY_INTERVAL)\n sb_volume2 = client.by_id_volume(sb_volume2_name)\n k_status = sb_volume2.kubernetesStatus\n workloads = k_status.workloadsStatus\n assert len(workloads) == 1\n assert workloads[0].podName == sb_volume2_pod_name\n assert workloads[0].podStatus == 'Running'\n assert not workloads[0].workloadName\n assert not workloads[0].workloadType\n assert k_status.namespace == 'default'\n assert k_status.pvcName == sb_volume2_name\n assert not k_status.lastPVCRefAt\n assert not k_status.lastPodRefAt\n\n delete_and_wait_pod(core_api, sb_volume2_pod_name)\n delete_and_wait_pvc(core_api, sb_volume2_name)\n delete_and_wait_pv(core_api, sb_volume2_name)\n\n # cleanup\n std_volume.detach()\n sb_volume0.detach()\n sb_volume1.detach()\n std_volume = common.wait_for_volume_detached(client, volume_name)\n sb_volume0 = common.wait_for_volume_detached(client, sb_volume0_name)\n sb_volume1 = common.wait_for_volume_detached(client, sb_volume1_name)\n sb_volume2 = common.wait_for_volume_detached(client, sb_volume2_name)\n\n backupstore_cleanup(client)\n\n client.delete(std_volume)\n client.delete(sb_volume0)\n client.delete(sb_volume1)\n client.delete(sb_volume2)\n\n wait_for_volume_delete(client, volume_name)\n wait_for_volume_delete(client, sb_volume0_name)\n wait_for_volume_delete(client, sb_volume1_name)\n wait_for_volume_delete(client, sb_volume2_name)\n\n volumes = client.list_volume()\n assert len(volumes) == 0\n\n\ndef test_deleting_backup_volume(client, volume_name): # NOQA\n \"\"\"\n Test deleting backup volumes\n\n 1. Create volume and create backup\n 2. Delete the backup and make sure it's gone in the backupstore\n \"\"\"\n lht_host_id = get_self_host_id()\n volume = create_and_check_volume(client, volume_name)\n\n volume.attach(hostId=lht_host_id)\n volume = common.wait_for_volume_healthy(client, volume_name)\n\n bv, _, snap1, _ = create_backup(client, volume_name)\n _, _, snap2, _ = create_backup(client, volume_name)\n\n delete_backup_volume(client, volume_name)\n cleanup_volume(client, volume)\n\n\n@pytest.mark.coretest # NOQA\ndef test_listing_backup_volume(client, base_image=\"\"): # NOQA\n \"\"\"\n Test listing backup volumes\n\n 1. Create three volumes: `volume1/2/3`\n 2. Setup NFS backupstore since we can manipulate the content easily\n 3. Create multiple snapshots for all three volumes\n 4. Rename `volume1`'s `volume.cfg` to `volume.cfg.tmp` in backupstore\n 5. List backup volumes. Make sure `volume1` errors out but found other two\n 6. Restore `volume1`'s `volume.cfg`.\n 7. Make sure now backup volume `volume1` can be found\n 8. Delete backups for `volume1/2`, make sure they cannot be found later\n 9. Corrupt a backup.cfg on volume3\n 11. Check that the backup is listed with the other backups of volume3\n 12. Verify that the corrupted backup has Messages of type error\n 13. Check that backup inspection for the previously corrupted backup fails\n 14. Delete backups for `volume3`, make sure they cannot be found later\n \"\"\"\n lht_hostId = get_self_host_id()\n\n # create 3 volumes.\n volume1_name = generate_volume_name()\n volume2_name = generate_volume_name()\n volume3_name = generate_volume_name()\n\n volume1 = create_and_check_volume(client, volume1_name)\n volume2 = create_and_check_volume(client, volume2_name)\n volume3 = create_and_check_volume(client, volume3_name)\n\n volume1.attach(hostId=lht_hostId)\n volume1 = common.wait_for_volume_healthy(client, volume1_name)\n volume2.attach(hostId=lht_hostId)\n volume2 = common.wait_for_volume_healthy(client, volume2_name)\n volume3.attach(hostId=lht_hostId)\n volume3 = common.wait_for_volume_healthy(client, volume3_name)\n\n # we only test NFS here.\n # Since it is difficult to directly remove volume.cfg from s3 buckets\n setting = client.by_id_setting(common.SETTING_BACKUP_TARGET)\n backupstores = common.get_backupstore_url()\n for backupstore in backupstores:\n if common.is_backupTarget_nfs(backupstore):\n updated = False\n for i in range(RETRY_COMMAND_COUNT):\n nfs_url = backupstore.strip(\"nfs://\")\n setting = client.update(setting, value=backupstore)\n assert setting.value == backupstore\n setting = client.by_id_setting(common.SETTING_BACKUP_TARGET)\n if \"nfs\" in setting.value:\n updated = True\n break\n assert updated\n\n _, _, snap1, _ = create_backup(client, volume1_name)\n _, _, snap2, _ = create_backup(client, volume2_name)\n _, _, snap3, _ = create_backup(client, volume3_name)\n subprocess.check_output([\"sync\"])\n _, _, snap4, _ = create_backup(client, volume3_name)\n subprocess.check_output([\"sync\"])\n _, _, snap5, _ = create_backup(client, volume3_name)\n subprocess.check_output([\"sync\"])\n\n # invalidate backup volume 1 by renaming volume.cfg to volume.cfg.tmp\n cmd = [\"mkdir\", \"-p\", \"/mnt/nfs\"]\n subprocess.check_output(cmd)\n cmd = [\"mount\", \"-t\", \"nfs4\", nfs_url, \"/mnt/nfs\"]\n subprocess.check_output(cmd)\n cmd = [\"find\", \"/mnt/nfs\", \"-type\", \"d\", \"-name\", volume1_name]\n volume1_backup_volume_path = \\\n subprocess.check_output(cmd).strip().decode('utf-8')\n\n cmd = [\"find\", volume1_backup_volume_path, \"-name\", \"volume.cfg\"]\n volume1_backup_volume_cfg_path = \\\n subprocess.check_output(cmd).strip().decode('utf-8')\n cmd = [\"mv\", volume1_backup_volume_cfg_path,\n volume1_backup_volume_cfg_path + \".tmp\"]\n subprocess.check_output(cmd)\n subprocess.check_output([\"sync\"])\n\n found1 = found2 = found3 = False\n for i in range(RETRY_COUNTS):\n bvs = client.list_backupVolume()\n for bv in bvs:\n if bv.name == volume1_name:\n if \"error\" in bv.messages:\n assert \"volume.cfg\" in bv.messages.error.lower()\n found1 = True\n elif bv.name == volume2_name:\n assert not bv.messages\n found2 = True\n elif bv.name == volume3_name:\n assert not bv.messages\n found3 = True\n if found1 & found2 & found3:\n break\n time.sleep(RETRY_INTERVAL)\n assert found1 & found2 & found3\n\n cmd = [\"mv\", volume1_backup_volume_cfg_path + \".tmp\",\n volume1_backup_volume_cfg_path]\n subprocess.check_output(cmd)\n subprocess.check_output([\"sync\"])\n\n bv1, b1 = common.find_backup(client, volume1_name, snap1.name)\n common.delete_backup(client, volume1_name, b1.name)\n\n bv2, b2 = common.find_backup(client, volume2_name, snap2.name)\n common.delete_backup(client, volume2_name, b2.name)\n\n # corrupt backup for snap4\n bv4, b4 = common.find_backup(client, volume3_name, snap4.name)\n b4_cfg_name = \"backup_\" + b4[\"name\"] + \".cfg\"\n cmd = [\"find\", \"/mnt/nfs\", \"-type\", \"d\", \"-name\", volume3_name]\n v3_backup_path = subprocess.check_output(cmd).strip().decode('utf-8')\n b4_cfg_path = os.path.join(v3_backup_path, \"backups\", b4_cfg_name)\n assert os.path.exists(b4_cfg_path)\n b4_tmp_cfg_path = os.path.join(v3_backup_path, b4_cfg_name)\n os.rename(b4_cfg_path, b4_tmp_cfg_path)\n assert os.path.exists(b4_tmp_cfg_path)\n\n corrupt_backup = open(b4_cfg_path, \"w\")\n assert corrupt_backup\n assert corrupt_backup.write(\"{corrupt: definitely\") > 0\n corrupt_backup.close()\n subprocess.check_output([\"sync\"])\n\n # a corrupt backup cannot provide information about the snapshot\n for i in range(RETRY_COMMAND_COUNT):\n found = False\n for b in bv4.backupList().data:\n if b.name in b4[\"name\"]:\n found = True\n assert b.messages is not None\n assert MESSAGE_TYPE_ERROR in b.messages\n break\n assert found\n\n # cleanup b4\n os.remove(b4_cfg_path)\n os.rename(b4_tmp_cfg_path, b4_cfg_path)\n subprocess.check_output([\"sync\"])\n\n bv3, b3 = common.find_backup(client, volume3_name, snap3.name)\n common.delete_backup(client, volume3_name, b3.name)\n bv4, b4 = common.find_backup(client, volume3_name, snap4.name)\n common.delete_backup(client, volume3_name, b4.name)\n bv5, b5 = common.find_backup(client, volume3_name, snap5.name)\n common.delete_backup(client, volume3_name, b5.name)\n\n volume1.detach()\n volume1 = common.wait_for_volume_detached(client, volume1_name)\n client.delete(volume1)\n wait_for_volume_delete(client, volume1_name)\n\n volume2.detach()\n volume2 = common.wait_for_volume_detached(client, volume2_name)\n client.delete(volume2)\n wait_for_volume_delete(client, volume2_name)\n\n volume3.detach()\n volume3 = common.wait_for_volume_detached(client, volume3_name)\n client.delete(volume3)\n wait_for_volume_delete(client, volume3_name)\n\n volumes = client.list_volume()\n assert len(volumes) == 0\n\n\n@pytest.mark.coretest # NOQA\ndef test_volume_multinode(client, volume_name): # NOQA\n \"\"\"\n Test the volume can be attached on multiple nodes\n\n 1. Create one volume\n 2. Attach it on every node once, verify the state, then detach it\n \"\"\"\n hosts = [node['name'] for node in client.list_node()]\n\n volume = client.create_volume(name=volume_name,\n size=SIZE,\n numberOfReplicas=2)\n volume = common.wait_for_volume_detached(client,\n volume_name)\n\n for host_id in hosts:\n volume = volume.attach(hostId=host_id)\n volume = common.wait_for_volume_healthy(client,\n volume_name)\n engine = get_volume_engine(volume)\n assert engine.hostId == host_id\n volume = volume.detach()\n volume = common.wait_for_volume_detached(client,\n volume_name)\n\n client.delete(volume)\n wait_for_volume_delete(client, volume_name)\n\n volumes = client.list_volume()\n assert len(volumes) == 0\n\n\n@pytest.mark.coretest # NOQA\ndef test_volume_scheduling_failure(client, volume_name): # NOQA\n '''\n Test fail to schedule by disable scheduling for all the nodes\n\n Also test cannot attach a scheduling failed volume\n\n 1. Disable `allowScheduling` for all nodes\n 2. Create a volume.\n 3. Verify the volume condition `Scheduled` is false\n 4. Verify the volume is not ready for workloads\n 5. Verify attaching the volume will result in error\n 6. Enable `allowScheduling` for all nodes\n 7. Volume should be automatically scheduled (condition become true)\n 8. Volume can be attached now\n '''\n nodes = client.list_node()\n assert len(nodes) > 0\n\n for node in nodes:\n node = client.update(node, allowScheduling=False)\n node = common.wait_for_node_update(client, node.id,\n \"allowScheduling\", False)\n\n volume = client.create_volume(name=volume_name, size=SIZE,\n numberOfReplicas=3)\n\n volume = common.wait_for_volume_condition_scheduled(client, volume_name,\n \"status\",\n CONDITION_STATUS_FALSE)\n volume = common.wait_for_volume_detached(client, volume_name)\n assert not volume.ready\n self_node = get_self_host_id()\n with pytest.raises(Exception) as e:\n volume.attach(hostId=self_node)\n assert \"cannot be scheduled\" in str(e.value)\n\n for node in nodes:\n node = client.update(node, allowScheduling=True)\n node = common.wait_for_node_update(client, node.id,\n \"allowScheduling\", True)\n\n volume = common.wait_for_volume_condition_scheduled(client, volume_name,\n \"status\",\n CONDITION_STATUS_TRUE)\n volume = common.wait_for_volume_detached(client, volume_name)\n volume = volume.attach(hostId=self_node)\n volume = common.wait_for_volume_healthy(client, volume_name)\n endpoint = get_volume_endpoint(volume)\n volume_rw_test(endpoint)\n\n volume = volume.detach()\n volume = common.wait_for_volume_detached(client, volume_name)\n\n client.delete(volume)\n wait_for_volume_delete(client, volume_name)\n\n\n@pytest.mark.coretest # NOQA\ndef test_setting_default_replica_count(client, volume_name): # NOQA\n \"\"\"\n Test `Default Replica Count` setting\n\n 1. Set default replica count in the global settings to 5\n 2. Create a volume without specify the replica count\n 3. The volume should have 5 replicas (instead of the previous default 3)\n \"\"\"\n setting = client.by_id_setting(common.SETTING_DEFAULT_REPLICA_COUNT)\n old_value = setting.value\n setting = client.update(setting, value=\"5\")\n\n volume = client.create_volume(name=volume_name, size=SIZE)\n volume = common.wait_for_volume_detached(client, volume_name)\n assert len(volume.replicas) == int(setting.value)\n\n client.delete(volume)\n wait_for_volume_delete(client, volume_name)\n\n setting = client.update(setting, value=old_value)\n\n\n@pytest.mark.coretest # NOQA\ndef test_volume_update_replica_count(client, volume_name): # NOQA\n \"\"\"\n Test updating volume's replica count\n\n 1. Create a volume with 2 replicas\n 2. Attach the volume\n 3. Increase the replica to 3.\n 4. Volume will become degraded and start rebuilding\n 5. Wait for rebuilding to complete\n 6. Update the replica count to 2. Volume should remain healthy\n 7. Remove 1 replicas, so there will be 2 replicas in the volume\n 8. Verify the volume is still healthy\n\n Volume should always be healthy even only with 2 replicas.\n \"\"\"\n host_id = get_self_host_id()\n\n replica_count = 2\n volume = create_and_check_volume(client, volume_name, replica_count)\n\n volume.attach(hostId=host_id)\n volume = common.wait_for_volume_healthy(client, volume_name)\n\n replica_count = 3\n volume = volume.updateReplicaCount(replicaCount=replica_count)\n volume = common.wait_for_volume_degraded(client, volume_name)\n volume = common.wait_for_volume_healthy(client, volume_name)\n assert len(volume.replicas) == replica_count\n\n old_replica_count = replica_count\n replica_count = 2\n volume = volume.updateReplicaCount(replicaCount=replica_count)\n volume = common.wait_for_volume_healthy(client, volume_name)\n assert len(volume.replicas) == old_replica_count\n\n volume.replicaRemove(name=volume.replicas[0].name)\n\n volume = common.wait_for_volume_replica_count(client, volume_name,\n replica_count)\n assert volume.robustness == \"healthy\"\n assert len(volume.replicas) == replica_count\n\n client.delete(volume)\n wait_for_volume_delete(client, volume_name)\n\n\n@pytest.mark.coretest # NOQA\ndef test_attach_without_frontend(client, volume_name): # NOQA\n \"\"\"\n Test attach in maintenance mode (without frontend)\n\n 1. Create a volume and attach to the current node with enabled frontend\n 2. Check volume has `blockdev`\n 3. Write `snap1_data` into volume and create snapshot `snap1`\n 4. Write more random data into volume and create another anspshot\n 5. Detach the volume and reattach with disabled frontend\n 6. Check volume still has `blockdev` as frontend but no endpoint\n 7. Revert back to `snap1`\n 8. Detach and reattach the volume with enabled frontend\n 9. Check volume contains data `snap1_data`\n \"\"\"\n volume = create_and_check_volume(client, volume_name)\n\n lht_hostId = get_self_host_id()\n volume.attach(hostId=lht_hostId, disableFrontend=False)\n common.wait_for_volume_healthy(client, volume_name)\n\n volume = client.by_id_volume(volume_name)\n assert volume.disableFrontend is False\n assert volume.frontend == VOLUME_FRONTEND_BLOCKDEV\n\n snap1_data = write_volume_random_data(volume)\n snap1 = create_snapshot(client, volume_name)\n\n write_volume_random_data(volume)\n create_snapshot(client, volume_name)\n\n volume.detach()\n volume = common.wait_for_volume_detached(client, volume_name)\n\n volume.attach(hostId=lht_hostId, disableFrontend=True)\n common.wait_for_volume_healthy_no_frontend(client, volume_name)\n\n volume = client.by_id_volume(volume_name)\n assert volume.disableFrontend is True\n assert volume.frontend == VOLUME_FRONTEND_BLOCKDEV\n check_volume_endpoint(volume)\n\n volume.snapshotRevert(name=snap1.name)\n\n volume.detach()\n volume = common.wait_for_volume_detached(client, volume_name)\n\n volume.attach(hostId=lht_hostId, disableFrontend=False)\n common.wait_for_volume_healthy(client, volume_name)\n\n volume = client.by_id_volume(volume_name)\n assert volume.disableFrontend is False\n assert volume.frontend == VOLUME_FRONTEND_BLOCKDEV\n\n check_volume_data(volume, snap1_data)\n\n client.delete(volume)\n wait_for_volume_delete(client, volume_name)\n\n\n@pytest.mark.coretest # NOQA\ndef test_storage_class_from_backup(volume_name, pvc_name, storage_class, client, core_api, pod_make): # NOQA\n \"\"\"\n Test restore backup using StorageClass\n\n 1. Create volume and PV/PVC/POD\n 2. Write `test_data` into pod\n 3. Create a snapshot and back it up. Get the backup URL\n 4. Create a new StorageClass `longhorn-from-backup` and set backup URL.\n 5. Use `longhorn-from-backup` to create a new PVC\n 6. Wait for the volume to be created and complete the restoration.\n 7. Create the pod using the PVC. Verify the data\n \"\"\"\n VOLUME_SIZE = str(DEFAULT_VOLUME_SIZE * Gi)\n\n pv_name = pvc_name\n\n volume = create_and_check_volume(\n client,\n volume_name,\n size=VOLUME_SIZE\n )\n\n wait_for_volume_detached(client, volume_name)\n\n create_pv_for_volume(client, core_api, volume, pv_name)\n create_pvc_for_volume(client, core_api, volume, pvc_name)\n\n pod_manifest = pod_make()\n pod_manifest['spec']['volumes'] = [create_pvc_spec(pvc_name)]\n pod_name = pod_manifest['metadata']['name']\n create_and_wait_pod(core_api, pod_manifest)\n\n test_data = generate_random_data(VOLUME_RWTEST_SIZE)\n write_pod_volume_data(core_api, pod_name, test_data)\n\n volume_id = client.by_id_volume(volume_name)\n snapshot = volume_id.snapshotCreate()\n\n volume_id.snapshotBackup(name=snapshot.name)\n wait_for_backup_completion(client, volume_name, snapshot.name)\n bv, b = find_backup(client, volume_name, snapshot.name)\n\n backup_url = b.url\n\n storage_class['metadata']['name'] = \"longhorn-from-backup\"\n storage_class['parameters']['fromBackup'] = backup_url\n\n create_storage_class(storage_class)\n\n backup_pvc_name = generate_volume_name()\n\n backup_pvc_spec = {\n \"apiVersion\": \"v1\",\n \"kind\": \"PersistentVolumeClaim\",\n \"metadata\": {\n \"name\": backup_pvc_name,\n },\n \"spec\": {\n \"accessModes\": [\n \"ReadWriteOnce\"\n ],\n \"storageClassName\": storage_class['metadata']['name'],\n \"resources\": {\n \"requests\": {\n \"storage\": VOLUME_SIZE\n }\n }\n }\n }\n\n volume_count = len(client.list_volume())\n\n core_api.create_namespaced_persistent_volume_claim(\n 'default',\n backup_pvc_spec\n )\n\n backup_volume_created = False\n\n for i in range(RETRY_COUNTS):\n if len(client.list_volume()) == volume_count + 1:\n backup_volume_created = True\n break\n time.sleep(RETRY_INTERVAL)\n\n assert backup_volume_created\n\n for i in range(RETRY_COUNTS):\n pvc_status = core_api.read_namespaced_persistent_volume_claim_status(\n name=backup_pvc_name,\n namespace='default'\n )\n\n if pvc_status.status.phase == 'Bound':\n break\n time.sleep(RETRY_INTERVAL)\n\n found = False\n for i in range(RETRY_COUNTS):\n volumes = client.list_volume()\n for volume in volumes:\n if volume.kubernetesStatus.pvcName == backup_pvc_name:\n backup_volume_name = volume.name\n found = True\n break\n if found:\n break\n time.sleep(RETRY_INTERVAL)\n assert found\n\n wait_for_volume_restoration_completed(client, backup_volume_name)\n wait_for_volume_detached(client, backup_volume_name)\n\n backup_pod_manifest = pod_make(name=\"backup-pod\")\n backup_pod_manifest['spec']['volumes'] = \\\n [create_pvc_spec(backup_pvc_name)]\n backup_pod_name = backup_pod_manifest['metadata']['name']\n create_and_wait_pod(core_api, backup_pod_manifest)\n\n restored_data = read_volume_data(core_api, backup_pod_name)\n assert test_data == restored_data\n\n\n@pytest.mark.coretest # NOQA\ndef test_expansion_basic(client, volume_name): # NOQA\n \"\"\"\n Test volume expansion using Longhorn API\n\n 1. Create volume and attach to the current node\n 2. Generate data `snap1_data` and write it to the volume\n 3. Create snapshot `snap1`\n 4. Expand the volume (volume will be detached, expanded, then attached)\n 5. Verify the volume has been expanded\n 6. Generate data `snap2_data` and write it to the volume\n 7. Create snapshot `snap2`\n 8. Gerneate data `snap3_data` and write it after the original size\n 9. Create snapshot `snap3` and verify the `snap3_data` with location\n 10. Detach and reattach the volume.\n 11. Verify the volume is still expanded, and `snap3_data` remain valid\n 12. Detach the volume.\n 13. Reattach the volume in maintence mode\n 14. Revert to `snap2` and detach.\n 15. Attach the volume and check data `snap2_data`\n 16. Generate `snap4_data` and write it after the original size\n 17. Create snapshot `snap4` and verify `snap4_data`.\n 18. Detach the volume and revert to `snap1`\n 19. Validate `snap1_data`\n \"\"\"\n volume = create_and_check_volume(client, volume_name)\n\n lht_hostId = get_self_host_id()\n volume.attach(hostId=lht_hostId, disableFrontend=False)\n common.wait_for_volume_healthy(client, volume_name)\n\n volume = client.by_id_volume(volume_name)\n assert volume.disableFrontend is False\n assert volume.frontend == VOLUME_FRONTEND_BLOCKDEV\n\n snap1_data = write_volume_random_data(volume)\n snap1 = create_snapshot(client, volume_name)\n\n expand_attached_volume(client, volume_name)\n volume = client.by_id_volume(volume_name)\n check_block_device_size(volume, int(EXPAND_SIZE))\n\n snap2_data = write_volume_random_data(volume)\n snap2 = create_snapshot(client, volume_name)\n\n snap3_data = {\n 'pos': int(SIZE),\n 'content': generate_random_data(VOLUME_RWTEST_SIZE),\n }\n snap3_data = write_volume_data(volume, snap3_data)\n create_snapshot(client, volume_name)\n check_volume_data(volume, snap3_data)\n\n volume.detach()\n volume = common.wait_for_volume_detached(client, volume_name)\n\n volume.attach(hostId=lht_hostId, disableFrontend=False)\n common.wait_for_volume_healthy(client, volume_name)\n volume = client.by_id_volume(volume_name)\n check_block_device_size(volume, int(EXPAND_SIZE))\n check_volume_data(volume, snap3_data)\n volume.detach()\n volume = common.wait_for_volume_detached(client, volume_name)\n\n volume.attach(hostId=lht_hostId, disableFrontend=True)\n volume = common.wait_for_volume_healthy_no_frontend(client, volume_name)\n assert volume.disableFrontend is True\n assert volume.frontend == VOLUME_FRONTEND_BLOCKDEV\n check_volume_endpoint(volume)\n volume.snapshotRevert(name=snap2.name)\n volume.detach()\n volume = common.wait_for_volume_detached(client, volume_name)\n volume.attach(hostId=lht_hostId, disableFrontend=False)\n common.wait_for_volume_healthy(client, volume_name)\n volume = client.by_id_volume(volume_name)\n check_volume_data(volume, snap2_data, False)\n snap4_data = {\n 'pos': int(SIZE),\n 'content': generate_random_data(VOLUME_RWTEST_SIZE),\n }\n snap4_data = write_volume_data(volume, snap4_data)\n create_snapshot(client, volume_name)\n check_volume_data(volume, snap4_data)\n volume.detach()\n volume = common.wait_for_volume_detached(client, volume_name)\n\n volume.attach(hostId=lht_hostId, disableFrontend=True)\n volume = common.wait_for_volume_healthy_no_frontend(client, volume_name)\n volume.snapshotRevert(name=snap1.name)\n volume.detach()\n volume = common.wait_for_volume_detached(client, volume_name)\n volume.attach(hostId=lht_hostId, disableFrontend=False)\n common.wait_for_volume_healthy(client, volume_name)\n volume = client.by_id_volume(volume_name)\n check_volume_data(volume, snap1_data, False)\n\n client.delete(volume)\n wait_for_volume_delete(client, volume_name)\n\n\n@pytest.mark.coretest # NOQA\ndef test_restore_inc_with_expansion(set_random_backupstore, client, core_api, volume_name, pod): # NOQA\n \"\"\"\n Test restore from disaster recovery volume with volume expansion\n\n Run test against a random backupstores\n\n 1. Create a volume and attach to the current node\n 2. Generate `data0`, write to the volume, make a backup `backup0`\n 3. Create three DR(standby) volumes from the backup: `dr_volume0/1/2`\n 4. Wait for all three DR volumes to start the initial restoration\n 5. Verify DR volumes's `lastBackup` is `backup0`\n 6. Verify snapshot/pv/pvc/change backup target are not allowed as long\n as the DR volume exists\n 7. Activate standby `dr_volume0` and attach it to check the volume data\n 8. Expand the original volume. Make sure the expansion is successful.\n 8. Generate `data1` and write to the original volume and create `backup1`\n 9. Make sure `dr_volume1`'s `lastBackup` field has been updated to\n `backup1`\n 10. Activate `dr_volume1` and check data `data0` and `data1`\n 11. Generate `data2` and write to the original volume after original SIZE\n 12. Create `backup2`\n 13. Wait for `dr_volume2` to finish expansion, show `backup2` as latest\n 14. Activate `dr_volume2` and verify `data2`\n 15. Detach `dr_volume2`\n 16. Create PV, PVC and Pod to use `sb_volume2`, check PV/PVC/POD are good\n\n FIXME: Step 16 works because the disk will be treated as a unformatted disk\n \"\"\"\n lht_host_id = get_self_host_id()\n\n std_volume = create_and_check_volume(client, volume_name, 2, SIZE)\n std_volume.attach(hostId=lht_host_id)\n std_volume = common.wait_for_volume_healthy(client, volume_name)\n\n with pytest.raises(Exception) as e:\n std_volume.activate(frontend=VOLUME_FRONTEND_BLOCKDEV)\n assert \"already in active mode\" in str(e.value)\n\n data0 = {'pos': 0, 'len': VOLUME_RWTEST_SIZE,\n 'content': common.generate_random_data(VOLUME_RWTEST_SIZE)}\n bv, backup0, _, data0 = create_backup(\n client, volume_name, data0)\n\n dr_volume0_name = \"dr-expand-0-\" + volume_name\n dr_volume1_name = \"dr-expand-1-\" + volume_name\n dr_volume2_name = \"dr-expand-2-\" + volume_name\n client.create_volume(name=dr_volume0_name, size=SIZE,\n numberOfReplicas=2, fromBackup=backup0.url,\n frontend=\"\", standby=True)\n client.create_volume(name=dr_volume1_name, size=SIZE,\n numberOfReplicas=2, fromBackup=backup0.url,\n frontend=\"\", standby=True)\n client.create_volume(name=dr_volume2_name, size=SIZE,\n numberOfReplicas=2, fromBackup=backup0.url,\n frontend=\"\", standby=True)\n wait_for_backup_restore_completed(client, dr_volume0_name, backup0.name)\n wait_for_backup_restore_completed(client, dr_volume1_name, backup0.name)\n wait_for_backup_restore_completed(client, dr_volume2_name, backup0.name)\n\n dr_volume0 = common.wait_for_volume_healthy_no_frontend(client,\n dr_volume0_name)\n dr_volume1 = common.wait_for_volume_healthy_no_frontend(client,\n dr_volume1_name)\n dr_volume2 = common.wait_for_volume_healthy_no_frontend(client,\n dr_volume2_name)\n\n for i in range(RETRY_COUNTS):\n client.list_backupVolume()\n dr_volume0 = client.by_id_volume(dr_volume0_name)\n dr_volume1 = client.by_id_volume(dr_volume1_name)\n dr_volume2 = client.by_id_volume(dr_volume2_name)\n dr_engine0 = get_volume_engine(dr_volume0)\n dr_engine1 = get_volume_engine(dr_volume1)\n dr_engine2 = get_volume_engine(dr_volume2)\n if dr_volume0.restoreRequired is False or \\\n dr_volume1.restoreRequired is False or \\\n dr_volume2.restoreRequired is False or \\\n not dr_engine0.lastRestoredBackup or \\\n not dr_engine1.lastRestoredBackup or \\\n not dr_engine2.lastRestoredBackup:\n time.sleep(RETRY_INTERVAL)\n else:\n break\n assert dr_volume0.standby is True\n assert dr_volume0.lastBackup == backup0.name\n assert dr_volume0.frontend == \"\"\n assert dr_volume0.restoreRequired is True\n dr_engine0 = get_volume_engine(dr_volume0)\n assert dr_engine0.lastRestoredBackup == backup0.name\n assert dr_engine0.requestedBackupRestore == backup0.name\n assert dr_volume1.standby is True\n assert dr_volume1.lastBackup == backup0.name\n assert dr_volume1.frontend == \"\"\n assert dr_volume1.restoreRequired is True\n dr_engine1 = get_volume_engine(dr_volume1)\n assert dr_engine1.lastRestoredBackup == backup0.name\n assert dr_engine1.requestedBackupRestore == backup0.name\n assert dr_volume2.standby is True\n assert dr_volume2.lastBackup == backup0.name\n assert dr_volume2.frontend == \"\"\n assert dr_volume2.restoreRequired is True\n dr_engine2 = get_volume_engine(dr_volume2)\n assert dr_engine2.lastRestoredBackup == backup0.name\n assert dr_engine2.requestedBackupRestore == backup0.name\n\n dr0_snaps = dr_volume0.snapshotList()\n assert len(dr0_snaps) == 2\n\n activate_standby_volume(client, dr_volume0_name)\n dr_volume0 = client.by_id_volume(dr_volume0_name)\n dr_volume0.attach(hostId=lht_host_id)\n dr_volume0 = common.wait_for_volume_healthy(client, dr_volume0_name)\n check_volume_data(dr_volume0, data0, False)\n\n expand_attached_volume(client, volume_name)\n std_volume = client.by_id_volume(volume_name)\n check_block_device_size(std_volume, int(EXPAND_SIZE))\n\n data1 = {'pos': VOLUME_RWTEST_SIZE, 'len': VOLUME_RWTEST_SIZE,\n 'content': common.generate_random_data(VOLUME_RWTEST_SIZE)}\n bv, backup1, _, data1 = create_backup(\n client, volume_name, data1)\n\n client.list_backupVolume()\n check_volume_last_backup(client, dr_volume1_name, backup1.name)\n activate_standby_volume(client, dr_volume1_name)\n dr_volume1 = client.by_id_volume(dr_volume1_name)\n dr_volume1.attach(hostId=lht_host_id)\n dr_volume1 = common.wait_for_volume_healthy(client, dr_volume1_name)\n check_volume_data(dr_volume1, data0, False)\n check_volume_data(dr_volume1, data1, False)\n\n data2 = {'pos': int(SIZE), 'len': VOLUME_RWTEST_SIZE,\n 'content': common.generate_random_data(VOLUME_RWTEST_SIZE)}\n bv, backup2, _, data2 = create_backup(\n client, volume_name, data2)\n assert backup2.volumeSize == EXPAND_SIZE\n\n client.list_backupVolume()\n wait_for_dr_volume_expansion(client, dr_volume2_name, EXPAND_SIZE)\n check_volume_last_backup(client, dr_volume2_name, backup2.name)\n activate_standby_volume(client, dr_volume2_name)\n dr_volume2 = client.by_id_volume(dr_volume2_name)\n dr_volume2.attach(hostId=lht_host_id)\n dr_volume2 = common.wait_for_volume_healthy(client, dr_volume2_name)\n check_volume_data(dr_volume2, data2)\n\n # allocated this active volume to a pod\n dr_volume2.detach()\n dr_volume2 = common.wait_for_volume_detached(client, dr_volume2_name)\n\n create_pv_for_volume(client, core_api, dr_volume2, dr_volume2_name)\n create_pvc_for_volume(client, core_api, dr_volume2, dr_volume2_name)\n\n dr_volume2_pod_name = \"pod-\" + dr_volume2_name\n pod['metadata']['name'] = dr_volume2_pod_name\n pod['spec']['volumes'] = [{\n 'name': pod['spec']['containers'][0]['volumeMounts'][0]['name'],\n 'persistentVolumeClaim': {\n 'claimName': dr_volume2_name,\n },\n }]\n create_and_wait_pod(core_api, pod)\n\n dr_volume2 = client.by_id_volume(dr_volume2_name)\n k_status = dr_volume2.kubernetesStatus\n workloads = k_status.workloadsStatus\n assert k_status.pvName == dr_volume2_name\n assert k_status.pvStatus == 'Bound'\n assert len(workloads) == 1\n for i in range(RETRY_COUNTS):\n if workloads[0].podStatus == 'Running':\n break\n time.sleep(RETRY_INTERVAL)\n dr_volume2 = client.by_id_volume(dr_volume2_name)\n k_status = dr_volume2.kubernetesStatus\n workloads = k_status.workloadsStatus\n assert len(workloads) == 1\n assert workloads[0].podName == dr_volume2_pod_name\n assert workloads[0].podStatus == 'Running'\n assert not workloads[0].workloadName\n assert not workloads[0].workloadType\n assert k_status.namespace == 'default'\n assert k_status.pvcName == dr_volume2_name\n assert not k_status.lastPVCRefAt\n assert not k_status.lastPodRefAt\n\n delete_and_wait_pod(core_api, dr_volume2_pod_name)\n delete_and_wait_pvc(core_api, dr_volume2_name)\n delete_and_wait_pv(core_api, dr_volume2_name)\n\n # cleanup\n std_volume.detach()\n dr_volume0.detach()\n dr_volume1.detach()\n std_volume = common.wait_for_volume_detached(client, volume_name)\n dr_volume0 = common.wait_for_volume_detached(client, dr_volume0_name)\n dr_volume1 = common.wait_for_volume_detached(client, dr_volume1_name)\n dr_volume2 = common.wait_for_volume_detached(client, dr_volume2_name)\n\n backupstore_cleanup(client)\n\n client.delete(std_volume)\n client.delete(dr_volume0)\n client.delete(dr_volume1)\n client.delete(dr_volume2)\n\n wait_for_volume_delete(client, volume_name)\n wait_for_volume_delete(client, dr_volume0_name)\n wait_for_volume_delete(client, dr_volume1_name)\n wait_for_volume_delete(client, dr_volume2_name)\n\n volumes = client.list_volume().data\n assert len(volumes) == 0\n\n\ndef test_engine_image_daemonset_restart(client, apps_api, volume_name): # NOQA\n \"\"\"\n Test restarting engine image daemonset\n\n 1. Get the default engine image\n 2. Create a volume and attach to the current node\n 3. Write random data to the volume and create a snapshot\n 4. Delete the engine image daemonset\n 5. Engine image daemonset should be recreated\n 6. In the meantime, validate the volume data to prove it's still functional\n 7. Wait for the engine image to become `ready` again\n 8. Check the volume data again.\n 9. Write some data and create a new snapshot.\n 1. Since create snapshot will use engine image binary.\n 10. Check the volume data again\n \"\"\"\n default_img = common.get_default_engine_image(client)\n ds_name = \"engine-image-\" + default_img.name\n\n volume = create_and_check_volume(client, volume_name)\n\n lht_hostId = get_self_host_id()\n volume.attach(hostId=lht_hostId, disableFrontend=False)\n volume = common.wait_for_volume_healthy(client, volume_name)\n snap1_data = write_volume_random_data(volume)\n create_snapshot(client, volume_name)\n\n # The engine image DaemonSet will be recreated/restarted automatically\n apps_api.delete_namespaced_daemon_set(ds_name, common.LONGHORN_NAMESPACE)\n\n # The Longhorn volume is still available\n # during the engine image DaemonSet restarting\n check_volume_data(volume, snap1_data)\n\n # Wait for the restart complete\n common.wait_for_engine_image_state(client, default_img.name, \"ready\")\n\n # Longhorn is still able to use the corresponding engine binary to\n # operate snapshot\n check_volume_data(volume, snap1_data)\n snap2_data = write_volume_random_data(volume)\n create_snapshot(client, volume_name)\n check_volume_data(volume, snap2_data)\n\n\n@pytest.mark.coretest # NOQA\ndef test_expansion_canceling(client, core_api, volume_name, pod): # NOQA\n \"\"\"\n Test expansion canceling\n\n 1. Create a volume, then create the corresponding PV, PVC and Pod.\n 2. Generate `test_data` and write to the pod\n 3. Create an empty directory with expansion snapshot tmp meta file path\n so that the following expansion will fail\n 4. Delete the pod and wait for volume detachment\n 5. Try to expand the volume using Longhorn API\n 6. Wait for expansion failure then use Longhorn API to cancel it\n 7. Create a new pod and validate the volume content,\n then re-write random data to the pod\n 8. Delete the pod and wait for volume detachment\n 9. Retry expansion then verify the expansion done using Longhorn API\n 10. Create a new pod\n 11. Validate the volume content, then check if data writing looks fine\n 12. Clean up pod, PVC, and PV\n \"\"\"\n expansion_pvc_name = \"pvc-\" + volume_name\n expansion_pv_name = \"pv-\" + volume_name\n pod_name = \"pod-\" + volume_name\n volume = create_and_check_volume(client, volume_name, 2, SIZE)\n create_pv_for_volume(client, core_api, volume, expansion_pv_name)\n create_pvc_for_volume(client, core_api, volume, expansion_pvc_name)\n pod['metadata']['name'] = pod_name\n pod['spec']['volumes'] = [{\n 'name': pod['spec']['containers'][0]['volumeMounts'][0]['name'],\n 'persistentVolumeClaim': {\n 'claimName': expansion_pvc_name,\n },\n }]\n create_and_wait_pod(core_api, pod)\n\n volume = client.by_id_volume(volume_name)\n replicas = volume.replicas\n fail_replica_expansion(client, core_api,\n volume_name, EXPAND_SIZE, replicas)\n\n test_data = generate_random_data(VOLUME_RWTEST_SIZE)\n write_pod_volume_data(core_api, pod_name, test_data)\n\n delete_and_wait_pod(core_api, pod_name)\n volume = wait_for_volume_detached(client, volume_name)\n\n volume.expand(size=EXPAND_SIZE)\n wait_for_expansion_failure(client, volume_name)\n volume = client.by_id_volume(volume_name)\n volume.cancelExpansion()\n wait_for_volume_expansion(client, volume_name)\n volume = client.by_id_volume(volume_name)\n assert volume.state == \"detached\"\n assert volume.size == SIZE\n\n # check if the volume still works fine\n create_and_wait_pod(core_api, pod)\n resp = read_volume_data(core_api, pod_name)\n assert resp == test_data\n test_data = generate_random_data(VOLUME_RWTEST_SIZE)\n write_pod_volume_data(core_api, pod_name, test_data)\n\n # retry expansion\n delete_and_wait_pod(core_api, pod_name)\n volume = wait_for_volume_detached(client, volume_name)\n volume.expand(size=EXPAND_SIZE)\n wait_for_volume_expansion(client, volume_name)\n volume = client.by_id_volume(volume_name)\n assert volume.state == \"detached\"\n assert volume.size == str(EXPAND_SIZE)\n\n create_and_wait_pod(core_api, pod)\n volume = client.by_id_volume(volume_name)\n engine = get_volume_engine(volume)\n assert volume.size == EXPAND_SIZE\n assert volume.size == engine.size\n resp = read_volume_data(core_api, pod_name)\n assert resp == test_data\n write_pod_volume_data(core_api, pod_name, test_data)\n resp = read_volume_data(core_api, pod_name)\n assert resp == test_data\n\n delete_and_wait_pod(core_api, pod_name)\n delete_and_wait_pvc(core_api, expansion_pvc_name)\n delete_and_wait_pv(core_api, expansion_pv_name)\n\n\n@pytest.mark.coretest # NOQA\ndef test_running_volume_with_scheduling_failure(\n client, core_api, volume_name, pod): # NOQA\n \"\"\"\n Test if the running volume still work fine\n when there is a scheduling failed replica\n\n Prerequisite:\n Setting \"soft anti-affinity\" is false.\n\n 1. Create a volume, then create the corresponding PV, PVC and Pod.\n 2. Wait for the pod running and the volume healthy.\n 3. Write data to the pod volume and get the md5sum.\n 4. Disable the scheduling for a node contains a running replica.\n 5. Crash the replica on the scheduling disabled node for the volume.\n 6. Wait for the scheduling failure which is caused\n by the new replica creation.\n 7. Verify:\n 7.1. `volume.ready == True`.\n 7.2. `volume.conditions[scheduled].status == False`.\n 7.3. the volume is Degraded.\n 7.4. the new replica is created but it is not running.\n 8. Write more data to the volume and get the md5sum\n 9. Delete the pod and wait for the volume detached.\n 10. Verify the scheduling failed replica is removed.\n 11. Verify:\n 11.1. `volume.ready == True`.\n 11.2. `volume.conditions[scheduled].status == True`\n 12. Recreate a new pod for the volume and wait for the pod running.\n 13. Validate the volume content, then check if data writing looks fine.\n 14. Clean up pod, PVC, and PV.\n \"\"\"\n\n replica_node_soft_anti_affinity_setting = \\\n client.by_id_setting(SETTING_REPLICA_NODE_SOFT_ANTI_AFFINITY)\n client.update(replica_node_soft_anti_affinity_setting, value=\"false\")\n\n data_path1 = \"/data/test1\"\n test_pv_name = \"pv-\" + volume_name\n test_pvc_name = \"pvc-\" + volume_name\n test_pod_name = \"pod-\" + volume_name\n\n volume = create_and_check_volume(client, volume_name, size=str(1 * Gi))\n create_pv_for_volume(client, core_api, volume, test_pv_name)\n create_pvc_for_volume(client, core_api, volume, test_pvc_name)\n\n pod['metadata']['name'] = test_pod_name\n pod['spec']['volumes'] = [{\n 'name': pod['spec']['containers'][0]['volumeMounts'][0]['name'],\n 'persistentVolumeClaim': {\n 'claimName': test_pvc_name,\n },\n }]\n create_and_wait_pod(core_api, pod)\n wait_for_volume_healthy(client, volume_name)\n write_pod_volume_random_data(core_api, test_pod_name,\n data_path1, DATA_SIZE_IN_MB_1)\n original_md5sum1 = get_pod_data_md5sum(core_api, test_pod_name,\n data_path1)\n\n volume = client.by_id_volume(volume_name)\n existing_replicas = {}\n for r in volume.replicas:\n existing_replicas[r.name] = r\n node = client.by_id_node(volume.replicas[0].hostId)\n node = client.update(node, allowScheduling=False)\n common.wait_for_node_update(client, node.id,\n \"allowScheduling\", False)\n\n crash_replica_processes(client, core_api, volume_name,\n replicas=[volume.replicas[0]],\n wait_to_fail=False)\n\n # Wait for scheduling failure.\n # It means the new replica is created but fails to be scheduled.\n wait_for_volume_condition_scheduled(client, volume_name, \"status\",\n CONDITION_STATUS_FALSE)\n wait_for_volume_condition_scheduled(client, volume_name, \"reason\",\n CONDITION_REASON_SCHEDULING_FAILURE)\n volume = wait_for_volume_degraded(client, volume_name)\n assert len(volume.replicas) == 4\n assert volume.ready\n for r in volume.replicas:\n if r.name not in existing_replicas:\n new_replica = r\n break\n assert new_replica\n assert not new_replica.running\n assert not new_replica.hostId\n\n data_path2 = \"/data/test2\"\n write_pod_volume_random_data(core_api, test_pod_name,\n data_path2, DATA_SIZE_IN_MB_1)\n original_md5sum2 = get_pod_data_md5sum(core_api, test_pod_name, data_path2)\n\n delete_and_wait_pod(core_api, test_pod_name)\n wait_for_volume_detached(client, volume_name)\n volume = wait_for_volume_condition_scheduled(client, volume_name, \"status\",\n CONDITION_STATUS_TRUE)\n assert volume.ready\n # The scheduling failed replica will be removed\n # so that the volume can be reattached later.\n assert len(volume.replicas) == 3\n for r in volume.replicas:\n assert r.hostId != \"\"\n assert r.name != new_replica.name\n\n create_and_wait_pod(core_api, pod)\n wait_for_volume_degraded(client, volume_name)\n\n md5sum1 = get_pod_data_md5sum(core_api, test_pod_name, data_path1)\n assert md5sum1 == original_md5sum1\n md5sum2 = get_pod_data_md5sum(core_api, test_pod_name, data_path2)\n assert md5sum2 == original_md5sum2\n\n # The data writing is fine\n data_path3 = \"/data/test3\"\n write_pod_volume_random_data(core_api, test_pod_name,\n data_path3, DATA_SIZE_IN_MB_1)\n get_pod_data_md5sum(core_api, test_pod_name, data_path3)\n\n delete_and_wait_pod(core_api, test_pod_name)\n delete_and_wait_pvc(core_api, test_pvc_name)\n delete_and_wait_pv(core_api, test_pv_name)\n\n\n@pytest.mark.coretest # NOQA\ndef test_expansion_with_scheduling_failure(\n client, core_api, volume_name, pod): # NOQA\n \"\"\"\n Test if the running volume with scheduling failure\n can be expanded after the detachment.\n\n Prerequisite:\n Setting \"soft anti-affinity\" is false.\n\n 1. Create a volume, then create the corresponding PV, PVC and Pod.\n 2. Wait for the pod running and the volume healthy.\n 3. Write data to the pod volume and get the md5sum.\n 4. Disable the scheduling for a node contains a running replica.\n 5. Crash the replica on the scheduling disabled node for the volume.\n Then delete the failed replica so that it won't be reused.\n 6. Wait for the scheduling failure which is caused\n by the new replica creation.\n 7. Verify:\n 7.1. `volume.ready == True`.\n 7.2. `volume.conditions[scheduled].status == False`.\n 7.3. the volume is Degraded.\n 7.4. the new replica is created but it is not running.\n 8. Write more data to the volume and get the md5sum\n 9. Delete the pod and wait for the volume detached.\n 10. Verify the scheduling failed replica is removed.\n 11. Verify:\n 11.1. `volume.ready == True`.\n 11.2. `volume.conditions[scheduled].status == True`\n 12. Expand the volume and wait for the expansion succeeds.\n 13. Verify there is no rebuild replica after the expansion.\n 14. Recreate a new pod for the volume and wait for the pod running.\n 15. Validate the volume content.\n 16. Verify the expanded part can be read/written correctly.\n 17. Enable the node scheduling.\n 18. Wait for the volume rebuild succeeds.\n 19. Verify the data written in the expanded part.\n 20. Clean up pod, PVC, and PV.\n\n Notice that the step 1 to step 11 is identical with\n those of the case test_running_volume_with_scheduling_failure().\n \"\"\"\n replica_node_soft_anti_affinity_setting = \\\n client.by_id_setting(SETTING_REPLICA_NODE_SOFT_ANTI_AFFINITY)\n client.update(replica_node_soft_anti_affinity_setting, value=\"false\")\n\n data_path1 = \"/data/test1\"\n test_pv_name = \"pv-\" + volume_name\n test_pvc_name = \"pvc-\" + volume_name\n test_pod_name = \"pod-\" + volume_name\n\n volume = create_and_check_volume(client, volume_name, size=str(300 * Mi))\n create_pv_for_volume(client, core_api, volume, test_pv_name)\n create_pvc_for_volume(client, core_api, volume, test_pvc_name)\n\n pod['metadata']['name'] = test_pod_name\n pod['spec']['volumes'] = [{\n 'name': pod['spec']['containers'][0]['volumeMounts'][0]['name'],\n 'persistentVolumeClaim': {\n 'claimName': test_pvc_name,\n },\n }]\n create_and_wait_pod(core_api, pod)\n wait_for_volume_healthy(client, volume_name)\n write_pod_volume_random_data(core_api, test_pod_name,\n data_path1, DATA_SIZE_IN_MB_1)\n original_md5sum1 = get_pod_data_md5sum(core_api, test_pod_name,\n data_path1)\n\n volume = client.by_id_volume(volume_name)\n old_replicas = {}\n for r in volume.replicas:\n old_replicas[r.name] = r\n failed_replica = volume.replicas[0]\n node = client.by_id_node(failed_replica.hostId)\n node = client.update(node, allowScheduling=False)\n common.wait_for_node_update(client, node.id,\n \"allowScheduling\", False)\n\n crash_replica_processes(client, core_api, volume_name,\n replicas=[failed_replica],\n wait_to_fail=False)\n\n # Remove the failed replica so that it won't be reused later\n volume = wait_for_volume_degraded(client, volume_name)\n volume.replicaRemove(name=failed_replica.name)\n\n # Wait for scheduling failure.\n # It means the new replica is created but fails to be scheduled.\n wait_for_volume_condition_scheduled(client, volume_name, \"status\",\n CONDITION_STATUS_FALSE)\n wait_for_volume_condition_scheduled(client, volume_name, \"reason\",\n CONDITION_REASON_SCHEDULING_FAILURE)\n volume = wait_for_volume_degraded(client, volume_name)\n assert len(volume.replicas) == 3\n assert volume.ready\n for r in volume.replicas:\n assert r.name != failed_replica.name\n if r.name not in old_replicas:\n new_replica = r\n break\n assert new_replica\n assert not new_replica.running\n assert not new_replica.hostId\n\n data_path2 = \"/data/test2\"\n write_pod_volume_random_data(core_api, test_pod_name,\n data_path2, DATA_SIZE_IN_MB_1)\n original_md5sum2 = get_pod_data_md5sum(core_api, test_pod_name, data_path2)\n\n delete_and_wait_pod(core_api, test_pod_name)\n wait_for_volume_detached(client, volume_name)\n volume = wait_for_volume_condition_scheduled(client, volume_name, \"status\",\n CONDITION_STATUS_TRUE)\n assert volume.ready\n # The scheduling failed replica will be removed\n # so that the volume can be reattached later.\n assert len(volume.replicas) == 2\n for r in volume.replicas:\n assert r.hostId != \"\"\n assert r.name != new_replica.name\n\n expanded_size = str(400 * Mi)\n volume.expand(size=expanded_size)\n wait_for_volume_expansion(client, volume_name)\n volume = client.by_id_volume(volume_name)\n assert volume.state == \"detached\"\n assert volume.size == expanded_size\n assert len(volume.replicas) == 2\n for r in volume.replicas:\n assert r.name in old_replicas\n\n create_and_wait_pod(core_api, pod)\n wait_for_volume_degraded(client, volume_name)\n\n md5sum1 = get_pod_data_md5sum(core_api, test_pod_name, data_path1)\n assert md5sum1 == original_md5sum1\n md5sum2 = get_pod_data_md5sum(core_api, test_pod_name, data_path2)\n assert md5sum2 == original_md5sum2\n\n # The data writing is fine\n data_path3 = \"/data/test3\"\n write_pod_volume_random_data(core_api, test_pod_name,\n data_path3, DATA_SIZE_IN_MB_1)\n original_md5sum3 = get_pod_data_md5sum(core_api, test_pod_name, data_path3)\n\n node = client.by_id_node(failed_replica.hostId)\n client.update(node, allowScheduling=True)\n wait_for_volume_healthy(client, volume_name)\n\n md5sum3 = get_pod_data_md5sum(core_api, test_pod_name, data_path3)\n assert md5sum3 == original_md5sum3\n\n delete_and_wait_pod(core_api, test_pod_name)\n delete_and_wait_pvc(core_api, test_pvc_name)\n delete_and_wait_pv(core_api, test_pv_name)\n\n\ndef test_dr_volume_with_last_backup_deletion(set_random_backupstore, client, core_api, csi_pv, pvc, volume_name, pod_make): # NOQA\n \"\"\"\n Test if the DR volume can be activated\n after deleting the lastest backup. There are two cases to the last\n backup, one is the last backup is no empty, and the other one is\n last backup is empty.\n\n 1. Set a random backupstore.\n 2. Create a volume, then create the corresponding PV, PVC and Pod.\n 3. Write data to the pod volume and get the md5sum\n after the pod running.\n 4. Create the 1st backup.\n 5. Create two DR volumes from the backup.\n 6. Wait for the DR volumes restore complete.\n 7. Write data to the original volume then create the 2nd backup.\n 8. Wait for the DR volumes incremental restore complete.\n 9. Delete the 2nd backup.\n 10. Verify the `lastBackup == 1st backup` for 2 DR volumes and\n original volume.\n 11. Activate the DR volume 1 and wait for it complete.\n 12. Create PV/PVC/Pod for the activated volume 1.\n 13. Validate the volume content.\n 14. Delete the 1st backup.\n 15. Verify the `lastBackup == \"\"` for DR volume 2 and original volume.\n 16. Activate the DR volume 2 and wait for it complete.\n 17. Create PV/PVC/Pod for the activated volume 2.\n 18. Validate the volume content, should be backup 1.\n \"\"\"\n std_volume_name = volume_name + \"-std\"\n data_path1 = \"/data/test1\"\n std_pod_name, std_pv_name, std_pvc_name, std_md5sum1 = \\\n prepare_pod_with_data_in_mb(\n client, core_api, csi_pv, pvc, pod_make, std_volume_name,\n data_path=data_path1, data_size_in_mb=DATA_SIZE_IN_MB_1)\n\n std_volume = client.by_id_volume(std_volume_name)\n snap1 = create_snapshot(client, std_volume_name)\n std_volume.snapshotBackup(name=snap1.name)\n wait_for_backup_completion(client, std_volume_name, snap1.name)\n bv, b1 = find_backup(client, std_volume_name, snap1.name)\n\n # Create DR volume 1 and 2.\n dr_volume_name = volume_name + \"-dr\"\n client.create_volume(name=dr_volume_name, size=str(1 * Gi),\n numberOfReplicas=3, fromBackup=b1.url,\n frontend=\"\", standby=True)\n wait_for_volume_creation(client, dr_volume_name)\n wait_for_volume_restoration_start(client, dr_volume_name, b1.name)\n wait_for_backup_restore_completed(client, dr_volume_name, b1.name)\n\n dr2_volume_name = volume_name + \"-dr2\"\n client.create_volume(name=dr2_volume_name, size=str(1 * Gi),\n numberOfReplicas=3, fromBackup=b1.url,\n frontend=\"\", standby=True)\n wait_for_volume_creation(client, dr2_volume_name)\n wait_for_volume_restoration_start(client, dr2_volume_name, b1.name)\n wait_for_backup_restore_completed(client, dr2_volume_name, b1.name)\n\n # Write data and create backup 2.\n data_path2 = \"/data/test2\"\n write_pod_volume_random_data(core_api, std_pod_name,\n data_path2, DATA_SIZE_IN_MB_1)\n snap2 = create_snapshot(client, std_volume_name)\n std_volume.snapshotBackup(name=snap2.name)\n wait_for_backup_completion(client, std_volume_name, snap2.name)\n bv, b2 = find_backup(client, std_volume_name, snap2.name)\n\n # Wait for the incremental restoration triggered then complete.\n check_volume_last_backup(client, dr_volume_name, b2.name)\n wait_for_volume_restoration_start(client, dr_volume_name, b2.name)\n wait_for_backup_restore_completed(client, dr_volume_name, b2.name)\n\n check_volume_last_backup(client, dr2_volume_name, b2.name)\n wait_for_volume_restoration_start(client, dr2_volume_name, b2.name)\n wait_for_backup_restore_completed(client, dr2_volume_name, b2.name)\n\n # Delete the latest backup backup 2 then check the `lastBackup` field.\n delete_backup(client, bv.name, b2.name)\n client.list_backupVolume()\n check_volume_last_backup(client, std_volume_name, b1.name)\n check_volume_last_backup(client, dr_volume_name, b1.name)\n check_volume_last_backup(client, dr2_volume_name, b1.name)\n\n # Active DR volume 1 and create PV/PVC/Pod for DR volume 1.\n activate_standby_volume(client, dr_volume_name)\n dr_volume = wait_for_volume_detached(client, dr_volume_name)\n\n dr_pod_name = dr_volume_name + \"-pod\"\n dr_pv_name = dr_volume_name + \"-pv\"\n dr_pvc_name = dr_volume_name + \"-pvc\"\n dr_pod = pod_make(name=dr_pod_name)\n create_pv_for_volume(client, core_api, dr_volume, dr_pv_name)\n create_pvc_for_volume(client, core_api, dr_volume, dr_pvc_name)\n dr_pod['spec']['volumes'] = [create_pvc_spec(dr_pvc_name)]\n create_and_wait_pod(core_api, dr_pod)\n\n # Validate the volume content.\n md5sum1 = get_pod_data_md5sum(core_api, dr_pod_name, data_path1)\n assert std_md5sum1 == md5sum1\n\n # For DR volume, the requested backup restore is backup1 and\n # the last restored backup is backup2 now. Since the backup2 is gone,\n # the DR volume will automatically fall back to do full restore\n # for backup1.\n\n # Delete backup 1 and check the `lastBackup` field.\n delete_backup(client, bv.name, b1.name)\n client.list_backupVolume()\n check_volume_last_backup(client, std_volume_name, \"\")\n check_volume_last_backup(client, dr_volume_name, \"\")\n check_volume_last_backup(client, dr2_volume_name, \"\")\n\n # Active DR volume 2 and create PV/PVC/Pod for DR volume 2.\n activate_standby_volume(client, dr2_volume_name)\n dr2_volume = wait_for_volume_detached(client, dr2_volume_name)\n\n dr2_pod_name = dr2_volume_name + \"-pod\"\n dr2_pv_name = dr2_volume_name + \"-pv\"\n dr2_pvc_name = dr2_volume_name + \"-pvc\"\n dr2_pod = pod_make(name=dr2_pod_name)\n create_pv_for_volume(client, core_api, dr2_volume, dr2_pv_name)\n create_pvc_for_volume(client, core_api, dr2_volume, dr2_pvc_name)\n dr2_pod['spec']['volumes'] = [create_pvc_spec(dr2_pvc_name)]\n create_and_wait_pod(core_api, dr2_pod)\n\n # Validate the volume content.\n md5sum1 = get_pod_data_md5sum(core_api, dr2_pod_name, data_path1)\n assert std_md5sum1 == md5sum1\n\n delete_and_wait_pod(core_api, std_pod_name)\n delete_and_wait_pod(core_api, dr_pod_name)\n delete_and_wait_pod(core_api, dr2_pod_name)\n client.delete(bv)\n\n\ndef test_backup_lock_deletion_during_restoration(set_random_backupstore, client, core_api, volume_name, csi_pv, pvc, pod_make): # NOQA\n \"\"\"\n Test backup locks\n Context:\n To test the locking mechanism that utilizes the backupstore,\n to prevent the following case of concurrent operations.\n - prevent backup deletion during backup restoration\n\n steps:\n 1. Create a volume, then create the corresponding PV, PVC and Pod.\n 2. Wait for the pod running and the volume healthy.\n 3. Write data to the pod volume and get the md5sum.\n 4. Take a backup.\n 5. Wait for the backup to be completed.\n 6. Start backup restoration for the backup creation.\n 7. Wait for restoration to be in progress.\n 8. Delete the backup from the backup store.\n 9. Wait for the restoration to be completed.\n 10. Assert the data from the restored volume with md5sum.\n 11. Assert the backup count in the backup store with 1.\n (The backup should not be deleted)\n \"\"\"\n backupstore_cleanup(client)\n std_volume_name = volume_name + \"-std\"\n restore_volume_name = volume_name + \"-restore\"\n _, _, _, std_md5sum = \\\n prepare_pod_with_data_in_mb(\n client, core_api, csi_pv, pvc, pod_make, std_volume_name,\n data_size_in_mb=DATA_SIZE_IN_MB_2)\n std_volume = client.by_id_volume(std_volume_name)\n snap1 = create_snapshot(client, std_volume_name)\n std_volume.snapshotBackup(name=snap1.name)\n wait_for_backup_completion(client, std_volume_name, snap1.name)\n backup_volume = client.by_id_backupVolume(std_volume_name)\n\n _, b = common.find_backup(client, std_volume_name, snap1.name)\n client.create_volume(name=restore_volume_name, fromBackup=b.url)\n wait_for_volume_restoration_start(client, restore_volume_name, b.name)\n\n backup_volume.backupDelete(name=b.name)\n\n wait_for_volume_restoration_completed(client, restore_volume_name)\n restore_volume = wait_for_volume_detached(client, restore_volume_name)\n assert len(restore_volume.replicas) == 3\n\n restore_pod_name = restore_volume_name + \"-pod\"\n restore_pv_name = restore_volume_name + \"-pv\"\n restore_pvc_name = restore_volume_name + \"-pvc\"\n restore_pod = pod_make(name=restore_pod_name)\n create_pv_for_volume(client, core_api, restore_volume, restore_pv_name)\n create_pvc_for_volume(client, core_api, restore_volume, restore_pvc_name)\n restore_pod['spec']['volumes'] = [create_pvc_spec(restore_pvc_name)]\n create_and_wait_pod(core_api, restore_pod)\n\n restore_volume = client.by_id_volume(restore_volume_name)\n assert restore_volume[VOLUME_FIELD_ROBUSTNESS] == VOLUME_ROBUSTNESS_HEALTHY\n\n md5sum = get_pod_data_md5sum(core_api, restore_pod_name, \"/data/test\")\n assert std_md5sum == md5sum\n\n _, b = common.find_backup(client, std_volume_name, snap1.name)\n assert b is not None\n\n\ndef test_backup_lock_deletion_during_backup(set_random_backupstore, client, core_api, volume_name, csi_pv, pvc, pod_make): # NOQA\n \"\"\"\n Test backup locks\n Context:\n To test the locking mechanism that utilizes the backupstore,\n to prevent the following case of concurrent operations.\n - prevent backup deletion while a backup is in progress\n\n steps:\n 1. Create a volume, then create the corresponding PV, PVC and Pod.\n 2. Wait for the pod running and the volume healthy.\n 3. Write data to the pod volume and get the md5sum.\n 4. Take a backup.\n 5. Wait for the backup to be completed.\n 6. Write more data into the volume and compute md5sum.\n 7. Take another backup of the volume.\n 8. While backup is in progress, delete the older backup up.\n 9. Wait for the backup creation in progress to be completed.\n 10. Check the backup store, there should be 2 backups.\n (The older backup should not be deleted)\n 11. Restore the latest backup.\n 12. Wait for the restoration to be completed. Assert md5sum from step 6.\n 13. Restore the older backup.\n 14. Wait for the restoration to be completed. Assert md5sum from step 3.\n \"\"\"\n backupstore_cleanup(client)\n std_volume_name = volume_name + \"-std\"\n restore_volume_name_1 = volume_name + \"-restore-1\"\n restore_volume_name_2 = volume_name + \"-restore-2\"\n\n std_pod_name, _, _, std_md5sum1 = \\\n prepare_pod_with_data_in_mb(\n client, core_api, csi_pv, pvc, pod_make, std_volume_name)\n std_volume = client.by_id_volume(std_volume_name)\n snap1 = create_snapshot(client, std_volume_name)\n std_volume.snapshotBackup(name=snap1.name)\n wait_for_backup_completion(client, std_volume_name, snap1.name)\n backup_volume = client.by_id_backupVolume(std_volume_name)\n _, b1 = common.find_backup(client, std_volume_name, snap1.name)\n\n write_pod_volume_random_data(core_api, std_pod_name, \"/data/test2\",\n DATA_SIZE_IN_MB_3)\n\n std_md5sum2 = get_pod_data_md5sum(core_api, std_pod_name, \"/data/test2\")\n snap2 = create_snapshot(client, std_volume_name)\n std_volume.snapshotBackup(name=snap2.name)\n wait_for_backup_to_start(client, std_volume_name, snap2.name)\n\n backup_volume.backupDelete(name=b1.name)\n\n wait_for_backup_completion(client, std_volume_name, snap2.name,\n retry_count=600)\n\n _, b1 = common.find_backup(client, std_volume_name, snap1.name)\n _, b2 = common.find_backup(client, std_volume_name, snap2.name)\n\n assert b1, b2 is not None\n\n client.create_volume(name=restore_volume_name_1, fromBackup=b1.url)\n\n wait_for_volume_restoration_completed(client, restore_volume_name_1)\n restore_volume_1 = wait_for_volume_detached(client, restore_volume_name_1)\n assert len(restore_volume_1.replicas) == 3\n\n restore_pod_name_1 = restore_volume_name_1 + \"-pod\"\n restore_pv_name_1 = restore_volume_name_1 + \"-pv\"\n restore_pvc_name_1 = restore_volume_name_1 + \"-pvc\"\n restore_pod_1 = pod_make(name=restore_pod_name_1)\n create_pv_for_volume(client, core_api, restore_volume_1, restore_pv_name_1)\n create_pvc_for_volume(client, core_api, restore_volume_1,\n restore_pvc_name_1)\n restore_pod_1['spec']['volumes'] = [create_pvc_spec(restore_pvc_name_1)]\n create_and_wait_pod(core_api, restore_pod_1)\n\n md5sum1 = get_pod_data_md5sum(core_api, restore_pod_name_1, \"/data/test\")\n\n assert std_md5sum1 == md5sum1\n\n client.create_volume(name=restore_volume_name_2, fromBackup=b2.url)\n\n wait_for_volume_restoration_completed(client, restore_volume_name_2)\n restore_volume_2 = wait_for_volume_detached(client, restore_volume_name_2)\n assert len(restore_volume_2.replicas) == 3\n\n restore_pod_name_2 = restore_volume_name_2 + \"-pod\"\n restore_pv_name_2 = restore_volume_name_2 + \"-pv\"\n restore_pvc_name_2 = restore_volume_name_2 + \"-pvc\"\n restore_pod_2 = pod_make(name=restore_pod_name_2)\n create_pv_for_volume(client, core_api, restore_volume_2, restore_pv_name_2)\n create_pvc_for_volume(client, core_api, restore_volume_2,\n restore_pvc_name_2)\n restore_pod_2['spec']['volumes'] = [create_pvc_spec(restore_pvc_name_2)]\n create_and_wait_pod(core_api, restore_pod_2)\n\n md5sum2 = get_pod_data_md5sum(core_api, restore_pod_name_2, \"/data/test2\")\n\n assert std_md5sum2 == md5sum2\n\n\ndef test_backup_lock_creation_during_deletion(set_random_backupstore, client, core_api, volume_name, csi_pv, pvc, pod_make): # NOQA\n \"\"\"\n Test backup locks\n Context:\n To test the locking mechanism that utilizes the backupstore,\n to prevent the following case of concurrent operations.\n - prevent backup creation during backup deletion\n\n steps:\n 1. Create a volume, then create the corresponding PV, PVC and Pod.\n 2. Wait for the pod running and the volume healthy.\n 3. Write data (DATA_SIZE_IN_MB_2) to the pod volume and get the md5sum.\n 4. Take a backup.\n 5. Wait for the backup to be completed.\n 6. Delete the backup.\n 7. Without waiting for the backup deletion completion, create another\n backup of the same volume.\n 8. Verify the API response of the backup creation containing the backup\n creation failure info.\n 9. Wait for the backup deletion and assert there is 0 backup in the backup\n store.\n \"\"\"\n backupstore_cleanup(client)\n std_volume_name = volume_name + \"-std\"\n\n std_pod_name, _, _, std_md5sum1 = \\\n prepare_pod_with_data_in_mb(\n client, core_api, csi_pv, pvc, pod_make, std_volume_name,\n data_size_in_mb=DATA_SIZE_IN_MB_2)\n std_volume = client.by_id_volume(std_volume_name)\n snap1 = create_snapshot(client, std_volume_name)\n std_volume.snapshotBackup(name=snap1.name)\n wait_for_backup_completion(client, std_volume_name, snap1.name)\n backup_volume = client.by_id_backupVolume(std_volume_name)\n _, b1 = common.find_backup(client, std_volume_name, snap1.name)\n\n write_pod_volume_random_data(core_api, std_pod_name,\n \"/data/test2\", DATA_SIZE_IN_MB_2)\n\n snap2 = create_snapshot(client, std_volume_name)\n\n backup_volume.backupDelete(name=b1.name)\n\n try:\n std_volume.snapshotBackup(name=snap2.name)\n except Exception as e:\n assert e.error.status == 500\n\n wait_for_backup_delete(client, volume_name, b1.name)\n try:\n _, b2 = common.find_backup(client, std_volume_name, snap2.name)\n except AssertionError:\n b2 = None\n assert b2 is None\n\n backupstore_wait_for_lock_expiration()\n\n\n@pytest.mark.skip(reason=\"This test takes more than 20 mins to run\") # NOQA\ndef test_backup_lock_restoration_during_deletion(set_random_backupstore, client, core_api, volume_name, csi_pv, pvc, pod_make): # NOQA\n \"\"\"\n Test backup locks\n Context:\n To test the locking mechanism that utilizes the backupstore,\n to prevent the following case of concurrent operations.\n - prevent backup restoration during backup deletion\n\n steps:\n 1. Create a volume, then create the corresponding PV, PVC and Pod.\n 2. Wait for the pod running and the volume healthy.\n 3. Write data to the pod volume and get the md5sum.\n 4. Take a backup.\n 5. Wait for the backup to be completed.\n 6. Write more data (1.5 Gi) to the volume and take another backup.\n 7. Wait for the 2nd backup to be completed.\n 8. Delete the 2nd backup.\n 9. Without waiting for the backup deletion completion, restore the 1st\n backup from the backup store.\n 10. Verify the restored volume become faulted.\n 11. Wait for the 2nd backup deletion and assert the count of the backups\n with 1 in the backup store.\n \"\"\"\n backupstore_cleanup(client)\n std_volume_name = volume_name + \"-std\"\n restore_volume_name = volume_name + \"-restore\"\n std_pod_name, _, _, std_md5sum1 = \\\n prepare_pod_with_data_in_mb(\n client, core_api, csi_pv, pvc, pod_make, std_volume_name,\n volume_size=str(3*Gi), data_size_in_mb=DATA_SIZE_IN_MB_1)\n std_volume = client.by_id_volume(std_volume_name)\n snap1 = create_snapshot(client, std_volume_name)\n std_volume.snapshotBackup(name=snap1.name)\n wait_for_backup_completion(client, std_volume_name, snap1.name)\n std_volume.snapshotBackup(name=snap1.name)\n backup_volume = client.by_id_backupVolume(std_volume_name)\n _, b1 = common.find_backup(client, std_volume_name, snap1.name)\n\n write_pod_volume_random_data(core_api, std_pod_name,\n \"/data/test2\", 1500)\n snap2 = create_snapshot(client, std_volume_name)\n std_volume.snapshotBackup(name=snap2.name)\n wait_for_backup_completion(client, std_volume_name, snap2.name,\n retry_count=1200)\n _, b2 = common.find_backup(client, std_volume_name, snap2.name)\n\n backup_volume.backupDelete(name=b2.name)\n\n client.create_volume(name=restore_volume_name, fromBackup=b1.url)\n wait_for_volume_detached(client, restore_volume_name)\n restore_volume = client.by_id_volume(restore_volume_name)\n assert restore_volume[VOLUME_FIELD_ROBUSTNESS] == VOLUME_ROBUSTNESS_FAULTED\n\n wait_for_backup_delete(client, volume_name, b2.name)\n\n _, b1 = common.find_backup(client, std_volume_name, snap1.name)\n assert b1 is not None\n\n try:\n _, b2 = common.find_backup(client, std_volume_name, snap2.name)\n except AssertionError:\n b2 = None\n assert b2 is None\n\n\n@pytest.mark.coretest\ndef test_allow_volume_creation_with_degraded_availability(client, volume_name): # NOQA\n \"\"\"\n Test Allow Volume Creation with Degraded Availability (API)\n\n Requirement:\n 1. Set `allow-volume-creation-with-degraded-availability` to true.\n 2. `node-level-soft-anti-affinity` to false.\n\n Steps:\n (degraded availablity)\n 1. Disable scheduling for node 2 and 3.\n 2. Create a volume with three replicas.\n 1. Volume should be `ready` after creation and `Scheduled` is true.\n 2. One replica schedule succeed. Two other replicas failed scheduling.\n 3. Enable the scheduling of node 2.\n 1. One additional replica of the volume will become scheduled.\n 2. The other replica is still failed to schedule.\n 3. Scheduled condition is still true.\n 4. Attach the volume.\n 1. After the volume is attached, scheduled condition become false.\n 5. Write data to the volume.\n 6. Detach the volume.\n 1. Scheduled condition should become true.\n 7. Reattach the volume to verify the data.\n 1. Scheduled condition should become false.\n 8. Enable the scheduling for the node 3.\n 9. Wait for the scheduling condition to become true.\n 10. Detach and reattach the volume to verify the data.\n \"\"\"\n # enable volume create with degraded availability\n degraded_availability_setting = \\\n client.by_id_setting(common.SETTING_DEGRADED_AVAILABILITY)\n client.update(degraded_availability_setting, value=\"true\")\n\n # disable node level soft anti-affinity\n replica_soft_anti_affinity_setting = \\\n client.by_id_setting(SETTING_REPLICA_NODE_SOFT_ANTI_AFFINITY)\n client.update(replica_soft_anti_affinity_setting, value=\"false\")\n\n nodes = client.list_node()\n node1 = nodes[0]\n node2 = nodes[1]\n node3 = nodes[2]\n\n # disable node 2 and 3 to schedule to node 1\n client.update(node2, allowScheduling=False)\n client.update(node3, allowScheduling=False)\n\n # create volume\n volume = create_and_check_volume(client, volume_name, num_of_replicas=3)\n assert volume.ready\n assert volume.conditions[VOLUME_CONDITION_SCHEDULED]['status'] == \"True\"\n\n # check only 1 replica scheduled successfully\n common.wait_for_replica_scheduled(client, volume_name,\n to_nodes=[node1.name],\n expect_success=1, expect_fail=2,\n is_vol_healthy=False,\n is_replica_running=False)\n\n # enable node 2 to schedule to node 1 and 2\n client.update(node2, allowScheduling=True)\n\n # check 2 replicas scheduled successfully\n common.wait_for_replica_scheduled(client, volume_name,\n to_nodes=[node1.name, node2.name],\n expect_success=2, expect_fail=1,\n is_vol_healthy=False,\n is_replica_running=False)\n\n volume = client.by_id_volume(volume_name)\n assert volume.conditions[VOLUME_CONDITION_SCHEDULED]['status'] == \"True\"\n\n # attach volume\n self_host = get_self_host_id()\n volume.attach(hostId=self_host)\n volume = common.wait_for_volume_degraded(client, volume_name)\n assert volume.conditions[VOLUME_CONDITION_SCHEDULED]['status'] == \"False\"\n\n data = write_volume_random_data(volume, {})\n\n # detach volume\n volume.detach()\n volume = common.wait_for_volume_detached(client, volume_name)\n assert volume.conditions[VOLUME_CONDITION_SCHEDULED]['status'] == \"True\"\n\n # re-attach volume to verify the data\n volume.attach(hostId=self_host)\n volume = common.wait_for_volume_degraded(client, volume_name)\n check_volume_data(volume, data)\n assert volume.conditions[VOLUME_CONDITION_SCHEDULED]['status'] == \"False\"\n\n # enable node 3 to schedule to node 1, 2 and 3\n client.update(node3, allowScheduling=True)\n common.wait_for_volume_condition_scheduled(client, volume_name,\n \"status\", \"True\")\n\n # detach and re-attach the volume to verify the data\n volume.detach()\n volume = common.wait_for_volume_detached(client, volume_name)\n\n volume.attach(hostId=self_host)\n volume = common.wait_for_volume_degraded(client, volume_name)\n check_volume_data(volume, data)\n\n\n@pytest.mark.coretest\ndef test_allow_volume_creation_with_degraded_availability_error(\n client, volume_name): # NOQA\n \"\"\"\n Test Allow Volume Creation with Degraded Availability (API)\n\n Requirement:\n 1. Set `allow-volume-creation-with-degraded-availability` to true.\n 2. `node-level-soft-anti-affinity` to false.\n\n Steps:\n (no availability)\n 1. Disable all nodes' scheduling.\n 2. Create a volume with three replicas.\n 1. Volume should be NotReady after creation.\n 2. Scheduled condition should become false.\n 3. Attaching the volume should result in error.\n 4. Enable one node's scheduling.\n 1. Volume should become Ready soon.\n 2. Scheduled condition should become true.\n 5. Attach the volume. Write data. Detach and reattach to verify the data.\n \"\"\"\n # enable volume create with degraded availability\n degraded_availability_setting = \\\n client.by_id_setting(common.SETTING_DEGRADED_AVAILABILITY)\n client.update(degraded_availability_setting, value=\"true\")\n\n # disable node level soft anti-affinity\n replica_soft_anti_affinity_setting = \\\n client.by_id_setting(SETTING_REPLICA_NODE_SOFT_ANTI_AFFINITY)\n client.update(replica_soft_anti_affinity_setting, value=\"false\")\n\n nodes = client.list_node()\n node1 = nodes[0]\n node2 = nodes[1]\n node3 = nodes[2]\n\n # disable node 1, 2 and 3 to make 0 available node\n client.update(node1, allowScheduling=False)\n client.update(node2, allowScheduling=False)\n client.update(node3, allowScheduling=False)\n\n # create volume\n volume = create_and_check_volume(client, volume_name, num_of_replicas=3)\n assert not volume.ready\n assert volume.conditions[VOLUME_CONDITION_SCHEDULED]['status'] == \"False\"\n\n # attach the volume\n self_host = get_self_host_id()\n with pytest.raises(Exception) as e:\n volume.attach(hostId=self_host)\n assert \"cannot be scheduled\" in str(e.value)\n\n # enable node 1\n client.update(node1, allowScheduling=True)\n\n # check only 1 replica scheduled successfully\n common.wait_for_replica_scheduled(client, volume_name,\n to_nodes=[node1.name],\n expect_success=1, expect_fail=2,\n is_vol_healthy=False,\n is_replica_running=False)\n volume = common.wait_for_volume_status(client, volume_name,\n VOLUME_FIELD_READY, True)\n assert volume.conditions[VOLUME_CONDITION_SCHEDULED]['status'] == \"True\"\n\n # attach the volume and write some data\n volume.attach(hostId=self_host)\n volume = common.wait_for_volume_degraded(client, volume_name)\n data = write_volume_random_data(volume, {})\n\n # detach and re-attach the volume to verify the data\n volume.detach()\n volume = common.wait_for_volume_detached(client, volume_name)\n\n volume.attach(hostId=self_host)\n volume = common.wait_for_volume_degraded(client, volume_name)\n check_volume_data(volume, data)\n\n\n@pytest.mark.skip(reason=\"TODO\") # NOQA\ndef test_multiple_volumes_creation_with_degraded_availability():\n \"\"\"\n Goal:\n We want to verify that multiple volumes with degraded availability\n can be created, attached, detached, and deleted at the nearly the\n same time.\n\n Steps:\n 1. create StorageClass longhorn-extra with numberOfReplicas=5\n Set allow-volume-creation-with-degraded-availability to True\n 2. Deploy this StatefulSet:\n https://github.com/longhorn/longhorn/issues/2073#issuecomment-742948726\n 3. In a 1-min retry loop, Verify that all 10 volumes are healthy\n 4. Delete the StatefulSet\n 5. In a 1-min retry loop, Verify that all 10 volumes are detached\n 6. Find and delete the PVC of the 10 volumes.\n 7. In a 1-min retry loop, Verify that all 10 volumes are deleted\n 8. Make sure to delete all extra storage classes in\n common.cleanup_client()\n \"\"\"\n pass\n\n\n@pytest.mark.skip(reason=\"TODO\")\ndef test_allow_volume_creation_with_degraded_availability_restore():\n \"\"\"\n Test Allow Volume Creation with Degraded Availability (Restore)\n\n Requirement:\n 1. Set `allow-volume-creation-with-degraded-availability` to true\n 2. `node-level-soft-anti-affinity` to false\n 3. Create a backup of 800MB.\n\n Steps:\n (restore)\n 1. Disable scheduling for node 2 and 3\n 2. Restore a volume with three replicas.\n 1. Volume should be attached automatically and `Scheduled` is true\n 2. One replica schedule succeed. Two other replicas failed scheduling.\n 3. During the restore, enable scheduling for node 2.\n 1. One additional replica of the volume will become scheduled\n 2. The other replica is still failed to schedule.\n 3. Scheduled condition is still true\n 4. Wait for the restore to complete and volume detach automatically.\n 1. After the volume detached, scheduled condition become true.\n 5. Attach the volume and verify the data.\n 1. After the volume is attached, scheduled condition become false.\n\n (DR volume)\n 1. Disable scheduling for node 2 and 3\n 2. Create a DR volume from backup with three replicas.\n 1. Volume should be attached automatically and `Scheduled` is true\n 2. One replica schedule succeed. Two other replicas failed scheduling.\n 3. During the restore, enable scheduling for node 2.\n 1. One additional replica of the volume will become scheduled\n 2. The other replica is still failed to schedule.\n 3. Scheduled condition is still true\n 4. Wait for the restore to complete.\n 5. Enable the scheduling for node 3.\n 1. DR volume should automatically rebuild the third replica.\n 6. Activate the volume and verify the data.\n \"\"\"\n\n\ndef test_cleanup_system_generated_snapshots(client, core_api, volume_name, csi_pv, pvc, pod_make): # NOQA\n \"\"\"\n Test Cleanup System Generated Snapshots\n\n 1. Enabled 'Auto Cleanup System Generated Snapshot'.\n 2. Create a volume and attach it to a node.\n 3. Write some data to the volume and get the checksum of the data.\n 4. Delete a random replica to trigger a system generated snapshot.\n 5. Repeat Step 3 for 3 times, and make sure only one snapshot is left.\n 6. Check the data with the saved checksum.\n \"\"\"\n\n pod_name, _, _, md5sum1 = \\\n prepare_pod_with_data_in_mb(\n client, core_api, csi_pv, pvc, pod_make, volume_name)\n\n volume = client.by_id_volume(volume_name)\n\n for i in range(3):\n replica_name = volume[\"replicas\"][i][\"name\"]\n volume.replicaRemove(name=replica_name)\n wait_for_volume_degraded(client, volume_name)\n wait_for_volume_healthy(client, volume_name)\n\n volume = client.by_id_volume(volume_name)\n # For the below assertion, the number of snapshots is compared with 2\n # as the list of snapshot have the volume-head too.\n assert len(volume.snapshotList()) == 2\n\n read_md5sum1 = get_pod_data_md5sum(core_api, pod_name, \"/data/test\")\n assert md5sum1 == read_md5sum1\n\n\ndef test_volume_toomanysnapshots_condition(client, core_api, volume_name): # NOQA\n \"\"\"\n Test Volume TooManySnapshots Condition\n\n 1. Create a volume and attach it to a node.\n 2. Check the 'TooManySnapshots' condition is False.\n 3. Writing data to this volume and meanwhile taking 100 snapshots.\n 4. Check the 'TooManySnapshots' condition is True.\n 5. Take one more snapshot to make sure snapshots works fine.\n 6. Delete 2 snapshots, and check the 'TooManySnapshots' condition is\n False.\n \"\"\"\n volume = create_and_check_volume(client, volume_name)\n self_hostId = get_self_host_id()\n volume = volume.attach(hostId=self_hostId)\n volume = common.wait_for_volume_healthy(client, volume_name)\n\n snap = {}\n max_count = 100\n for i in range(max_count):\n write_volume_random_data(volume, {})\n\n count = i + 1\n snap[count] = create_snapshot(client, volume_name)\n\n if count < max_count:\n volume = client.by_id_volume(volume_name)\n assert volume.conditions.toomanysnapshots.status == \"False\"\n else:\n wait_for_volume_condition_toomanysnapshots(client, volume_name,\n \"status\", \"True\")\n\n snap[max_count + 1] = create_snapshot(client, volume_name)\n wait_for_volume_condition_toomanysnapshots(client, volume_name,\n \"status\", \"True\")\n\n volume = client.by_id_volume(volume_name)\n volume.snapshotDelete(name=snap[100].name)\n volume.snapshotDelete(name=snap[99].name)\n\n volume.snapshotPurge()\n volume = wait_for_snapshot_purge(client, volume_name,\n snap[100].name, snap[99].name)\n\n wait_for_volume_condition_toomanysnapshots(client, volume_name,\n \"status\", \"False\")\n","sub_path":"manager/integration/tests/test_basic.py","file_name":"test_basic.py","file_ext":"py","file_size_in_byte":135542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"548504849","text":"def gcd(a, b):\n if (b == 0):\n return a\n return gcd(b, a%b)\n\nN = int(input())\nfor i in range(N):\n A = input().split()\n size = int(A[0])\n A = A[1:]\n ans=0\n for k in range(0, size):\n for j in range(k+1, size):\n ans+=gcd(int(A[k]), int(A[j]))\n print(ans)\n","sub_path":"intro/9613.py","file_name":"9613.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"30973769","text":"import os\nimport sys\nimport urllib.request\n\ndef checkImg(id,secret,keys,input):\n client_id = id # 개발자센터에서 발급받은 Client ID 값\n client_secret = secret # 개발자센터에서 발급받은 Client Secret 값\n code = \"1\"\n key = keys\n value = input\n url = \"https://openapi.naver.com/v1/captcha/nkey?code=\" + code + \"&key=\" + key + \"&value=\" + value\n request = urllib.request.Request(url)\n request.add_header(\"X-Naver-Client-Id\",client_id)\n request.add_header(\"X-Naver-Client-Secret\",client_secret)\n response = urllib.request.urlopen(request)\n rescode = response.getcode()\n if(rescode==200):\n response_body = response.read()\n result = response_body.decode('utf-8')\n return result\n else:\n print(\"Error Code:\" + rescode)","sub_path":"HelloPython/capchar/check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"39717340","text":"#!/usr/bin/env python2.7\n\nimport numpy as np\nimport commpy as cp\n\n__all__ = [\n 'transmitMatrix',\n 'fourierMatrix',\n 'samplingMatrix',\n 'randomQAMSymbols',\n 'gfdm_tx',\n 'gfdm_rx']\n\n# FIXME TransmitMatrix should group different subcarriers on timeslot-basis\n\n\ndef transmitMatrix(filtertype, alpha, M, K, N):\n '''\n Create Convolution Matrix for pulse shaping\n\n filtertype : (rrc,rc)\n alpha : roll-off-factor\n sampling_rate : sampling rate (in Hz)\n symbol_period : symbol period (in s)\n M : number of symbol time slots\n K : number of subcarriers\n\n h_matrix: array of impulse responses for time slot (0...M-1)\n '''\n if filtertype == \"rrc\":\n time_h, h = cp.rrcosfilter(M*K*N, alpha, N*K, 1)\n elif filtertype == \"rc\":\n time_h, h = cp.rcosfilter(M*K*N, alpha, N*K, 1)\n # Move filter cyclic\n G_tx = np.array([np.roll(h, m - (M*K*N/2)) for m in xrange(M*K*N)])\n S_mn = samplingMatrix(M, K*N)\n S_nm = samplingMatrix(K, M)\n if N > 1:\n # if oversampling is specified add zeros to samplingMatrix\n S_nm = np.insert(\n S_nm, M * K / 2, np.zeros((M * K * (N - 1), K), dtype='complex'),\n axis=0)\n W_H = fourierMatrix(M*K*N).conj().transpose()\n # Resample Filter\n G_tx_s = np.dot(G_tx, S_mn)\n # Resample FourierMatrix\n W_s = np.dot(S_nm.transpose(), W_H)\n # compute and use all elements of the main diagonal W_s.dot(G_tx_s)\n A = np.array([(np.kron(W_s.transpose()[n], G_tx_s[n]))\n for n in xrange(K*M*N)])\n\n return A\n\n\ndef fourierMatrix(N):\n i, j = np.meshgrid(np.arange(N), np.arange(N))\n omega = np.exp(- 2 * np.pi * 1j / N)\n W = np.power(omega, i * j) / np.sqrt(N)\n return W\n\n\ndef samplingMatrix(M, K):\n output = np.zeros((M*K, M), dtype='complex')\n for n in xrange(M*K):\n for m in xrange(M):\n if n == ((m)*K):\n output[n][m] = 1\n return output\n\n\ndef randomQAMSymbols(length, M):\n '''\n length: number of symbols to generate\n M: M-QAM - Order (4,16,64,...)\n '''\n n = np.sqrt(M/4)\n if np.around(n) - n > 1e-10:\n raise Exception('M must be power of 4')\n n = int(n)\n n_M_pos = np.array([1+2*i for i in xrange(n)])\n n_M_neg = np.array([-1-2*i for i in xrange(n)])\n choices = np.concatenate((n_M_pos, n_M_neg))\n return np.array(\n [np.random.choice(choices) + 1j * np.random.choice\n (choices) for i in xrange(length)])\n\n\ndef gfdm_tx(x, filtertype, alpha, M, K, L, N):\n '''\n x: Input-Symbols (length M*K)\n filtertype: ['rrc','rc']\n alpha: rolloff-factor\n M: number of timeslots\n K: number of subcarrier\n N: oversampling-factor\n '''\n A = transmitMatrix(filtertype, alpha, M, K, N)\n A = A*M\n tx =A.dot(x)\n return tx\n\n\ndef gfdm_rx(y, filtertype, alpha, M, K, L, N, QAM, J):\n '''\n y: Transmit-Symbols (length M*K*N)\n filtertype: ['rrc','rc']\n alpha: rolloff-factor\n rx_strat: ['zf','mf']\n M: number of timeslots\n K: numbor of subcarrier\n N: oversampling-factor\n '''\n A = transmitMatrix(filtertype, alpha, M, K, N)\n #if rx_strat == \"zf\":\n # A_rx = np.linalg.pinv(A)\n #else:\n #A_rx = np.linalg.pinv(A)/M\n A_rx = A.conj().transpose()\n rx = np.array([])\n rx = A_rx.dot(y)\n return rx\n\n\ndef gfdm_tx_fft(x, filtertype, alpha, M, K):\n '''\n Realization of GFDM-Transmitter in FFT:\n Required input: x a np.array of length M*K\n FFT is applied in shifted version (zero-frequency term is centered)\n First symbol is on -freq_max and last symbol ist on freq_max\n h: Prototype-filter impulse response\n s_e[n]:[s_0[n] 0{M-1} s_1[n] .... s_N-1[n] 0{M-1}]\n x[n] = h (*) (IFFT(s_e[n]))\n x_gfdm = sum_M(circshift(x[n],nN))\n '''\n if filtertype == \"rrc\":\n time_h, h = cp.rrcosfilter(M*K, alpha, K, 1)\n elif filtertype == \"rc\":\n time_h, h = cp.rcosfilter(M*K, alpha, K, 1)\n # Initialization of output vector\n x_out = np.zeros(M*K, dtype='complex')\n # circulary move filter window to symbol 0\n h = np.roll(h, -(M*K/2))\n # for each gfdm-block\n # for each timeslot\n for m in xrange(M):\n # select the K next symbols\n #symbols = np.fft.ifftshift(x[(m*K):(m+1)*K])\n symbols = np.fft.ifftshift(np.array([x[k*M+m] for k in xrange(K)]))\n # transform K symbols to K carriertones in time-domain\n sym_t = np.fft.ifft(symbols)\n sym_te = np.array([])\n # Repeat result M-times in a vector\n for m2 in xrange(M):\n sym_te = np.concatenate((sym_te, sym_t))\n # multipy with transmit filter -> better convolve?\n sym_te = np.convolve(sym_te, h, mode='same')\n #sym_te = np.multiply(sym_te,h)\n # shift result m*K samples to the right and add it up to the result\n # vector\n x_out = np.add(x_out, np.roll(sym_te, m*K))\n\n return x_out\n\n\ndef gfdm_tx_fft2(x, filtertype, alpha, M, K, L, N):\n '''\n x: Input-Array (length: M*K symbols)\n filtertype: ('rrc'|'rc')\n alpha: (0,1) float\n M: number of slots\n K: number of subcarriers\n L: freq-domain length of filter\n\n Low-complexity transmitter implementation as proposed by G. Fettweis\n '''\n if filtertype == \"rrc\":\n time_h, h = cp.rrcosfilter(M*K, alpha, K, 1)\n elif filtertype == \"rc\":\n time_h, h = cp.rcosfilter(M*K, alpha, K, 1)\n h = np.roll(h, h.shape[-1]/2)\n H = np.fft.fft(h)\n H_sparse = np.concatenate((H[0:(M*L)/2], H[-(M*L)/2:]))\n # Sort Input subcarrierwise\n x = reshape_input(x, M, K)\n x_out = np.zeros((M*K)+(L-1)*M, dtype='complex')\n for k in xrange(K):\n # M rows and L columns with respective FFT output\n # pick symbols per subcarrier\n x_k = x[k*M:((k+1)*M)]\n # perform fft and switch to frequency domain\n x_f = np.fft.fft(x_k)\n # copy values of M-point DFT to obtain MK-point DFT\n x_f_L = np.tile(x_f, L)\n # make data-vector 'sparse'\n #x_f_L = np.concatenate((x_f_K[0:(M*L)/2], x_f_K[-(M*L)/2:]))\n # filter with sparse filter taps in frequency domain\n x_fil = np.multiply(x_f_L, H_sparse)\n # Add data-vector to correct position -max neg frequency : 0 :\n # max_pos_frequency\n x_out[k*M:(k+L)*M] = x_out[k*M:(L+k)*M] + np.fft.fftshift(x_fil)\n # Add 'oversampled' parts of first subcarrier to end and 'oversampled' parts\n # of last subcarrier to start\n x_first = x_out[0:(L-1)*M/2]\n x_last = x_out[-(L-1)*M/2:]\n x_out = x_out[(L-1)*M/2:-(L-1)*M/2]\n x_out[0:(L-1)*M/2] = x_out[0:(L-1)*M/2] + x_last\n x_out[-(L-1)*M/2:] = x_out[-(L-1)*M/2:] + x_first\n x_t = np.fft.ifft(np.fft.ifftshift(x_out))\n x_t = (1.0/K)*x_t\n return x_t\n\n\ndef gfdm_rx_fft2(y, filtertype, alpha, M, K, L, N, QAM,J):\n '''\n y: transmitted gfdm-block (length: M*K samples)\n filtertype: ('rrc'|'rc')\n alpha: (0,1) float\n M: number of slots\n K: number of subcarriers\n L: freq-domain length of filter\n Low-complexity receiver implementation as proposed by G.Fettweis\n (based on sparse frequency Domain Processing)\n\n output: demodulated samples in original order (first K samples in timeslot 1, second K ...)\n '''\n if filtertype == \"rrc\":\n time_h, h = cp.rrcosfilter(M*K, alpha, K, 1)\n h = np.roll(h, h.shape[-1]/2)\n H_rx = np.fft.fft(h)\n H_sparse = np.concatenate((H_rx[0:M*L/2], H_rx[-M*L/2:]))\n y_ifft = np.array([])\n y = (1.0/K)*y\n # Transfer input to frequency domain and center around 0th frequency bin\n y_f = np.fft.fftshift(np.fft.fft(y))\n # Filter and superposition in frequency domain\n Y_fs = gfdm_rx_filsup(y_f, H_sparse, M, K, L)\n # Demodulate per subcarrier\n y_ifft = gfdm_rx_demod(Y_fs, K)\n if J>0:\n y_ifft = gfdm_rx_sic(K,M,J,H_sparse,y_ifft,Y_fs,QAM)\n y_ifft = np.reshape(y_ifft,(K*M))\n # Sort output in timeslot,subcarrier order\n y_ifft = reshape_input(y_ifft, K, M)\n return y_ifft\n\ndef gfdm_rx_demod(Y_fs, K):\n '''\n Y_fs: received samples filtered and superpositioned in frequency domain (not centered) KxM-array\n K: Number of subcarriers\n\n output: demodulated samples in subcarrier order (first M samples are on subcarrier 1, second M....)\n '''\n y_ifft = np.array([])\n for k in xrange(K):\n y_ifft = np.concatenate((y_ifft, np.fft.ifft(Y_fs[k])))\n return y_ifft\n\ndef gfdm_rx_filsup(y_f, H_sparse, M, K, L):\n '''\n y_f: input samples centered in frequency domain 1xK*M-array\n H_sparse: Rx-filter per subcarrier - length (M*L)\n M: number of time slots\n K: number of subcarrier\n L: width of sparse Rx-filter in number of subcarrier\n\n output: (K,M) - array\n '''\n y_out = np.empty((K,M),dtype='complex')\n y_f = np.concatenate((y_f[-(L-1)*M/2:],y_f,y_f[0:(L-1)*M/2]))\n for k in xrange(K):\n # select kth subcarrier\n y_down = y_f[k*M:(k+L)*M]\n # 'uncenter' in Frequency domain\n y_down = np.fft.ifftshift(y_down)\n # apply filter in frequency domain (not centered)\n y_filter = np.multiply(y_down, H_sparse)\n # Superposition L samples in frequency domain\n y_out[k] = np.sum(y_filter.reshape(L, M), axis=0)\n return y_out\n\n\n\ndef gfdm_rx_sic(K,M,J,H_sparse,d_rx,Y_fs,QAM):\n '''\n K: Number of subcarriers\n M: Number of slots\n J: Number of Iterations for Interference Cancellation\n H_sparse: Rx-filter of length M*L in frequency domain\n d_rx: mapped symbols before Interference cancellation (sorted by subcarrier)\n Y_fs: filtered, superpositioned input samples in frequency domain (not centered) KxM-array\n QAM: QAM order\n '''\n # Receive all subcarriers in F-Domain\n # map each symbol to closest QAM - Point\n # d_rx s\n qam_mod = cp.QAMModem(QAM)\n # Calculate rising/falling flank interference coefficients\n H_rf = np.multiply((H_sparse[0:M]/K),(H_sparse[M:]/K))\n # Reshape mapped symbols into per-subcarrier array\n d_p = np.empty((K,M),dtype='complex')\n # d_p (K,M)\n for k in xrange(K):\n d_p[k] = qam_mod.mapping(d_rx[k*M:(k+1)*M],'hard')\n for j in xrange(J):\n y = np.empty((K,M),dtype='complex')\n for k in xrange(K):\n y[k] = Y_fs[k] - H_rf*np.fft.fft(d_p[(k-1) % K] + d_p[(k+1) % K])\n # Recalculate d_rx\n d_rx = gfdm_rx_demod(y,K)\n for k in xrange(K):\n d_p[k] = d_rx[k*M:(k+1)*M]\n d_p[k] = qam_mod.mapping(d_p[k], 'hard')\n return d_rx\n\n\ndef sync_symbol(filtertype, alpha, K, n_mod, N):\n '''\n Generate Schmidls Training Symbols to achieve Receiver Synchronisation\n K: should be an odd number\n Process:\n * First Symbol: Transmit PN-Sequence on all even frequencies while zeros on the odd\n frequencies. Constant signal energy -> Multiply every Symbol with sqrt(2)\n\n * Second Symbol: Transmit PN-Sequence on all odd frequencies and another PN-Sequence\n on the even frequencies\n\n\n '''\n pn_order = 14\n pn_seed = '00101101010010'\n pn_mask = '01001110100111'\n if int(np.floor(K/2.0)) % 2:\n n_even_freq = int(np.floor(K/2.0))\n else:\n n_even_freq = int(np.ceil(K/2.0))\n seq_length = n_even_freq*n_mod\n sym_sequence = np.zeros(K, dtype='complex')\n pn_sequence = cp.pnsequence(pn_order, pn_seed, pn_mask, seq_length)\n qam_mod = cp.modulation.QAMModem(2**n_mod)\n qam_sequence = qam_mod.modulate(pn_sequence)\n for i in xrange(len(sym_sequence)):\n if not i % 2:\n sym_sequence[i] = qam_sequence[i/2]\n ifft_sequence = np.fft.ifftshift(sym_sequence)\n output = gfdm_tx(ifft_sequence, filtertype, alpha, 1, K, N)\n # output = np.fft.ifft(np.sqrt(2)*ifft_sequence)\n\n return output\n\n\ndef sync_symbol2(filtertype, alpha, K, L, n_mod):\n pn_order = 14\n pn_seed = '01001000111011'\n pn_mask = '01001101001110'\n seq_length = K*n_mod\n pn_sequence = cp.pnsequence(pn_order, pn_seed, pn_mask, seq_length)\n qam_mod = cp.modulation.QAMModem(2**n_mod)\n qam_sequence = qam_mod.modulate(pn_sequence)\n output = gfdm_tx_fft2(np.tile(qam_sequence, 2), filtertype, alpha, 2, K, 2, 1)\n return output\n\n\ndef sync_product(x, L):\n '''\n Auto-Korrelation der ersten L Samples mit den naechsten L Samples\n '''\n return np.sum([x[i].conj()*x[i+L] for i in xrange(L)])\n\n\ndef sync_iter(x, L, cp):\n '''\n Schrittweise Iteration ueber alle Samples (zunaechst die ersten 2*L Samples)\n Danach ueber die restlichen len(x)-2*L Samples\n '''\n P_d = np.array([])\n P_d = np.append(P_d, sync_product(x, L))\n for i in xrange(len(x)-2*L):\n P_d = np.append(\n P_d, P_d[i] + (x[L + i].conj() * x[2 * L + i]) -\n (x[i].conj() * x[L + i]))\n P_d_out = P_d\n P_d = np.append(np.zeros(cp, dtype='complex'), P_d)\n # Integrate cp-samples to eliminate cp-plateau\n P_di = np.array([])\n for i in xrange(cp, len(x)-2*L):\n P_di = np.append(\n P_di, (1.0/(cp+1)*np.sum(np.abs(P_d[i-cp:i])**2)))\n return (P_di, P_d_out)\n\n\ndef sync_energy(x, L):\n '''\n Berechnung der Energie der zweiten Haelfte der Sync-Samples -> normieren\n '''\n R_d = np.array([])\n R_d = np.append(R_d, np.sum([np.abs(x[i+L])**2 for i in xrange(L)]))\n for i in xrange(len(x)-2*L):\n R_d = np.append(R_d, R_d[-1]+np.abs(x[2*L+i])**2-np.abs(x[L+i])**2)\n return R_d\n\n\ndef sync_perform(x, L, cp):\n (P_di, P_d) = sync_iter(x, L, cp)\n #R_d = sync_energy(x, L)\n #M_d = (np.abs(P_d)**2)/(R_d**2)\n return (P_di, P_d)\n\n\ndef sync_CFO(P_d, P_di):\n '''\n Gewinn von d (Beginn der Pilotsequenz) und d_f Frequenzoffset genormt auf 1/T.\n Kann bei nur einem Pilotsymbol nur +/- 1/T betragen.\n '''\n d = np.argmax(P_di)\n dphi = np.angle(P_d[d])\n d_f = dphi/(np.pi)\n print(\"P_d:{},df:{})\".format(P_d[d], d_f))\n\n return (d, d_f)\n\n\ndef add_cp(x, n):\n return np.append(x[-n:], x)\n\n\ndef reshape_input(x, M, K):\n '''\n 1. pick every m*Kth symbol and append to output.\n 2. Increase counter one time\n 3. perform step 1.+2. M times\n '''\n x_out = np.array([])\n for k in xrange(K):\n for m in xrange(M):\n x_out = np.append(x_out, x[(m*K)+k])\n return x_out\n","sub_path":"python/pygfdm/modulation.py","file_name":"modulation.py","file_ext":"py","file_size_in_byte":14331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"517644571","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 23 11:28:39 2020\n\n@author: Claudio Collado\n\n\"\"\"\n#Ejercicio 4.30\n\nimport csv\nimport matplotlib.pyplot as plt\n\ndef leer_arboles(nombre_archivo):\n arboleda = []\n f = open(nombre_archivo,'r',encoding = 'utf8')\n filas = csv.reader(f)\n encabezado = next(filas)\n for fila in filas:\n diccionario_arbol = dict(zip(encabezado,fila))\n arboleda.append(diccionario_arbol)\n return arboleda\n \narboleda = leer_arboles('arbolado-en-espacios-verdes.csv')\n\naltos = [float(arbol['altura_tot']) for arbol in arboleda if arbol['nombre_com'] == 'Jacarandá']\n\nplt.hist(altos,bins='auto')\n\n\n\n","sub_path":"4. Aleatoridad/4.5 Gráficos del Arbolado porteño/ejercicio_4.30.py","file_name":"ejercicio_4.30.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"276392384","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Nov 22 09:55:49 2019\r\n\r\n@author: samde\r\n\"\"\"\r\n\r\n\"\"\"\r\nquand un des deux joueur a 2 points de différence avec l'autre il gagne le jeu\r\n\r\npour gagner un set il faut 2 jeu d'avance\r\n\r\n6 jeu = 1 set\r\n\r\npour gagner il faut 2 jeu d'avance sur l'autre\r\n\r\n6 jeu max par joueurs\r\n\r\npour gagner la partie il faut 2 set d'avance\r\n\r\n/!\\ : si le joueur arrive a 6 jeu et qui y a pas 2 jeu de diff : JEU DECISIF\r\n-> on compte les points de 1 a 7, il faut deux points de diff pour gagner un set\r\n\r\nBrouillon :\r\n \r\ndef jeu_v1():\r\n point_j1 = 0\r\n point_j2 = 0\r\n \r\n joueur_1_gagnant = None\r\n jeu_finis = False\r\n while jeu_finis != True :\r\n gagnant = int (input(\"quel joueur a gagner le point ? 1 ou 2\\n\"))\r\n if gagnant == 1 :\r\n point_j1 += 1 \r\n elif gagnant == 2:\r\n point_j2 += 1\r\n \r\n jeu_finis, joueur_1_gagnant = j1_as_win_jeu(point_j1,point_j2)\r\n if joueur_1_gagnant == True :\r\n print(\"joueur 1 a gagner\")\r\n else:\r\n print(\"joueur 2 a gagner\")\r\n\r\n#\"\"\"\r\n\r\ndef j1_as_win_jeu(score_j1,score_j2):\r\n diff_score = score_j1-score_j2\r\n j_as_win = False\r\n j1_win = None\r\n\r\n if diff_score >=2 :\r\n j1_win = True\r\n j_as_win = True\r\n elif diff_score <= -2:\r\n j1_win = False\r\n j_as_win = True\r\n return j_as_win,j1_win\r\n\r\ndef jeu_v2(liste_de_point):\r\n point_j1 = 0\r\n point_j2 = 0\r\n \r\n joueur_1_gagnant = None\r\n jeu_finis = False\r\n for g in list(liste_de_point):\r\n gagnant = int(g)\r\n if gagnant == 1 :\r\n point_j1 += 1 \r\n elif gagnant == 2:\r\n point_j2 += 1\r\n \r\n jeu_finis, joueur_1_gagnant = j1_as_win_jeu(point_j1,point_j2)\r\n \r\n if jeu_finis == True:\r\n if joueur_1_gagnant == True :\r\n print(\"joueur 1 a gagner le jeu\")\r\n else:\r\n print(\"joueur 2 a gagner le jeu\")\r\n return joueur_1_gagnant\r\n\r\ndef set_tennis():\r\n set_gagnant_j1 = 0\r\n set_gagnant_j2 = 0\r\n partie_finie = False\r\n set_decisif = False\r\n #tant que le score des deux joueurs est différent et strictement plus petit que 6 ou le score des deux joueurs est 6 et egal (set decisif)\r\n while partie_finie == False:\r\n jeu = input(\"entrez le score:\\n\")\r\n j1_win = jeu_v2(jeu)\r\n if j1_win == True :\r\n set_gagnant_j1 += 1\r\n else :\r\n set_gagnant_j2 += 1\r\n \r\n if abs(set_gagnant_j1-set_gagnant_j2)>=2:\r\n partie_finie = True\r\n elif set_gagnant_j1==6 and set_gagnant_j2==6 :\r\n partie_finie = True\r\n set_decisif = True\r\n \r\n j1_win = None\r\n if partie_finie == True and set_decisif == False :\r\n if set_gagnant_j1-set_gagnant_j2>0:\r\n print(\"joueur 1 a gagner le set\")\r\n j1_win = True\r\n else:\r\n print(\"joueur 2 a gagner le set\")\r\n j1_win = False\r\n else:\r\n j1_win = jeu_decisif()\r\n return j1_win\r\n\r\ndef jeu_decisif():\r\n j1_win = jeu_v2(input(\"ecrir les score du j1 et j2 : ex 1122212121211\\n\")) \r\n if j1_win == True :\r\n print(\"joueur 1 a gagner\")\r\n else:\r\n print(\"joueur 2 a gagner\")\r\n return j1_win\r\n\r\ndef match(nb_set_gagnant):\r\n set_j1 = 0\r\n set_j2 = 0\r\n while set_j1 < nb_set_gagnant and set_j2 < nb_set_gagnant :\r\n j1_win = set_tennis()\r\n if j1_win == True :\r\n set_j1 += 1\r\n else:\r\n set_j2 += 1\r\n if set_j1 == nb_set_gagnant :\r\n print(\"joueur 1 remporte le match\")\r\n else:\r\n print(\"joueur 2 remporte le match\")","sub_path":"Python Project/TD/Archive/Samuel/Tenis.py","file_name":"Tenis.py","file_ext":"py","file_size_in_byte":3644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"356765811","text":"from django.http import HttpResponse, HttpResponseNotFound\nfrom django.shortcuts import render, get_object_or_404\nfrom django.contrib.auth.decorators import user_passes_test\nfrom .models import Leaders\nfrom user.models import Player\nfrom quiz.forms import UserAnswer\nfrom django.core.mail import send_mail\nfrom django.contrib import messages\n\nfrom django.contrib.admin.views.decorators import staff_member_required\n\n\n# Create your views here.\n@staff_member_required\ndef email_users(request) :\n player = Player.objects.all()\n return render(request, 'home/emails.html', {'players':player})\n\n\ndef not_logged_in(user):\n return not user.is_authenticated\n\n\ndef base(request):\n return render(request, 'home/base.html')\n\n\ndef home(request):\n return render(request, 'home/home.html')\n\n\ndef hello(request):\n return render(request, 'home/hello.html')\n\n\ndef rules(request):\n return render(request, 'home/rule.html')\n\n\n@staff_member_required\ndef page(request):\n \"Only After 1st Round is complete\"\n\n p = get_object_or_404(Leaders, pk=1)\n n = p.playerNum\n lst = [0, 1, 2]\n form = UserAnswer\n\n if request.method == 'GET':\n # print(n)\n j = 1\n leaders = Player.objects.order_by(\n '-score', 'last_submit')[:n]\n\n email_list = []\n\n for i in leaders:\n i.rank = j\n j += 1\n i.save()\n\n email_list.append(i.email)\n\n print(email_list)\n return render(request, 'home/page.html', {\"n\": n, \"leaders\": leaders, \"form\": form, \"lst\": lst[0]})\n\n if request.method == \"POST\": # if the admin submits the passcode\n my_form = UserAnswer(request.POST)\n\n if my_form.is_valid():\n ans = my_form.cleaned_data.get(\"answer\")\n organs = \"AlohaMoraHarryPotter\"\n\n \n\n # correct answer\n if (str(organs) == str(ans)): # if the answer is correct\n leaders = Player.objects.order_by(\n '-score', 'last_submit')[:n]\n for x in leaders:\n x.level2 = 0 \n \n x.save()\n print(x.name)\n\n with open('text_messages/login_user.txt', 'r') as file:\n data_email = file.read()\n\n send_mail(\n 'Congrats, you cleared round 1 !',\n str(data_email).format(x.name),\n 'ieeesbnitd@gmail.com',\n [x.email],\n fail_silently=True,\n )\n\n\n\n return render(request, 'home/page.html', {\"n\": n, \"leaders\": leaders, \"form\": form, \"lst\": lst[1]})\n\n # incorrect answer\n else: # returns the same page\n leaders = Player.objects.order_by(\n '-score', 'last_submit')[:n]\n return render(request, 'home/page.html', {\"n\": n, \"leaders\": leaders, \"form\": form, \"lst\": lst[2]})\n else:\n return HttpResponse('

    Your Form Data was Invalid

    ')\n\n\ndef error_404(request, exception):\n data = {}\n return render(request,'home/404.html', data)\n\n\n\n","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"537013231","text":"import sys\nimport numpy as np\n\nsys.path.append(\"..\")\nfrom Game import Game\nfrom .Connect4Logic import *\n\n\nclass Connect4Game(Game):\n \"\"\"\n Connect4 Game class implementing the alpha-zero-general Game interface.\n \"\"\"\n\n def __init__(self, height=None, width=None, win_length=None, np_pieces=None):\n Game.__init__(self)\n board = Board(height, width, win_length, np_pieces)\n self.height = board.height\n self.width = board.width\n self.win_length = board.win_length\n self.np_pieces = np_pieces\n\n def getInitBoard(self):\n return Board(self.height, self.width, self.win_length, self.np_pieces)\n\n def getBoardSize(self):\n return (self.height, self.width)\n\n def getActionSize(self):\n return self.width\n\n def getNextState(self, board, player, action):\n \"\"\"Returns the board with updated move, original board is modified.\"\"\"\n board.add_stone(action, player)\n return board, -player\n\n def getValidMoves(self, board, player):\n \"Any zero value in top row in a valid move\"\n try:\n return board.get_valid_moves(player)\n except AttributeError:\n board = Board(self.height, self.width, self.win_length, board)\n return self.getValidMoves(board, player)\n\n def getGameEnded(self, board, player):\n try:\n winstate = board.get_win_state()\n if winstate.is_ended:\n if winstate.winner is None:\n # draw has very little value.\n return 1e-4\n elif winstate.winner == player:\n return +1\n elif winstate.winner == -player:\n return -1\n else:\n raise ValueError(\"Unexpected winstate found: \", winstate)\n else:\n # 0 used to represent unfinished game.\n return 0\n # TODO: Really, really need a better workaround\n except AttributeError:\n board = Board(self.height, self.width, self.win_length, board)\n return self.getGameEnded(board, player)\n\n def getCanonicalForm(self, board, player):\n # Flip player from 1 to -1\n return np.copy(board.np_pieces)\n\n def getSymmetries(self, board, pi):\n \"\"\"Board is left/right board symmetric\"\"\"\n return [(board, pi), (board[:, ::-1], pi[::-1])]\n\n def stringRepresentation(self, board):\n return board.tostring()\n\n @staticmethod\n def display(board):\n print(\" -----------------------\")\n print(\" \".join(map(str, range(len(board[0])))))\n print(board)\n print(\" -----------------------\")\n\n def getModelBoard(self, canonicalBoard, player=1):\n # TODO: Rename\n return Board(self.height, self.width, self.win_length, canonicalBoard)\n\n def getNextPlayer(self, board):\n pieces_1 = 0\n pieces_2 = 0\n for y in range(self.width):\n for x in range(self.height):\n if board[x][y] == 1:\n pieces_1 += 1\n if board[x][y] == -1:\n pieces_2 += 1\n if pieces_1 > pieces_2:\n return -1\n else:\n return 1\n\n\nclass InvisibleConnect4Game(Connect4Game):\n \n def __init__(self, height=None, width=None, win_length=None, np_pieces=None):\n super().__init__(height, width, win_length, np_pieces)\n board = InvisibleBoard(height, width, win_length, np_pieces)\n\n def getInitBoard(self):\n return InvisibleBoard(self.height, self.width, self.win_length, self.np_pieces)\n\n def getNextState(self, board, player, action):\n if board.add_stone(action, player):\n # Weird solution that'll probably work\n next_player = self.getNextPlayer(board)\n return (board, next_player)\n else:\n return (board, player)\n\n def getCanonicalForm(self, board, player):\n # Flip player from 1 to -1\n return np.copy(board.visible_pieces[player])\n\n def getModelBoard(self, canonicalBoard, player):\n # TODO: Rename\n return InvisibleBoard(self.height, self.width, self.win_length, canonicalBoard, player)\n\n @staticmethod\n def display(board):\n print(\" -----------------------\")\n print(\" \".join(map(str, range(len(board[0])))))\n print(board)\n print(board.visible_pieces[1])\n print(board.visible_pieces[-1])\n print(\" -----------------------\")\n","sub_path":"connect4/Connect4Game.py","file_name":"Connect4Game.py","file_ext":"py","file_size_in_byte":4479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"515639851","text":"\r\n# datamodel class를 생성한다.\r\nclass DataModel:\r\n def __init__(self):\r\n print(\"데이터 모델 입니다.\")\r\n self.myLoginInfo = None\r\n self.itemList = []\r\n\r\n class Logininfo:\r\n def __init__(self, accCnt, accList, userId, userName, keyBSEC, firew, serverGubun):\r\n self.accCnt = accCnt\r\n self.accList = accList\r\n self.userId = userId\r\n self.userName = userName\r\n self.keyBSEC = keyBSEC\r\n self.firew = firew\r\n self.serverGubun = serverGubun\r\n\r\n def getServerGubun(self):\r\n if self.serverGubun == '1':\r\n return \"모의투자\"\r\n else:\r\n return \"실서버\"\r\n\r\n # 종목관리를 위한 클래스\r\n class ItemInfo:\r\n def __init__(self, itemCode, itemName):\r\n self.itemCode = itemCode\r\n self.itemName = itemName","sub_path":"dataModel.py","file_name":"dataModel.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"474031080","text":"from plug_manager_template import create_plug, ExtendedGenericManagerDescriptor\nfrom rboxfileplug import FileManager\nfrom models import RboxFileConnector, RboxFile\nfrom south.modelsinspector import add_introspection_rules\n\nclass SingleFileManagerDescriptor(ExtendedGenericManagerDescriptor):\n \"\"\"\n This class provides the functionality that makes the related-object\n managers available as attributes on a model class, for fields that have\n multiple \"remote\" values and have a GenericRelation defined in their model\n (rather than having another model pointed *at* them). In the example\n \"article.publications\", the publications attribute is a\n ReverseGenericRelatedObjectsDescriptor instance.\n \"\"\"\n \n def __init__(self, field, field_identifier, max_count=1, manager_kwargs=None):\n if max_count > 1:\n raise TypeError(\"max_count in a singlefileplug should be always 1\")\n self.field = field\n self.field_identifier = field_identifier\n self.max_count = max_count\n self.manager_kwargs = manager_kwargs\n \n\n def __get__(self, instance, instance_type=None, return_manager=False):\n manager = super(SingleFileManagerDescriptor, self).__get__(instance, instance_type=None)\n if return_manager:\n return manager\n try:\n return manager.all()[0]\n except IndexError:\n return None\n \n\n def __set__(self, instance, value):\n if instance is None:\n raise AttributeError(\"Manager must be accessed via instance\")\n \n if not isinstance(value, RboxFile):\n raise TypeError(\"Only accepts a RboxFile object\")\n \n manager = self.__get__(instance, return_manager=True) \n manager.remove(manager.all()[0])\n manager.add(value)\n\n\nRboxSingleFilePlug = create_plug(manager=FileManager, descriptor_cls=SingleFileManagerDescriptor, to=RboxFileConnector)\n\nrboxsinglefileplug_introspection_rules = [((RboxSingleFilePlug,),[],{\"field_identifier\": [\"field_identifier\",{}],},)]\nadd_introspection_rules(rboxsinglefileplug_introspection_rules, [\"filemanager.models.RboxSingleFilePlug\"])\n","sub_path":"rboxsinglefileplug.py","file_name":"rboxsinglefileplug.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"453915373","text":"class Solution(object):\n def removeDuplicates(self, nums):\n i=0\n j=i+1\n while j!=len(nums) and nums:\n if nums[i]==nums[j]:\n j+=1\n else:\n nums[i+1]=nums[j]\n i+=1\n j+=1\n return i+1\n'''\nRuntime: 60 ms, faster than 95.81% of Python online submissions for Remove Duplicates from Sorted Array.\nMemory Usage: 13.5 MB, less than 87.50% of Python online submissions for Remove Duplicates from Sorted Array.\n'''\n\nif __name__ == '__main__':\n nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]\n sol=Solution()\n ans=sol.removeDuplicates(nums)\n print('non-duplicated:',ans)\n for i in range(ans):\n print(nums[i])","sub_path":"26. Remove Duplicates from Sorted Array/doublePointer1.py","file_name":"doublePointer1.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"392476852","text":"from packages.datapoint import Datapoint\nimport csv\nimport os\nimport ntpath\nimport numpy as np\nimport random as rnd\nimport matplotlib.pyplot as plt\n\n\nclass SimulatorDatasetImporter(object):\n def __init__(self):\n self._dataset = []\n\n @property\n def dataset(self):\n return self._dataset\n\n def clear_dataset(self):\n self._dataset = []\n\n def append_dataset(self, csv_file_path, exclude_angles: list=None):\n if os.path.isfile(csv_file_path) is False:\n raise FileNotFoundError('Could not read csv in DatasetImporter.')\n\n csv_directory = ntpath.dirname(csv_file_path)\n csv_directory = os.path.join(csv_directory, 'IMG')\n with open(csv_file_path) as f:\n reader = csv.reader(f)\n for row in reader:\n\n angle = float(row[3])\n if exclude_angles is not None and angle in exclude_angles:\n continue\n\n datapoint = Datapoint(os.path.join(csv_directory, ntpath.basename(row[0])),\n os.path.join(csv_directory, ntpath.basename(row[1])),\n os.path.join(csv_directory, ntpath.basename(row[2])),\n float(row[3]),\n float(row[4]),\n float(row[5]),\n float(row[6]))\n self._dataset.append(datapoint)\n\n def harmonize_angles(self,\n epsilon=1e-1,\n exclude_angles: list=None,\n exclude_less_than=None,\n random_sample_max_to=None,\n center=False,\n show_histogram=False):\n\n # collect all angles in a dictionary\n angles_dict = {}\n for element in self._dataset:\n rounded = float(int(element.steering_angle / epsilon) * epsilon)\n if rounded not in angles_dict:\n angles_dict[rounded] = []\n # building up the histogram\n angles_dict[rounded].append(element)\n\n if show_histogram:\n self.visualize_dataset_frequencies(angles_dict, 'Non-normalized steering angles')\n\n # Random sample the maximum to x\n if random_sample_max_to is not None:\n max_entries_key = sorted([(k, len(angles_dict[k])) for k in angles_dict],\n key=lambda x: x[1],\n reverse=True)[0][0]\n rnd.shuffle(angles_dict[max_entries_key])\n angles_dict[max_entries_key] = angles_dict[max_entries_key][:random_sample_max_to]\n\n # Exclude some angles\n if exclude_angles is not None:\n for angle_to_ex in exclude_angles:\n angles_dict.pop(angle_to_ex)\n\n # Exclude rare occurrences\n to_pop = []\n if exclude_less_than is not None:\n for angle_k in angles_dict:\n if len(angles_dict[angle_k]) < exclude_less_than:\n to_pop.append(angle_k)\n for tp in to_pop:\n angles_dict.pop(tp)\n\n # Center the steering angles\n if center is True:\n max_angle = float(np.max([float(k) for k in angles_dict.keys()]))\n min_angle = float(np.min([float(k) for k in angles_dict.keys()]))\n\n if abs(min_angle) > max_angle:\n min_angle = -max_angle\n if max_angle > abs(min_angle):\n max_angle = abs(min_angle)\n\n to_pop = []\n for angle_k in angles_dict:\n if angle_k > max_angle or angle_k < min_angle:\n to_pop.append(angle_k)\n\n for tp in to_pop:\n angles_dict.pop(tp)\n\n # Calc the maximum count of a rounded steering angle\n angle_max_count = np.max(np.array([len(angles_dict[k]) for k in angles_dict]))\n\n # Now, fill up a new dictionary with indices\n angles_dict_harmonize = angles_dict.copy()\n\n for k in angles_dict_harmonize:\n needed_for_fill = angle_max_count - len(angles_dict[k])\n for i in range(needed_for_fill):\n angles_dict_harmonize[k].append(rnd.choice(angles_dict[k]))\n\n # Overwrite dataset with harmonized version of itself\n self._dataset = []\n for k in angles_dict_harmonize:\n for element in angles_dict_harmonize[k]:\n self._dataset.append(element)\n\n if show_histogram:\n self.visualize_dataset_frequencies(angles_dict_harmonize, 'Normalized steering angles')\n # Done\n return\n\n def visualize_dataset_frequencies(self, y, title: str):\n # count the frequencies of classes in dataset and visualize\n hist = {}\n\n for label_id in sorted(y.keys()):\n hist[label_id] = len(y[label_id])\n\n # visualize as histogram\n fig = plt.figure(figsize=(16, 12))\n sub = fig.add_subplot(1, 1, 1)\n sub.set_title(title)\n y_data = np.array([float(hist[k]) for k in hist])\n plt.bar(range(len(hist)), y_data, align='center')\n x_axis = np.array([k for k in hist])\n plt.xticks(range(len(hist)), x_axis, rotation='vertical', fontsize=8)\n plt.subplots_adjust(bottom=0.4)\n plt.show()\n","sub_path":"packages/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":5340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"388285014","text":"from __future__ import print_function\n\nimport requests\nfrom frinx_rest import odl_url_base, odl_headers, odl_credentials, parse_response\n\nfrom string import Template\n\nodl_url_components = odl_url_base + \"/operational/network-topology:network-topology/topology/unified/node/$id/yang-ext:mount/frinx-openconfig-platform:components\"\n\n\ndef read_components(task):\n device_id = task['inputData']['id']\n\n id_url = Template(odl_url_components).substitute({\"id\": device_id})\n\n r = requests.get(id_url, headers=odl_headers, auth=odl_credentials)\n response_code, response_json = parse_response(r)\n\n if response_code == requests.codes.ok:\n return {'status': 'COMPLETED', 'output': {'url': id_url,\n 'response_code': response_code,\n 'response_body': response_json},\n 'logs': []}\n else:\n return {'status': 'FAILED', 'output': {'url': id_url,\n 'response_code': response_code,\n 'response_body': response_json},\n 'logs': []}\n\n\ndef start(cc):\n print('Starting Platform workers')\n\n cc.start('OC-PLATFORM_read_components', read_components, False)\n","sub_path":"microservices/netinfra_utils/workers/platform_worker.py","file_name":"platform_worker.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"134301293","text":"import os\nimport random\n\nfrom flask import Flask ,render_template\n\nfrom . import db\n\ndef create_app(test_config=None):\n app = Flask(\"todolist\")\n app.config.from_mapping(\n DATABASE=os.path.join(app.instance_path,'todo.db')\n )\n if test_config is not None:\n app.config.update(test_config)\n \n try:\n os.makedirs(app.instance_path)\n except OSError:\n pass\n \n from . import todo\n app.register_blueprint(todo.bp)\n \n from . import db\n db.init_app(app)\n \n return app","sub_path":"project/todolist/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"425660330","text":"\"\"\" Page.py module implements a page \"\"\"\nfrom .html_parser import parse_html\nfrom .log import warn\n\nfrom .compat import urljoin, parse_qsl\n\nfrom .form import Form\nfrom re import findall\n\n\nclass Page(object):\n def __init__(self, url, html, headers, status_code, blacklist=[]):\n self.html = html\n self.headers = headers\n self.url = url\n self.status_code = status_code\n self.document = parse_html(html, url)\n\n self.blacklist = blacklist\n\n @property\n def get_url_parameters(self):\n _, _, url = self.url.partition(\"?\")\n return parse_qsl(url)\n\n def get_forms(self):\n \"\"\" Generator for all forms on the page. \"\"\"\n for form in self.document.findall('.//form[@action]'):\n generated = Form(self.url, form)\n\n if any([findall(x, generated.action) for x in self.blacklist]):\n continue\n\n yield generated\n\n def get_links(self):\n \"\"\" Generator for all links on the page. \"\"\"\n for link in self.document.findall('.//a[@href]'):\n href = link.attrib.get('href')\n yield urljoin(self.url, href)\n","sub_path":"webvulnscan/page.py","file_name":"page.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"544540923","text":"#coding=utf-8\n\n\nabc=list(map(int,input(\"input a b and c:\").split(\" \")))\n\n\nif abc[0]+abc[1]>abc[2] and abc[1]+abc[2]>abc[0] and abc[2]+abc[0]>abc[1]:\n\tp=0.5*(abc[0]+abc[1]+abc[2])\n\tprint('能构成三角形 面积是 %f' % (p*(p-abc[0])*(p-abc[1])*(p-abc[2]) )**0.5 )\nelse:\n\t print(\"不能构成三角形\")\n\n","sub_path":"Python-learning/2019course/python作业1/2_triangle.py","file_name":"2_triangle.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"166039811","text":"# 55분\n# 날짜를 넣으면 시작시간과 종료 시간을 반환하는 함수\n# 날짜는 고정되어 있으므로 시간, 분, 초만 생각하면 된다.\ndef time_log(line):\n # 2016년 9월 15일은 고정, 종료 시간, 프로세스 시간\n yymmdd, hhmmss, process = line.split()\n hh,mm,ss = hhmmss.split(':')\n hh,mm,ss = int(hh), int(mm), float(ss)\n # 소수점 연산의 경우 이진분수 표현 문제로 오류가 발생하므로 1000을 곱해 소수점 처리를 해준다.\n process= int(float(process[:-1])*1000)\n end_time = int((hh*3600 + mm*60 + ss)*1000)\n start_time = end_time - process + 1\n return start_time, end_time\n \ndef solution(lines):\n for idx in range(len(lines)):\n lines[idx] = time_log(lines[idx])\n # lines를 시작 시점을 기준으로 정렬\n lines.sort()\n max_cnt = 0\n for i in range(len(lines)):\n cnt = 0\n # 새로 시작하는 요소 앞의 1초를 탐색한다.\n target_time = lines[i][0]-1000\n for j in range(i+1):\n if lines[j][1] > target_time:\n cnt += 1\n if cnt > max_cnt:\n max_cnt = cnt\n return max_cnt\n\nprint(solution(\t[\"2016-09-15 01:00:04.002 2.0s\", \"2016-09-15 01:00:07.000 2s\"]))\n\n","sub_path":"Programmers/카카오 모의고사/2018 KAKAO BLIND RECRUITMENT/추석트래픽.py","file_name":"추석트래픽.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"644189640","text":"from .. import Parser, parser\n\nerrors = [\"virt-what: virt-what-cpuid-helper program not found in $PATH\"]\n\n\n@parser('virt-what')\nclass VirtWhat(Parser):\n\n @property\n def is_virtual(self):\n return self.generic != \"Baremetal\" and self.generic != 'Failed'\n\n @property\n def has_specific(self):\n return self.specific is not None and self.generic != self.specific\n\n def parse_content(self, content):\n if content and content[0] in errors:\n self.generic = 'Failed'\n self.specific = content[0]\n elif content:\n self.generic = content[0]\n self.specific = content[-1]\n else:\n self.generic = \"Baremetal\"\n self.specific = None\n","sub_path":"insights/parsers/virt_what.py","file_name":"virt_what.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"48408235","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\ndef countApplesAndOranges(s, t, a, b, apples, oranges):\n appleCount = 0\n orangeCount = 0\n fellPointApple = list(map(lambda apple: apple + a, apples))\n fellPointOrange = list(map(lambda orange: orange + b, oranges))\n\n for point in fellPointApple:\n if(s <= point <= t):\n appleCount += 1\n\n for point in fellPointOrange:\n if(s <= point <= t):\n orangeCount += 1\n\n print(appleCount)\n print(orangeCount)\n\n\nif __name__ == '__main__':\n st = input().split()\n\n s = int(st[0])\n\n t = int(st[1])\n\n ab = input().split()\n\n a = int(ab[0])\n\n b = int(ab[1])\n\n mn = input().split()\n\n m = int(mn[0])\n\n n = int(mn[1])\n\n apples = list(map(int, input().rstrip().split()))\n\n oranges = list(map(int, input().rstrip().split()))\n\n countApplesAndOranges(s, t, a, b, apples, oranges)\n","sub_path":"hackerrank/algorithms/implemantation/apple-and-orange/apple_and_orange.py","file_name":"apple_and_orange.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"352933496","text":"import copy\n\nimport lenstronomy.Util.util as util\nimport lenstronomy.Util.mask as util_maskl\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.ndimage as ndimage\nfrom lenstronomy.LensModel.Profiles.external_shear import ExternalShear\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\nfrom lenstronomy.LensModel.lens_model_extensions import LensModelExtensions\nimport lenstronomy.Util.class_creator as class_creator\nfrom lenstronomy.Analysis.lens_analysis import LensAnalysis\nfrom lenstronomy.Data.coord_transforms import Coordinates\nfrom lenstronomy.Data.imaging_data import Data\n\n\ndef text_description(ax, d, text, color='w', backgroundcolor='k', flipped=False):\n if flipped:\n ax.text(d - d / 40., d - d / 15., text, color=color, fontsize=15, backgroundcolor=backgroundcolor)\n else:\n ax.text(d / 40., d - d / 15., text, color=color, fontsize=15, backgroundcolor=backgroundcolor)\n\n\ndef scale_bar(ax, d, dist=1., text='1\"', color='w', flipped=False):\n if flipped:\n p0 = d - d / 15. - dist\n p1 = d / 15.\n ax.plot([p0, p0 + dist], [p1, p1], linewidth=2, color=color)\n ax.text(p0 + dist / 2., p1 + 0.01 * d, text, fontsize=15, color=color, ha='center')\n else:\n p0 = d / 15.\n ax.plot([p0, p0 + dist], [p0, p0], linewidth=2, color=color)\n ax.text(p0 + dist / 2., p0 + 0.01 * d, text, fontsize=15, color=color, ha='center')\n\n\ndef coordinate_arrows(ax, d, coords, color='w', arrow_size=0.05):\n d0 = d / 8.\n p0 = d / 15.\n pt = d / 9.\n deltaPix = coords.pixel_size\n ra0, dec0 = coords.map_pix2coord((d - d0) / deltaPix, d0 / deltaPix)\n xx_, yy_ = coords.map_coord2pix(ra0, dec0)\n xx_ra, yy_ra = coords.map_coord2pix(ra0 - p0, dec0)\n xx_dec, yy_dec = coords.map_coord2pix(ra0, dec0 + p0)\n xx_ra_t, yy_ra_t = coords.map_coord2pix(ra0 - pt, dec0)\n xx_dec_t, yy_dec_t = coords.map_coord2pix(ra0, dec0 + pt)\n\n ax.arrow(xx_ * deltaPix, yy_ * deltaPix, (xx_ra - xx_) * deltaPix, (yy_ra - yy_) * deltaPix,\n head_width=arrow_size * d, head_length=arrow_size * d, fc=color, ec=color, linewidth=1)\n ax.text(xx_ra_t * deltaPix, yy_ra_t * deltaPix, \"E\", color=color, fontsize=15, ha='center')\n ax.arrow(xx_ * deltaPix, yy_ * deltaPix, (xx_dec - xx_) * deltaPix, (yy_dec - yy_) * deltaPix,\n head_width=arrow_size * d, head_length=arrow_size * d, fc\n =color, ec=color, linewidth=1)\n ax.text(xx_dec_t * deltaPix, yy_dec_t * deltaPix, \"N\", color=color, fontsize=15, ha='center')\n\n\ndef plot_line_set(ax, coords, ra_caustic_list, dec_caustic_list, color='g'):\n \"\"\"\n\n :param coords:\n :return:\n \"\"\"\n deltaPix = coords.pixel_size\n for i in range(len(ra_caustic_list)):\n x_c, y_c = coords.map_coord2pix(ra_caustic_list[i], dec_caustic_list[i])\n ax.plot((x_c + 0.5) * (deltaPix), (y_c + 0.5) * (deltaPix), color=color)\n return ax\n\n\ndef image_position_plot(ax, coords, ra_image, dec_image, color='w'):\n \"\"\"\n\n :param ax:\n :param coords:\n :param kwargs_else:\n :return:\n \"\"\"\n deltaPix = coords.pixel_size\n if len(ra_image) > 0:\n x_image, y_image = coords.map_coord2pix(ra_image, dec_image)\n abc_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G']\n for i in range(len(x_image)):\n x_ = (x_image[i] + 0.5) * deltaPix\n y_ = (y_image[i] + 0.5) * deltaPix\n ax.plot(x_, y_, 'or')\n ax.text(x_, y_, abc_list[i], fontsize=20, color=color)\n return ax\n\n\ndef source_position_plot(ax, coords, kwargs_source):\n \"\"\"\n\n :param ax:\n :param coords:\n :param kwargs_source:\n :return:\n \"\"\"\n deltaPix = coords.pixel_size\n x_source, y_source = coords.map_coord2pix(kwargs_source[0]['center_x'], kwargs_source[0]['center_y'])\n ax.plot((x_source + 0.5) * deltaPix, (y_source + 0.5) * deltaPix, '*', markersize=10)\n return ax\n\n\ndef lens_model_plot(ax, lensModel, kwargs_lens, numPix=500, deltaPix=0.01, sourcePos_x=0, sourcePos_y=0, point_source=False):\n \"\"\"\n plots a lens model (convergence) and the critical curves and caustics\n\n :param ax:\n :param kwargs_lens:\n :param numPix:\n :param deltaPix:\n :return:\n \"\"\"\n from lenstronomy.SimulationAPI.simulations import Simulation\n simAPI = Simulation()\n data = simAPI.data_configure(numPix, deltaPix)\n _frame_size = numPix * deltaPix\n _coords = data._coords\n x_grid, y_grid = data.coordinates\n lensModelExt = class_creator.creat_lens_model_extension(lensModel)\n ra_crit_list, dec_crit_list, ra_caustic_list, dec_caustic_list = lensModelExt.critical_curve_caustics(\n kwargs_lens, compute_window=_frame_size, grid_scale=0.005)\n kappa_result = util.array2image(lensModel.kappa(x_grid, y_grid, kwargs_lens))\n im = ax.matshow(np.log10(kappa_result), origin='lower',\n extent=[0, _frame_size, 0, _frame_size], cmap='Greys', vmin=-1, vmax=1) #, cmap=self._cmap, vmin=v_min, vmax=v_max)\n\n plot_line_set(ax, _coords, ra_caustic_list, dec_caustic_list, color='g')\n plot_line_set(ax, _coords, ra_crit_list, dec_crit_list, color='r')\n if point_source:\n from lenstronomy.LensModel.Solver.lens_equation_solver import LensEquationSolver\n solver = LensEquationSolver(lensModel)\n theta_x, theta_y = solver.image_position_from_source(sourcePos_x, sourcePos_y, kwargs_lens)\n mag_images = lensModel.magnification(theta_x, theta_y, kwargs_lens)\n x_image, y_image = _coords.map_coord2pix(theta_x, theta_y)\n abc_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K']\n for i in range(len(x_image)):\n x_ = (x_image[i] + 0.5) * deltaPix\n y_ = (y_image[i] + 0.5) * deltaPix\n ax.plot(x_, y_, 'dk', markersize=4*(1 + np.log(np.abs(mag_images[i]))), alpha=0.5)\n #ax.text(x_, y_, abc_list[i], fontsize=20, color='k')\n x_source, y_source = _coords.map_coord2pix(sourcePos_x, sourcePos_y)\n ax.plot((x_source + 0.5) * deltaPix, (y_source + 0.5) * deltaPix, '*k', markersize=10)\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n ax.autoscale(False)\n #image_position_plot(ax, _coords, self._kwargs_else)\n #source_position_plot(ax, self._coords, self._kwargs_source)\n return ax\n\n\nclass LensModelPlot(object):\n \"\"\"\n class that manages the summary plots of a lens model\n \"\"\"\n def __init__(self, kwargs_data, kwargs_psf, kwargs_numerics, kwargs_model, kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps, arrow_size=0.1, cmap_string=\"gist_heat\", high_res=5):\n \"\"\"\n\n :param kwargs_options:\n :param kwargs_data:\n :param arrow_size:\n :param cmap_string:\n \"\"\"\n self._kwargs_data = kwargs_data\n if isinstance(cmap_string, str) or isinstance(cmap_string, unicode):\n cmap = plt.get_cmap(cmap_string)\n else:\n cmap = cmap_string\n cmap.set_bad(color='k', alpha=1.)\n cmap.set_under('k')\n self._cmap = cmap\n self._arrow_size = arrow_size\n data = Data(kwargs_data)\n self._coords = data._coords\n nx, ny = np.shape(kwargs_data['image_data'])\n Mpix2coord = kwargs_data['transform_pix2angle']\n self._Mpix2coord = Mpix2coord\n\n self._deltaPix = self._coords.pixel_size\n self._frame_size = self._deltaPix * nx\n\n self._x_grid, self._y_grid = data.coordinates\n\n self._imageModel = class_creator.creat_image_model(kwargs_data, kwargs_psf, kwargs_numerics, kwargs_model)\n self._analysis = LensAnalysis(kwargs_model)\n self._lensModel = LensModelExtensions(lens_model_list=kwargs_model.get('lens_model_list', ['NONE']),\n z_source=kwargs_model.get('z_source', None),\n redshift_list=kwargs_model.get('redshift_list', None),\n multi_plane=kwargs_model.get('multi_plane', False))\n self._ra_crit_list, self._dec_crit_list, self._ra_caustic_list, self._dec_caustic_list = self._lensModel.critical_curve_caustics(kwargs_lens, compute_window=self._frame_size, grid_scale=0.01)\n\n model, error_map, cov_param, param = self._imageModel.image_linear_solve(kwargs_lens, kwargs_source,\n kwargs_lens_light, kwargs_ps, inv_bool=True)\n self._kwargs_lens = kwargs_lens\n self._kwargs_source = kwargs_source\n self._kwargs_lens_light = kwargs_lens_light\n self._kwargs_else = kwargs_ps\n self._model = model\n self._data = kwargs_data['image_data']\n self._cov_param = cov_param\n self._norm_residuals = self._imageModel.reduced_residuals(model, error_map=error_map)\n self._reduced_x2 = self._imageModel.reduced_chi2(model, error_map=error_map)\n log_model = np.log10(model)\n log_model[np.isnan(log_model)] = -5\n self._v_min_default = max(np.min(log_model), -5)\n self._v_max_default = min(np.max(log_model), 10)\n print(\"reduced chi^^ = \", self._reduced_x2)\n\n def data_plot(self, ax, v_min=None, v_max=None):\n \"\"\"\n\n :param ax:\n :return:\n \"\"\"\n if v_min is None:\n v_min = self._v_min_default\n if v_max is None:\n v_max = self._v_max_default\n im = ax.matshow(np.log10(self._data), origin='lower',\n extent=[0, self._frame_size, 0, self._frame_size], cmap=self._cmap, vmin=v_min, vmax=v_max) # , vmin=0, vmax=2\n\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n ax.autoscale(False)\n\n scale_bar(ax, self._frame_size, dist=1, text='1\"')\n text_description(ax, self._frame_size, text=\"Observed\", color=\"w\", backgroundcolor='k')\n coordinate_arrows(ax, self._frame_size, self._coords, arrow_size=self._arrow_size)\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n cb = plt.colorbar(im, cax=cax)\n cb.set_label(r'log$_{10}$ flux', fontsize=15)\n return ax\n\n def model_plot(self, ax, v_min=None, v_max=None):\n \"\"\"\n\n :param ax:\n :param model:\n :param v_min:\n :param v_max:\n :return:\n \"\"\"\n if v_min is None:\n v_min = self._v_min_default\n if v_max is None:\n v_max = self._v_max_default\n im = ax.matshow(np.log10(self._model), origin='lower', vmin=v_min, vmax=v_max,\n extent=[0, self._frame_size, 0, self._frame_size], cmap=self._cmap)\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n ax.autoscale(False)\n scale_bar(ax, self._frame_size, dist=1, text='1\"')\n text_description(ax, self._frame_size, text=\"Reconstructed\", color=\"w\", backgroundcolor='k')\n coordinate_arrows(ax, self._frame_size, self._coords, arrow_size=self._arrow_size)\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n cb = plt.colorbar(im, cax=cax)\n cb.set_label(r'log$_{10}$ flux', fontsize=15)\n\n plot_line_set(ax, self._coords, self._ra_caustic_list, self._dec_caustic_list, color='b')\n plot_line_set(ax, self._coords, self._ra_crit_list, self._dec_crit_list, color='r')\n ra_image, dec_image = self._imageModel.image_positions(self._kwargs_else, self._kwargs_lens)\n image_position_plot(ax, self._coords, ra_image[0], dec_image[0])\n source_position_plot(ax, self._coords, self._kwargs_source)\n\n def convergence_plot(self, ax, v_min=None, v_max=None):\n \"\"\"\n\n :param x_grid:\n :param y_grid:\n :param kwargs_lens:\n :param kwargs_else:\n :return:\n \"\"\"\n kappa_result = util.array2image(self._lensModel.kappa(self._x_grid, self._y_grid, self._kwargs_lens))\n im = ax.matshow(np.log10(kappa_result), origin='lower',\n extent=[0, self._frame_size, 0, self._frame_size], cmap=self._cmap, vmin=v_min, vmax=v_max)\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n ax.autoscale(False)\n scale_bar(ax, self._frame_size, dist=1, text='1\"', color='w')\n coordinate_arrows(ax, self._frame_size, self._coords, color='w', arrow_size=self._arrow_size)\n text_description(ax, self._frame_size, text=\"Convergence\", color=\"w\", backgroundcolor='k', flipped=False)\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n cb = plt.colorbar(im, cax=cax)\n cb.set_label(r'log$_{10}$ $\\kappa$', fontsize=15)\n return ax\n\n def normalized_residual_plot(self, ax, v_min=-6, v_max=6):\n \"\"\"\n\n :param ax:\n :param residuals:\n :return:\n \"\"\"\n im = ax.matshow(self._norm_residuals, vmin=v_min, vmax=v_max,\n extent=[0, self._frame_size, 0, self._frame_size], cmap='bwr', origin='lower')\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n ax.autoscale(False)\n scale_bar(ax, self._frame_size, dist=1, text='1\"', color='k')\n text_description(ax, self._frame_size, text=\"Normalized Residuals\", color=\"k\", backgroundcolor='w')\n coordinate_arrows(ax, self._frame_size, self._coords, color='k', arrow_size=self._arrow_size)\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n cb = plt.colorbar(im, cax=cax)\n cb.set_label(r'(f$_{model}$-f$_{data}$)/$\\sigma$', fontsize=15)\n return ax\n\n def absolute_residual_plot(self, ax, v_min=-1, v_max=1):\n \"\"\"\n\n :param ax:\n :param residuals:\n :return:\n \"\"\"\n im = ax.matshow(self._model - self._data, vmin=v_min, vmax=v_max,\n extent=[0, self._frame_size, 0, self._frame_size], cmap='bwr', origin='lower')\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n ax.autoscale(False)\n scale_bar(ax, self._frame_size, dist=1, text='1\"', color='k')\n text_description(ax, self._frame_size, text=\"Residuals\", color=\"k\", backgroundcolor='w')\n coordinate_arrows(ax, self._frame_size, self._coords, color='k', arrow_size=self._arrow_size)\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n cb = plt.colorbar(im, cax=cax)\n cb.set_label(r'(f$_{model}$-f$_{data}$)', fontsize=15)\n return ax\n\n def source_plot(self, ax, numPix, deltaPix_source, source_sigma=0.001, convolution=False, v_min=None, v_max=None):\n \"\"\"\n\n :param ax:\n :param coords_source:\n :param source:\n :return:\n \"\"\"\n if v_min is None:\n v_min = self._v_min_default\n if v_max is None:\n v_max = self._v_max_default\n d_s = numPix * deltaPix_source\n x_grid_source, y_grid_source = util.make_grid_transformed(numPix,\n self._Mpix2coord * deltaPix_source / self._deltaPix)\n x_center = self._kwargs_source[0]['center_x']\n y_center = self._kwargs_source[0]['center_y']\n x_grid_source += x_center\n y_grid_source += y_center\n coords_source = Coordinates(self._Mpix2coord * deltaPix_source / self._deltaPix, ra_at_xy_0=x_grid_source[0],\n dec_at_xy_0=y_grid_source[0])\n\n source = self._imageModel.SourceModel.surface_brightness(x_grid_source, y_grid_source, self._kwargs_source)\n source = util.array2image(source)\n if convolution:\n source = ndimage.filters.gaussian_filter(source, sigma=source_sigma / deltaPix_source, mode='nearest',\n truncate=20)\n\n im = ax.matshow(np.log10(source), origin='lower', extent=[0, d_s, 0, d_s],\n cmap=self._cmap, vmin=v_min, vmax=v_max) # source\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n ax.autoscale(False)\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n cb = plt.colorbar(im, cax=cax)\n cb.set_label(r'log$_{10}$ flux', fontsize=15)\n plot_line_set(ax, coords_source, self._ra_caustic_list, self._dec_caustic_list, color='b')\n scale_bar(ax, d_s, dist=0.1, text='0.1\"', color='w', flipped=False)\n coordinate_arrows(ax, d_s, coords_source, arrow_size=self._arrow_size, color='w')\n text_description(ax, d_s, text=\"Reconstructed source\", color=\"w\", backgroundcolor='k', flipped=False)\n source_position_plot(ax, coords_source, self._kwargs_source)\n return ax\n\n def error_map_source_plot(self, ax, numPix, deltaPix_source, v_min=None, v_max=None):\n x_grid_source, y_grid_source = util.make_grid_transformed(numPix,\n self._Mpix2coord * deltaPix_source / self._deltaPix)\n x_center = self._kwargs_source[0]['center_x']\n y_center = self._kwargs_source[0]['center_y']\n x_grid_source += x_center\n y_grid_source += y_center\n coords_source = Coordinates(self._Mpix2coord * deltaPix_source / self._deltaPix, ra_at_xy_0=x_grid_source[0],\n dec_at_xy_0=y_grid_source[0])\n error_map_source = self._analysis.error_map_source(self._kwargs_source, x_grid_source, y_grid_source, self._cov_param)\n error_map_source = util.array2image(error_map_source)\n d_s = numPix * deltaPix_source\n im = ax.matshow(error_map_source, origin='lower', extent=[0, d_s, 0, d_s],\n cmap=self._cmap, vmin=v_min, vmax=v_max) # source\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n ax.autoscale(False)\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n cb = plt.colorbar(im, cax=cax)\n cb.set_label(r'error variance', fontsize=15)\n plot_line_set(ax, coords_source, self._ra_caustic_list, self._dec_caustic_list, color='b')\n scale_bar(ax, d_s, dist=0.1, text='0.1\"', color='w', flipped=False)\n coordinate_arrows(ax, d_s, coords_source, arrow_size=self._arrow_size, color='w')\n text_description(ax, d_s, text=\"Error map in source\", color=\"w\", backgroundcolor='k', flipped=False)\n source_position_plot(ax, coords_source, self._kwargs_source)\n return ax\n\n def magnification_plot(self, ax, v_min=-10, v_max=10):\n \"\"\"\n\n :param ax:\n :return:\n \"\"\"\n mag_result = util.array2image(self._lensModel.magnification(self._x_grid, self._y_grid, self._kwargs_lens))\n im = ax.matshow(mag_result, origin='lower', extent=[0, self._frame_size, 0, self._frame_size],\n vmin=v_min, vmax=v_max, cmap=self._cmap, alpha=0.5)\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n ax.autoscale(False)\n scale_bar(ax, self._frame_size, dist=1, text='1\"', color='k')\n coordinate_arrows(ax, self._frame_size, self._coords, color='k', arrow_size=self._arrow_size)\n text_description(ax, self._frame_size, text=\"Magnification model\", color=\"k\", backgroundcolor='w')\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n cb = plt.colorbar(im, cax=cax)\n cb.set_label(r'det(A$^{-1}$)', fontsize=15)\n\n plot_line_set(ax, self._coords, self._ra_caustic_list, self._dec_caustic_list, color='b')\n plot_line_set(ax, self._coords, self._ra_crit_list, self._dec_crit_list, color='r')\n ra_image, dec_image = self._imageModel.image_positions(self._kwargs_else, self._kwargs_lens)\n image_position_plot(ax, self._coords, ra_image[0], dec_image[0], color='k')\n source_position_plot(ax, self._coords, self._kwargs_source)\n return ax\n\n def deflection_plot(self, ax, v_min=None, v_max=None, axis=0):\n \"\"\"\n\n :param kwargs_lens:\n :param kwargs_else:\n :return:\n \"\"\"\n\n alpha1, alpha2 = self._lensModel.alpha(self._x_grid, self._y_grid, self._kwargs_lens)\n alpha1 = util.array2image(alpha1)\n alpha2 = util.array2image(alpha2)\n if axis == 0:\n alpha = alpha1\n else:\n alpha = alpha2\n im = ax.matshow(alpha, origin='lower', extent=[0, self._frame_size, 0, self._frame_size],\n vmin=v_min, vmax=v_max, cmap=self._cmap, alpha=0.5)\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n ax.autoscale(False)\n scale_bar(ax, self._frame_size, dist=1, text='1\"', color='k')\n coordinate_arrows(ax, self._frame_size, self._coords, color='k', arrow_size=self._arrow_size)\n text_description(ax, self._frame_size, text=\"Deflection model\", color=\"k\", backgroundcolor='w')\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n cb = plt.colorbar(im, cax=cax)\n cb.set_label(r'arcsec', fontsize=15)\n\n plot_line_set(ax, self._coords, self._ra_caustic_list, self._dec_caustic_list, color='b')\n plot_line_set(ax, self._coords, self._ra_crit_list, self._dec_crit_list, color='r')\n ra_image, dec_image = self._imageModel.image_positions(self._kwargs_else, self._kwargs_lens)\n image_position_plot(ax, self._coords, ra_image[0], dec_image[0])\n source_position_plot(ax, self._coords, self._kwargs_source)\n return ax\n\n def decomposition_plot(self, ax, text='Reconstructed', v_min=None, v_max=None, unconvolved=False, point_source_add=False, source_add=False, lens_light_add=False):\n\n model = self._imageModel.image(self._kwargs_lens, self._kwargs_source, self._kwargs_lens_light,\n self._kwargs_else, unconvolved=unconvolved, source_add=source_add,\n lens_light_add=lens_light_add, point_source_add=point_source_add)\n if v_min is None:\n v_min = self._v_min_default\n if v_max is None:\n v_max = self._v_max_default\n im = ax.matshow(np.log10(model), origin='lower', vmin=v_min, vmax=v_max,\n extent=[0, self._frame_size, 0, self._frame_size], cmap=self._cmap)\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n ax.autoscale(False)\n scale_bar(ax, self._frame_size, dist=1, text='1\"')\n text_description(ax, self._frame_size, text=text, color=\"w\", backgroundcolor='k')\n coordinate_arrows(ax, self._frame_size, self._coords, arrow_size=self._arrow_size)\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n cb = plt.colorbar(im, cax=cax)\n cb.set_label(r'log$_{10}$ flux', fontsize=15)\n return ax\n\n def subtract_from_data_plot(self, ax, text='Subtracted', v_min=None, v_max=None, point_source_add=False, source_add=False, lens_light_add=False):\n model = self._imageModel.image(self._kwargs_lens, self._kwargs_source, self._kwargs_lens_light,\n self._kwargs_else, unconvolved=False, source_add=source_add,\n lens_light_add=lens_light_add, point_source_add=point_source_add)\n if v_min is None:\n v_min = self._v_min_default\n if v_max is None:\n v_max = self._v_max_default\n im = ax.matshow(np.log10(self._data - model), origin='lower', vmin=v_min, vmax=v_max,\n extent=[0, self._frame_size, 0, self._frame_size], cmap=self._cmap)\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n ax.autoscale(False)\n scale_bar(ax, self._frame_size, dist=1, text='1\"')\n text_description(ax, self._frame_size, text=text, color=\"w\", backgroundcolor='k')\n coordinate_arrows(ax, self._frame_size, self._coords, arrow_size=self._arrow_size)\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n cb = plt.colorbar(im, cax=cax)\n cb.set_label(r'log$_{10}$ flux', fontsize=15)\n return ax\n\n\ndef plot_chain(chain, param_list):\n X2_list, pos_list, vel_list, _ = chain\n\n f, axes = plt.subplots(1, 3, figsize=(18, 6), sharex=False, sharey=False)\n ax = axes[0]\n ax.plot(np.log10(-np.array(X2_list)))\n ax.set_title('-logL')\n\n ax = axes[1]\n pos = np.array(pos_list)\n vel = np.array(vel_list)\n n_iter = len(pos)\n plt.figure()\n for i in range(0,len(pos[0])):\n ax.plot((pos[:,i]-pos[n_iter-1,i]),label=param_list[i])\n ax.set_title('particle position')\n ax.legend()\n\n ax = axes[2]\n for i in range(0,len(vel[0])):\n ax.plot(vel[:,i], label=param_list[i])\n ax.set_title('param velocity')\n ax.legend()\n return f, axes\n\n\ndef ext_shear_direction(data_class, lens_model_class, kwargs_lens, strength_multiply=10):\n \"\"\"\n\n :param kwargs_data:\n :param kwargs_psf:\n :param kwargs_options:\n :param lens_result:\n :param source_result:\n :param lens_light_result:\n :param else_result:\n :return:\n \"\"\"\n x_grid, y_grid = data_class.coordinates\n shear = ExternalShear()\n\n f_x_shear, f_y_shear = 0, 0\n for i, lens_model in enumerate(lens_model_class.lens_model_list):\n if lens_model == 'SHEAR':\n kwargs = kwargs_lens[i]\n f_x_shear, f_y_shear = shear.derivatives(x_grid, y_grid, e1=kwargs['e1'] * strength_multiply,\n e2=kwargs['e2'] * strength_multiply)\n x_shear = x_grid - f_x_shear\n y_shear = y_grid - f_y_shear\n\n f_x_foreground, f_y_foreground = 0, 0\n for i, lens_model in enumerate(lens_model_class.lens_model_list):\n if lens_model == 'FOREGROUND_SHEAR':\n kwargs = kwargs_lens[i]\n f_x_foreground, f_y_foreground = shear.derivatives(x_grid, y_grid, e1=kwargs['e1'] * strength_multiply,\n e2=kwargs['e2'] * strength_multiply)\n x_foreground = x_grid - f_x_foreground\n y_foreground = y_grid - f_y_foreground\n\n center_x = np.mean(x_grid)\n center_y = np.mean(y_grid)\n radius = (np.max(x_grid) - np.min(x_grid))/4\n circle_shear = util_maskl.mask_sphere(x_shear, y_shear, center_x, center_y, radius)\n circle_foreground = util_maskl.mask_sphere(x_foreground, y_foreground, center_x, center_y, radius)\n f, ax = plt.subplots(1, 1, figsize=(16, 8), sharex=False, sharey=False)\n im = ax.matshow(np.log10(data_class.data), origin='lower', alpha=0.5)\n im = ax.matshow(util.array2image(circle_shear), origin='lower', alpha=0.5, cmap=\"jet\")\n im = ax.matshow(util.array2image(circle_foreground), origin='lower', alpha=0.5)\n #f.show()\n return f, ax\n\n\ndef psf_iteration_compare(kwargs_psf):\n \"\"\"\n\n :param kwargs_psf:\n :return:\n \"\"\"\n psf_out = kwargs_psf['kernel_point_source']\n psf_in = kwargs_psf['kernel_point_source_init']\n n_kernel = len(psf_in)\n delta_x = n_kernel/20.\n delta_y = n_kernel/10.\n cmap_kernel = 'seismic'\n\n f, axes = plt.subplots(1, 3, figsize=(15, 5), sharex=False, sharey=False)\n ax = axes[0]\n im = ax.matshow(np.log10(psf_in), origin='lower', cmap=cmap_kernel)\n v_min, v_max = im.get_clim()\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n plt.colorbar(im, cax=cax)\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n ax.text(delta_x, n_kernel-delta_y, \"stacked stars\", color=\"k\", fontsize=20, backgroundcolor='w')\n\n ax = axes[1]\n im = ax.matshow(np.log10(psf_out), origin='lower', vmin=v_min, vmax=v_max, cmap=cmap_kernel)\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n plt.colorbar(im, cax=cax)\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n ax.text(delta_x, n_kernel-delta_y, \"iterative reconstruction\", color=\"k\", fontsize=20, backgroundcolor='w')\n\n ax = axes[2]\n im = ax.matshow(psf_out-psf_in, origin='lower', vmin=-10**-3, vmax=10**-3, cmap=cmap_kernel)\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n plt.colorbar(im, cax=cax)\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n ax.text(delta_x, n_kernel-delta_y, \"difference\", color=\"k\", fontsize=20, backgroundcolor='w')\n f.tight_layout()\n return f, axes","sub_path":"lenstronomy/Plots/output_plots.py","file_name":"output_plots.py","file_ext":"py","file_size_in_byte":28820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"578949660","text":"# Exercise3 List Less than 10\n\n'''Take a list, say for example this one:\n\n a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]\nand write a program that prints out all the elements of the list that are less than 5.\n\nExtras:\n\nInstead of printing the elements one by one, make a new list that has all the elements less than 5 from this list in it and print out this new list.\nWrite this in one line of Python.\nAsk the user for a number and return a list that contains only elements from the original list a \nthat are smaller than that number given by the user.\n'''\n\nl = list(input(\"Please input a list here : \"))\nnum = input(\"Please input the max number : \")\nprint([ele for ele in l if ele < num])","sub_path":"level 1/exercise3_list_<_10.py","file_name":"exercise3_list_<_10.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"440291445","text":"# расчет полей пространственного заряда в любой точке\n\nclass pic:\n\n def __init__(self, h, x, y, z, E0, B0):\n self.h = h\n self.x = x\n self.y = y\n self.z = z\n self.E0 = E0\n self.B0 = B0\n\n# функция которая определяет диапазон координат, из сеточных узлов которого брать напряженности\n def rangeGrid(self, r, p):\n index = []\n for i in r:\n if abs(p - i) < self.h:\n index.append(int(i/self.h))\n return [min(index), max(index)]\n\n # функция для расчета сеточного ядра\n def R(self, r, p):\n if abs(r - p) < self.h:\n return (1 - abs(r - p)/self.h)/self.h\n else: return 0\n\n # функция для расчета полей пространственного заряда непосредственно для конкретной частицы\n def fieldEBRandomPoint(self, mas, particle):\n maxminX = self.rangeGrid(self.x, particle[0])\n maxminY = self.rangeGrid(self.y, particle[1])\n maxminZ = self.rangeGrid(self.z, particle[2])\n particle[6] = 0\n particle[7] = self.E0\n particle[8] = 0\n particle[9] = self.B0\n particle[10] = 0\n particle[11] = 0\n for i in range(maxminX[0], maxminX[1]+1):\n for j in range(maxminY[0], maxminY[1]+1):\n for k in range(maxminZ[0], maxminZ[1]+1):\n ii = i * 2\n jj = j * 2\n kk = k * 2\n # ПЗ электрического поля\n particle[6] += (mas[i+0.5][j][k])[0] * self.R(self.x[ii+1], particle[0]) * self.R(self.y[jj], particle[1]) * self.R(self.z[kk], particle[2])\n particle[7] += (mas[i][j+0.5][k])[0] * self.R(self.x[ii], particle[0]) * self.R(self.y[jj+1], particle[1]) * self.R(self.z[kk], particle[2])\n particle[8] += (mas[i][j][k+0.5])[0] * self.R(self.x[ii], particle[0]) * self.R(self.y[jj], particle[1]) * self.R(self.z[kk+1], particle[2])\n # ПЗ магнитного поля\n particle[9] += (mas[i][j+0.5][k+0.5])[1] * self.R(self.x[ii], particle[0]) * self.R(self.y[jj+1], particle[1]) * self.R(self.z[kk+1], particle[2])\n particle[10] += (mas[i+0.5][j][k+0.5])[1] * self.R(self.x[ii+1], particle[0]) * self.R(self.y[jj], particle[1]) * self.R(self.z[kk+1], particle[2])\n particle[11] += (mas[i+0.5][j+0.5][k])[1] * self.R(self.x[ii+1], particle[0]) * self.R(self.y[jj+1], particle[1]) * self.R(self.z[kk], particle[2])\n return particle[6], particle[7], particle[8], particle[9], particle[10], particle[11]\n","sub_path":"program/pic.py","file_name":"pic.py","file_ext":"py","file_size_in_byte":2846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"524386274","text":"import random\nfrom setting import setting\n\nclass tower(setting):\n\n\tdef __init__(self):\n\t\tsetting.__init__('A tower', 'TowerDescription', 'TowerTransition')\n\n\n\tdef get_description(self):\n\t\tname = open(\"./transition.txt\") \n\t\tcase = open(\"description.txt\")\n\t\tfor number in range(0, random.randint(1,3)):\n\t\t\ttransition = name.readline()\n\t\t\tsetting = case.readline()\n\t\treturn(transition + setting)","sub_path":"settings/tower/tower.py","file_name":"tower.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"482156687","text":"\n\nimport pytest\n\nfrom problems.p18_get_binary_tree_next_node import get_next, Node\n\n\n# Tree nodes\nA, B, C = Node('a'), Node('b'), Node('c')\nD, E, F = Node('d'), Node('e'), Node('f')\nG, H, I = Node('g'), Node('h'), Node('i')\n\nA.left, A.right = B, C\nB.left, B.right, B.parent = D, E, A\nC.left, C.right, C.parent = F, G, A\nD.parent = B\nE.left, E.right, E.parent = H, I, B\nF.parent = C\nG.parent = C\nH.parent = E\nI.parent = E\n\n# In-order 中序遍历获得的序列\nin_order = [D, B, H, E, I, A, F, C, G]\n\n# 输入节点对应的下个节点\ntest_params = [\n (A, F),\n (D, B),\n (C, G),\n (E, I)\n]\n\n\n@pytest.mark.parametrize('node, expected', test_params)\ndef test_get_next_node(node, expected):\n assert get_next(node) == expected\n","sub_path":"src/problems/tests/test_get_next_node_of_binary_tree.py","file_name":"test_get_next_node_of_binary_tree.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"551520841","text":"import pytest\nfrom traitlets import Float, TraitError\n\nfrom ctapipe.core import Component\nfrom abc import abstractmethod\n\n\ndef test_component_is_abstract():\n\n class AbstractComponent(Component):\n @abstractmethod\n def test(self):\n pass\n\n with pytest.raises(TypeError):\n AbstractComponent()\n\n\ndef test_component_simple():\n \"\"\"\n very basic test to construct a component and check\n that it's traits work correctly\n \"\"\"\n\n class ExampleComponent(Component):\n description = \"this is a test\"\n param = Float(default_value=1.0,\n help=\"float parameter\").tag(config=True)\n\n comp = ExampleComponent()\n\n assert comp.has_trait('param') is True\n comp.param = 1.2\n\n with pytest.raises(TraitError):\n comp.param = \"badvalue\"\n\n\ndef test_component_kwarg_setting():\n class ExampleComponent(Component):\n description = \"this is a test\"\n param = Float(default_value=1.0,\n help=\"float parameter\").tag(config=True)\n\n comp = ExampleComponent(param=3)\n assert comp.param == 3\n\n # Invalid type\n with pytest.raises(TraitError):\n comp = ExampleComponent(param=\"badvalue\")\n\n # Invalid traitlet\n with pytest.raises(TraitError):\n comp = ExampleComponent(incorrect=\"wrong\")\n","sub_path":"ctapipe/core/tests/test_component.py","file_name":"test_component.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"411569591","text":"\"\"\" Compiled: 2020-09-18 10:38:55 \"\"\"\n\n#__src_file__ = \"extensions/SecuritiesLending/etc/FSecLendOrdersMenuItems.py\"\nfrom __future__ import print_function\n\"\"\"--------------------------------------------------------------------------\nMODULE\n FSecLendOrdersMenuItems\n\n (c) Copyright 2017 FIS FRONT ARENA. All rights reserved.\n\nDESCRIPTION\n Order Manager - Menu items.\n\n---------------------------------------------------------------------------\"\"\"\nimport acm\n\nimport FSecLendHooks\nimport FSecLendUtils\nimport FSecLendHoldTrade\nfrom ACMPyUtils import Transaction\nfrom FClipboardUtilities import SetClipboardText # @UnresolvedImport pylint: disable=import-error\nfrom FSecLendHooks import ClipBoardTextHookFromTrades\nfrom FSecLendMenuItem import SecLendMenuItemBase\nfrom FSecLendOrderCapturePanelBase import StreamBufferDialog\nfrom FSecLendWorkflow import SecLendWorkflow\nfrom GenerateOrderReportAPI import GetReportParameters\nfrom SecLendingReportingATS import SEC_LEND_REPORT_TO_DESTINATIONS\nfrom FWorkflowMenuItem import MultiWorkflowMenuItem\nfrom FParameterSettings import ParameterSettingsCreator\nfrom datetime import datetime, timedelta\n\n_SETTINGS = ParameterSettingsCreator.FromRootParameter('SecLendSettings')\n\nclass SecLendingWorkflowMenuItem(MultiWorkflowMenuItem, SecLendMenuItemBase):\n EVENT = None\n BP_CACHE = {}\n\n def __init__(self, extObj):\n super(SecLendingWorkflowMenuItem, self).__init__(extObj, SecLendWorkflow, self.EVENT)\n\n\n def _BusinessProcess(self, trade):\n try:\n if not trade in self.BP_CACHE:\n bp = acm.BusinessProcess.FindBySubjectAndStateChart(trade, self._workflow.StateChart())[0]\n self.BP_CACHE[trade] = bp\n return self.BP_CACHE[trade]\n except IndexError:\n return None\n\n def _SelectedTrades(self, maxNbrOfTrades=1000):\n return [trade for trade in self._frame.ActiveSheet().Selection().SelectedTrades()[0:maxNbrOfTrades] \n if not trade.IsDeleted()]\n\n def BusinessProcesses(self):\n trades = self._SelectedTrades(100) # Cut off because of performance\n if not trades:\n return None\n return filter(lambda x: bool(x), [self._BusinessProcess(trade) for trade in trades])\n\n def Applicable(self):\n return True\n\n def _HandleEvent(self, businessProcess, parameters=None, notes=None):\n MIFIDParams = FSecLendUtils.ColumnValuesFromExtensionattribute(businessProcess.Subject(),\n \"_SecurityLoan_Reporting_Columns\")\n if parameters:\n parameters.update(MIFIDParams)\n self.Workflow()(businessProcess)._HandleEvent(self.Event(), parameters, notes)\n\n def _IsValidUserForAction(self):\n validUser = []\n trades = self._SelectedTrades()\n if trades:\n return FSecLendHooks.IsValidUserForRibbon(trades)\n else:\n return False\n \n def _IsValidEvent(self):\n if self.EVENT:\n return MultiWorkflowMenuItem.Enabled(self)\n else:\n return True\n \n def Enabled(self):\n return bool(self._SelectedTrades()) and self._IsValidUserForAction() and SecLendMenuItemBase.Enabled(self) and self._IsValidEvent()\n \n\nclass ReCheckMenuItem(SecLendingWorkflowMenuItem):\n EVENT = 'Re-check'\n\n def Invoke(self, eii):\n \"\"\" Force error state if state is different from \n or handle event to the previous state. Apply all changes if there are any..\"\"\"\n notes, parameters = self._NotesAndParameters()\n for bp in self.BusinessProcesses():\n if bp.CurrentStep().IsInErrorState():\n bp.HandleEvent(\"Revert\")\n bp.Commit()\n elif self._SatisfiesCondition(bp, parameters):\n self._HandleEvent(bp, parameters, notes)\n\n\nclass ManualApproveMenuItem(SecLendingWorkflowMenuItem):\n EVENT = 'Manual approve'\n\n\nclass SecLendingWorkflowReplyingMenuItem(SecLendingWorkflowMenuItem):\n\n def Invoke(self, eii):\n if not self.VerifyValidCollection(eii):\n return\n notes, parameters = self._NotesAndParameters()\n if not self.VerifyOrderReportMapping(eii, parameters):\n return\n if not self.SetClipboardTextAndShowBuffer(eii):\n return\n self.SetRespondTrades(parameters)\n for bp in self.BusinessProcesses():\n trade = bp.Subject()\n self.SetRespondSource(eii, parameters, trade)\n if self._SatisfiesCondition(bp, parameters):\n self._HandleEvent(bp, parameters, notes)\n \n def SelectedTradesString(self):\n return ','.join([str(trade.Oid()) for trade in self._SelectedTrades(100)])\n \n def VerifyOrderReportMapping(self, eii, parameters = {}):\n destination = self.GetDestination(eii)\n if destination:\n if destination in SEC_LEND_REPORT_TO_DESTINATIONS:\n sheet = eii.Parameter('sheet') or eii.ExtensionObject().ActiveSheet()\n trade = sheet.Selection().SelectedCell().RowObject().Trade()\n try:\n GetReportParameters(destination, trade.Counterparty())\n except Exception as e:\n dialogMsg = \"%s. Do you want to %s it anyway without a confirmation?\" % (e, self.EVENT)\n if acm.UX().Dialogs().MessageBoxYesNo(self._frame.Shell(), \"Warning\", dialogMsg) == 'Button1':\n parameters.update({\"Response\":\"NO [%s]\" % e})\n return True\n return False\n elif destination not in ('Clipboard', \"Manual\"):\n dialogMsg = \"No confirmation can be sent to %s. Do you want to %s it anyway without a confirmation?\" % (destination, self.EVENT)\n return acm.UX().Dialogs().MessageBoxYesNo(self._frame.Shell(), \"Warning\", dialogMsg ) == 'Button1'\n \n return True\n \n def VerifyValidCollection(self, eii):\n destination = eii.MenuExtension().GetString('Destination')\n if destination == '*SOURCE*':\n sources = set(trade.Market() and trade.Market().Name() for trade in self._SelectedTrades())\n if len(sources) == 1:\n destination = sources.pop()\n elif set(SEC_LEND_REPORT_TO_DESTINATIONS) & sources:\n msg = 'Trades from multiple sources %s cannot be sent in the same message' % list(sources)\n acm.UX().Dialogs().MessageBox(self._frame.Shell(), \"Error\", msg, 'Ok', None, None, 'Button1', 'Button3' )\n return False\n else:\n #Multiple sources but no source is a reporting source\n destination = None\n \n if destination and destination in SEC_LEND_REPORT_TO_DESTINATIONS:\n source = '_NO_VALUE_'\n counterparty = '_NO_VALUE_'\n error = ''\n for trade in self._SelectedTrades():\n s = trade.AddInfoValue('SBL_TradeOriginId')\n if source != '_NO_VALUE_' and s != source:\n error = 'source objects'\n cp = trade.Counterparty()\n if counterparty != '_NO_VALUE_' and cp != counterparty:\n error = 'counterparties'\n if error:\n msg = 'Trades from multiple %s cannot be sent in the same message' % error\n acm.UX().Dialogs().MessageBox(self._frame.Shell(), \"Error\", msg, 'Ok', None, None, 'Button1', 'Button3' )\n return False\n source = s\n counterparty = cp\n nbrOfTrades = len(self._SelectedTrades())\n\n if source:\n sourceTrades = acm.FAdditionalInfo.Select(\"addInf = 'SBL_TradeOriginId' and fieldValue = '%s'\" % source)\n if sourceTrades.Size() > nbrOfTrades:\n msg = 'Only %d of %d orders from the import where selected, do you want to send the reply anyway?' % \\\n (nbrOfTrades, sourceTrades.Size())\n if acm.UX().Dialogs().MessageBoxYesNo(self._frame.Shell(), \"Warning\", msg) == 'Button1':\n return True\n return False\n if sourceTrades.Size() < nbrOfTrades:\n print(\"ERROR - shouldn't end up here, there has to be multiple sources, %d, %d\" %\\\n (sourceTrades.Size(), nbrOfTrades))\n return False\n return True\n \n def GetDestination(self, eii, defaultValue = ''):\n destination = eii.MenuExtension().GetString('Destination', defaultValue)\n if destination == '*SOURCE*':\n sheet = eii.Parameter('sheet') or eii.ExtensionObject().ActiveSheet()\n trade = sheet.Selection().SelectedCell().RowObject().Trade()\n destination = trade.Market() and trade.Market().Name()\n return destination\n\n def SetClipboardTextAndShowBuffer(self, eii):\n destination = self.GetDestination(eii, eii.MenuExtension().Name().AsString())\n try:\n text = ClipBoardTextHookFromTrades(self._SelectedTrades(), self.Event())\n SetClipboardText(text)\n if destination == \"Manual\" and _SETTINGS.ShowRespondBuffer():\n buffer_dialog = StreamBufferDialog(text, 'Text To Clipboard', False)\n return acm.UX().Dialogs().ShowCustomDialogModal(self._frame.Shell(),\n buffer_dialog.CreateLayout(), buffer_dialog)\n except Exception as e:\n print('Failed to set content to clipboard', e)\n return True\n \n def SetRespondTrades(self, parameters):\n parameters.update({\"TargetTrades\":self.SelectedTradesString()})\n \n def SetRespondSource(self, eii, parameters, trade):\n buttonName = eii.MenuExtension().Name().AsString()\n if buttonName == self.EVENT:\n parameters.update({\"TargetSource\":trade.Market() and trade.Market().Name()})\n else:\n assert acm.FMarketPlace[buttonName] is not None, \\\n \"No FMarketPlace named '{}' to route orders to.\" \\\n .format(buttonName)\n parameters.update({\"TargetSource\":buttonName})\n \n def Enabled(self):\n return SecLendingWorkflowMenuItem.Enabled(self) and \\\n FSecLendHooks.IsCompliantToSourceMapping(self._SelectedTrades())\n\n\nclass RespondMenuItem(SecLendingWorkflowReplyingMenuItem):\n EVENT = 'Respond'\n \n def SelectedTradesAreNotReturns(self):\n for t in self._SelectedTrades():\n if t.Type() == 'Closing':\n return False\n return True\n\n def Enabled(self):\n return self.SelectedTradesAreNotReturns() and super(RespondMenuItem, self).Enabled()\n\nclass RejectMenuItem(SecLendingWorkflowReplyingMenuItem):\n EVENT = 'Reject'\n \n def SetRespondSource(self, eii, parameters, trade):\n destination = self.GetDestination(eii)\n if destination:\n assert acm.FMarketPlace[destination] is not None, \\\n \"No FMarketPlace named '{}' to route orders to. The destination is specified in the menu extension '{}'\" \\\n .format(destination, eii.MenuExtension().Name())\n parameters.update({\"TargetSource\":destination})\n else:\n parameters.update({\"TargetSource\":trade.Market().Name(),\n \"Response\":\"NO\"})\n\n\nclass BookMenuItem(SecLendingWorkflowReplyingMenuItem):\n EVENT = 'Book'\n\n def Invoke(self, eii):\n if not all(FSecLendHooks.IsValidForProcessing(trade) for trade in self._SelectedTrades()):\n acm.GetFunction('msgBox', 3)('Security Lending', \"One or more trades is not suitable for booking\", 0)\n return\n isOverClosing, instrument = FSecLendHooks.IsOverClosingPosition([trade for trade in self._SelectedTrades() \\\n if trade.Type() == 'Closing'])\n if isOverClosing:\n acm.GetFunction('msgBox', 3)('Closing Position', \"To high quantity to return for order(s) in \" \\\n \"instrument %s. Adjust the quantity of the order(s).\" %(instrument), 0)\n return \n super(BookMenuItem, self).Invoke(eii)\n\n def SetRespondSource(self, eii, parameters, trade):\n destination = self.GetDestination(eii)\n if destination:\n assert acm.FMarketPlace[destination] is not None, \\\n \"No FMarketPlace named '{}' to route orders to. The destination is specified in the menu extension '{}'\" \\\n .format(destination, eii.MenuExtension().Name())\n parameters.update({\"TargetSource\":destination})\n else:\n parameters.update({\"TargetSource\":trade.Market().Name(),\n \"Response\":\"NO\"})\n\n\nclass InspectWorkflowMenuItem(SecLendingWorkflowMenuItem):\n\n def Invoke(self, eii):\n businessProcesses = self.BusinessProcesses()\n if len(businessProcesses) > 1:\n acm.StartApplication(\"Operations Manager\", businessProcesses)\n elif len(businessProcesses) == 1:\n acm.StartApplication(\"Business Process Details\", businessProcesses[0])\n\n def Enabled(self):\n return bool(self.BusinessProcesses())\n\n\nclass DeleteTradeMenuItem(SecLendingWorkflowMenuItem):\n\n def Invoke(self, eii):\n res = acm.UX.Dialogs().MessageBoxYesNo(self._frame.Shell(), 'Question',\n 'Are you sure you want to delete the selected trades?')\n if res == 'Button1': # Yes\n trades = self._SelectedTrades()\n instruments = [t.Instrument() for t in trades]\n for bp in self.BusinessProcesses():\n bp.Delete()\n for trade in trades:\n trade.Delete()\n for ins in set(instruments):\n if not ins.Trades():\n ins.Delete()\n\n\nclass AssignMenuItem(SecLendingWorkflowMenuItem):\n\n def Invoke(self, eii):\n editedTrades = []\n assignedTrades = {}\n for trade in self._SelectedTrades():\n assignedTrades.setdefault(trade.Trader(), []).append(trade)\n with Transaction():\n for trade in self._SelectedTrades():\n if trade.StorageId() == trade.Originator().StorageId():\n trade = trade.StorageImage()\n trade.Trader(acm.User())\n trade.AddInfoValue('SBL_ToDoList', eii.MenuExtension().GetString('ToDoList'))\n trade.Commit()\n else:\n editedTrades.append(trade)\n # Edited trades need to be handled separetly.\n # They shouldn't be commited as they're already an image of the original\n # They can't be changed within a transaction as that will mute notifications\n # The should only be changed it the transaction succeeds\n for trade in editedTrades:\n trade.Trader(acm.User())\n \n for trader, trades in assignedTrades.items():\n if trader != acm.User():\n acm.SendUserMessage([trader], \"Assigned orders\", \"%s has assigned himself to the attached orders\" % acm.User().Name(), trades)\n\n def Enabled(self):\n return bool(self._SelectedTrades())\n\n\nclass HoldMenuItem(SecLendingWorkflowMenuItem):\n\n def Invoke(self, eii):\n self.HoldTrade()\n \n def SetHoldTime(self, trade, time, hold):\n FSecLendHoldTrade.HoldTrade(trade, time) if hold else FSecLendHoldTrade.UnholdTrade(trade)\n\n def HoldTrade(self, time=None, hold=True):\n editedTrades = []\n with Transaction():\n for trade in self._SelectedTrades():\n if trade.StorageId() == trade.Originator().StorageId():\n self.SetHoldTime(trade, time, hold)\n trade.Commit()\n else:\n editedTrades.append(trade)\n # Edited trades need to be handled separetly.\n # They shouldn't be commited as they're already an image of the original\n # They can't be changed within a transaction as that will mute notifications\n # The should only be changed it the transaction succeeds\n for trade in editedTrades:\n self.SetHoldTime(trade, time, hold)\n\nclass HoldOneHourMenuItem(HoldMenuItem):\n\n def Invoke(self, eii):\n timeOneHour = datetime.now()+timedelta(hours=1)\n self.HoldTrade(timeOneHour)\n\n\nclass HoldThreeHoursMenuItem(HoldMenuItem):\n\n def Invoke(self, eii):\n timeThreeHours = datetime.now()+timedelta(hours=3)\n self.HoldTrade(time=timeThreeHours)\n\n\nclass HoldEndOfDayMenuItem(HoldMenuItem):\n\n def Invoke(self, eii):\n if _SETTINGS.EndOfBusinessDay() is not None:\n hour, min = _SETTINGS.EndOfBusinessDay().split(':')\n timeEndOfDay = datetime.today().replace(hour=int(hour), minute=int(min), second=0, microsecond=0)\n self.HoldTrade(timeEndOfDay)\n else:\n timeEndOfDay = datetime.today().replace(hour=18, minute=0, second=0, microsecond=0)\n self.HoldTrade(timeEndOfDay)\n\n\nclass RemoveHoldMenuItem(HoldMenuItem):\n \n def Invoke(self, eii):\n self.HoldTrade(hold=False)\n\n\nclass TradeOrigin(SecLendingWorkflowMenuItem):\n\n def Invoke(self, eii):\n trade = self._SelectedTrades()[0]\n info = FSecLendHooks.GetTradeOriginInfo(trade)\n dlg = FSecLendUtils.InformationDialog(\"Trade Origin\", info, 500, 500)\n acm.UX().Dialogs().ShowCustomDialog(self._frame.Shell(), dlg.CreateLayout(), dlg)\n\n def Enabled(self):\n enabled = False\n if len(self._SelectedTrades()) == 1:\n enabled = bool(self._SelectedTrades()[0].AddInfoValue('SBL_TradeOriginId'))\n return enabled\n\n\nclass FlipSignMenuItem(SecLendingWorkflowMenuItem):\n\n def Invoke(self, eii):\n editedTrades = []\n with Transaction():\n for trade in self._SelectedTrades():\n if trade.StorageId() == trade.Originator().StorageId():\n trade.Quantity(-trade.Quantity())\n trade.Commit()\n else:\n editedTrades.append(trade)\n # Edited trades need to be handled separetly.\n # They shouldn't be commited as they're already an image of the original\n # They can't be changed within a transaction as that will mute notifications\n # The should only be changed it the transaction succeeds\n for trade in editedTrades:\n trade.Quantity(-trade.Quantity())\n\n\nclass ApplySuggestedFeeItem(SecLendingWorkflowMenuItem):\n\n def Invoke(self, eii):\n editedTrades = []\n with Transaction():\n for trade in self._SelectedTrades():\n if trade.StorageId() == trade.Originator().StorageId() and trade.StorageId() > 0:\n FSecLendUtils.SetDefaultRate(trade) # Only changes the instrument\n trade.Instrument().Commit()\n else:\n editedTrades.append(trade)\n # Edited trades need to be handled separetly.\n # They shouldn't be commited as they're already an image of the original\n # They can't be changed within a transaction as that will mute notifications\n # The should only be changed it the transaction succeeds\n for trade in editedTrades:\n FSecLendUtils.SetDefaultRate(trade)\n\n\ndef FlipSign(eii):\n return FlipSignMenuItem(eii)\n\n\ndef Assign(eii):\n return AssignMenuItem(eii)\n\n \ndef Hold(eii):\n return HoldMenuItem(eii)\n\n\ndef HoldOneHour(eii):\n return HoldOneHourMenuItem(eii)\n\n\ndef HoldThreeHours(eii):\n return HoldThreeHoursMenuItem(eii)\n\n\ndef RemoveHold(eii):\n return RemoveHoldMenuItem(eii)\n \n\ndef HoldEndOfDay(eii):\n return HoldEndOfDayMenuItem(eii)\n\n\ndef InspectWorkflow(eii):\n return InspectWorkflowMenuItem(eii)\n\n\ndef Book(eii):\n return BookMenuItem(eii)\n\n\ndef ReCheck(eii):\n return ReCheckMenuItem(eii)\n\n\ndef Respond(eii):\n return RespondMenuItem(eii)\n\n\ndef Reject(eii):\n return RejectMenuItem(eii)\n\n\ndef ManualApprove(eii):\n return ManualApproveMenuItem(eii)\n\n\ndef DeleteTrade(eii):\n return DeleteTradeMenuItem(eii)\n\n\ndef ApplySuggestedFee(eii):\n return ApplySuggestedFeeItem(eii)\n \n","sub_path":"Extensions/_securities_lending_py/FPythonCode/FSecLendOrdersMenuItems.py","file_name":"FSecLendOrdersMenuItems.py","file_ext":"py","file_size_in_byte":20385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"612827159","text":"import logging\nimport threading\n\nfrom google.appengine.api import datastore\n\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom django.core.signals import request_finished, request_started\nfrom django.dispatch import receiver\nfrom djangae.db import utils\nfrom djangae.db.unique_utils import unique_identifiers_from_entity, _format_value_for_identifier\nfrom djangae.db.backends.appengine.context import ContextStack\n\nlogger = logging.getLogger(\"djangae\")\n\n_context = threading.local()\n\nCACHE_TIMEOUT_SECONDS = getattr(settings, \"DJANGAE_CACHE_TIMEOUT_SECONDS\", 60 * 60)\nCACHE_ENABLED = getattr(settings, \"DJANGAE_CACHE_ENABLED\", True)\n\n\nclass CachingSituation:\n DATASTORE_GET = 0\n DATASTORE_PUT = 1\n DATASTORE_GET_PUT = 2 # When we are doing an update\n\n\ndef ensure_context():\n _context.memcache_enabled = getattr(_context, \"memcache_enabled\", True)\n _context.context_enabled = getattr(_context, \"context_enabled\", True)\n _context.stack = _context.stack if hasattr(_context, \"stack\") else ContextStack()\n\n\ndef _add_entity_to_memcache(model, entity, identifiers):\n cache.set_many({ x: entity for x in identifiers}, timeout=CACHE_TIMEOUT_SECONDS)\n\n\ndef _get_cache_key_and_model_from_datastore_key(key):\n model = utils.get_model_from_db_table(key.kind())\n\n if not model:\n # This should never happen.. if it does then we can edit get_model_from_db_table to pass\n # include_deferred=True/included_swapped=True to get_models, whichever makes it better\n raise AssertionError(\"Unable to locate model for db_table '{}' - item won't be evicted from the cache\".format(key.kind()))\n\n # We build the cache key for the ID of the instance\n cache_key = \"|\".join([key.kind(), \"{}:{}\".format(model._meta.pk.column, _format_value_for_identifier(key.id_or_name()))])\n\n return (cache_key, model)\n\n\ndef _remove_entity_from_memcache_by_key(key):\n \"\"\"\n Note, if the key of the entity got evicted from the cache, it's possible that stale cache\n entries would be left behind. Remember if you need pure atomicity then use disable_cache() or a\n transaction.\n \"\"\"\n\n cache_key, model = _get_cache_key_and_model_from_datastore_key(key)\n entity = cache.get(cache_key)\n\n if entity:\n identifiers = unique_identifiers_from_entity(model, entity)\n cache.delete_many(identifiers)\n\n\ndef _get_entity_from_memcache(identifier):\n return cache.get(identifier)\n\n\ndef _get_entity_from_memcache_by_key(key):\n # We build the cache key for the ID of the instance\n cache_key, _ = _get_cache_key_and_model_from_datastore_key(key)\n return cache.get(cache_key)\n\n\ndef add_entity_to_cache(model, entity, situation):\n ensure_context()\n\n identifiers = unique_identifiers_from_entity(model, entity)\n\n # Don't cache on Get if we are inside a transaction, even in the context\n # This is because transactions don't see the current state of the datastore\n # We can still cache in the context on Put() but not in memcache\n if situation == CachingSituation.DATASTORE_GET and datastore.IsInTransaction():\n return\n\n if situation in (CachingSituation.DATASTORE_PUT, CachingSituation.DATASTORE_GET_PUT) and datastore.IsInTransaction():\n # We have to wipe the entity from memcache\n if entity.key():\n _remove_entity_from_memcache_by_key(entity.key())\n\n _context.stack.top.cache_entity(identifiers, entity, situation)\n\n # Only cache in memcache of we are doing a GET (outside a transaction) or PUT (outside a transaction)\n # the exception is GET_PUT - which we do in our own transaction so we have to ignore that!\n if (not datastore.IsInTransaction() and situation in (CachingSituation.DATASTORE_GET, CachingSituation.DATASTORE_PUT)) or \\\n situation == CachingSituation.DATASTORE_GET_PUT:\n\n _add_entity_to_memcache(model, entity, identifiers)\n\n\ndef remove_entity_from_cache(entity):\n key = entity.key()\n remove_entity_from_cache_by_key(key)\n\n\ndef remove_entity_from_cache_by_key(key, memcache_only=False):\n \"\"\"\n Removes an entity from all caches (both context and memcache)\n or just memcache if specified\n \"\"\"\n ensure_context()\n\n if not memcache_only:\n for identifier in _context.stack.top.reverse_cache.get(key, []):\n if identifier in _context.stack.top.cache:\n del _context.stack.top.cache[identifier]\n\n _remove_entity_from_memcache_by_key(key)\n\n\ndef get_from_cache_by_key(key):\n \"\"\"\n Return an entity from the context cache, falling back to memcache when possible\n \"\"\"\n\n ensure_context()\n\n if not CACHE_ENABLED:\n return None\n\n ret = None\n if _context.context_enabled:\n # It's safe to hit the context cache, because a new one was pushed on the stack at the start of the transaction\n ret = _context.stack.top.get_entity_by_key(key)\n if ret is None and not datastore.IsInTransaction():\n if _context.memcache_enabled:\n ret = _get_entity_from_memcache_by_key(key)\n elif _context.memcache_enabled and not datastore.IsInTransaction():\n ret = _get_entity_from_memcache_by_key(key)\n\n return ret\n\n\ndef get_from_cache(unique_identifier):\n \"\"\"\n Return an entity from the context cache, falling back to memcache when possible\n \"\"\"\n\n ensure_context()\n\n if not CACHE_ENABLED:\n return None\n\n ret = None\n if _context.context_enabled:\n # It's safe to hit the context cache, because a new one was pushed on the stack at the start of the transaction\n ret = _context.stack.top.get_entity(unique_identifier)\n if ret is None and not datastore.IsInTransaction():\n if _context.memcache_enabled:\n ret = _get_entity_from_memcache(unique_identifier)\n elif _context.memcache_enabled and not datastore.IsInTransaction():\n ret = _get_entity_from_memcache(unique_identifier)\n\n return ret\n\n\n@receiver(request_finished)\n@receiver(request_started)\ndef reset_context(keep_disabled_flags=False, *args, **kwargs):\n \"\"\"\n Called at the beginning and end of each request, resets the thread local\n context. If you pass keep_disabled_flags=True the memcache_enabled and context_enabled\n flags will be preserved, this is really only useful for testing.\n \"\"\"\n\n memcache_enabled = getattr(_context, \"memcache_enabled\", True)\n context_enabled = getattr(_context, \"context_enabled\", True)\n\n for attr in (\"stack\", \"memcache_enabled\", \"context_enabled\"):\n if hasattr(_context, attr):\n delattr(_context, attr)\n\n ensure_context()\n\n if keep_disabled_flags:\n _context.memcache_enabled = memcache_enabled\n _context.context_enabled = context_enabled\n","sub_path":"djangae/db/backends/appengine/caching.py","file_name":"caching.py","file_ext":"py","file_size_in_byte":6778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"513090863","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('release', '0005_release_comments'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='release',\n name='name',\n field=models.ForeignKey(related_name='project_release', to='release.projectinfo'),\n ),\n ]\n","sub_path":"release/migrations/0006_auto_20151013_0320.py","file_name":"0006_auto_20151013_0320.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"314655992","text":"# -*- coding: utf-8 -*-\n\nfrom .context import scripts\n\nimport unittest\n\nfrom scripts import get_welcome, get_dt, get_rules\n\nclass BasicTestSuite(unittest.TestCase):\n \"\"\"Basic test cases.\"\"\"\n\n def test_absolute_truth_and_meaning(self):\n assert True\n\n def test_getWelcome(self):\n self.assertEquals(get_welcome(), 'RPSLS - Rock, Paper, Scissor, Lizard, Spock' \\\n '\\nPlease choose from the list below:', 'Should get the welcome message')\n\n def test_shouldGetDT(self):\n self.assertNotEquals(get_dt(), 'Not dt', 'It should not get the dt')\n\n def test_getRules(self):\n self.assertEqual(get_rules(),\n '1. Scissors cuts paper'\n '2. Paper covers rock'\n '3. Rock crushes lizard'\n '4. Lizard poisons Spock'\n '5. Spock smashes scissors'\n '6. Scissors decapitates lizard'\n '7. Lizard eats paper'\n '8. Paper disproves Spock'\n '9. Spock vaporizes rock'\n '10. Rock crushes scissors', 'Should get rules of game')\n\n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"tests/test_basic.py","file_name":"test_basic.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"129475767","text":"from datetime import datetime, timedelta\n\nimport pytest\nfrom asgiref.sync import sync_to_async\nfrom channels.testing import WebsocketCommunicator\nfrom rest_framework.reverse import reverse\nfrom rest_framework.status import HTTP_201_CREATED\nfrom thenewboston.utils.signed_requests import generate_signed_request\n\nfrom v1.notifications.constants import VALIDATOR_CONFIRMATION_SERVICE_NOTIFICATION\nfrom ..consumers.validator_confirmation_service import ValidatorConfirmationServiceConsumer\n\n\n@pytest.mark.asyncio\nasync def test_validator_confirmation_service_post_async(\n client, validator, signing_key\n):\n communicator = WebsocketCommunicator(\n ValidatorConfirmationServiceConsumer,\n 'ws/validator_confirmation_services'\n )\n connected, subprotocol = await communicator.connect()\n assert connected\n\n start = datetime.now().isoformat()\n end = (datetime.now() + timedelta(days=2)).isoformat()\n\n payload = generate_signed_request(\n data={\n 'start': start,\n 'end': end\n },\n nid_signing_key=signing_key\n )\n\n response = await sync_to_async(\n client.post_json\n )(\n reverse('validatorconfirmationservice-list'),\n payload,\n expected=HTTP_201_CREATED\n )\n communicator_response = await communicator.receive_json_from()\n\n assert response['end'][:-1] == end\n assert response['start'][:-1] == start\n assert response['validator'] == str(validator.pk)\n\n assert communicator_response == {\n 'notification_type': VALIDATOR_CONFIRMATION_SERVICE_NOTIFICATION,\n 'payload': {\n 'bank_node_identifier': validator.node_identifier,\n 'validator_confirmation_service': response\n }\n }\n\n await communicator.disconnect()\n","sub_path":"v1/validator_confirmation_services/tests/validator_confirmation_service_async.py","file_name":"validator_confirmation_service_async.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"283047284","text":"\"\"\"empty message\n\nRevision ID: 9b53a6374401\nRevises: ec07f067b572\nCreate Date: 2019-11-04 12:49:36.086719\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '9b53a6374401'\ndown_revision = 'ec07f067b572'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('soft',\n sa.Column('soft_id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=50), nullable=True),\n sa.Column('version', sa.String(length=30), nullable=True),\n sa.Column('cost', sa.Integer(), nullable=True),\n sa.Column('creation_date', sa.Date(), nullable=True),\n sa.PrimaryKeyConstraint('soft_id')\n )\n op.add_column('repo', sa.Column('soft_id', sa.Integer(), nullable=True))\n op.create_foreign_key(None, 'repo', 'soft', ['soft_id'], ['soft_id'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'repo', type_='foreignkey')\n op.drop_column('repo', 'soft_id')\n op.drop_table('soft')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/9b53a6374401_.py","file_name":"9b53a6374401_.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"324468957","text":"import thread\nimport time\nimport random\nimport threading\nfrom scapy.all import *\n\ndef keep_query():\n\tno_such_domain = 'no-such-domain.com'\n\tdns_query = IP(dst='127.0.0.1')/UDP(dport=53)/DNS(rd=1,qd=DNSQR(qname=no_such_domain, qtype=2))\n\tDNS_RCODE_NXDOMAIN = 3\n\twhile True:\n\t\tprint('query')\n\t\tresponse = sr1(dns_query)\n\t\tresponse.show()\n\t\tif response.rcode != DNS_RCODE_NXDOMAIN:\n\t\t\tprint(response.rdata)\n\t\t\texit(0)\n\t\ttime.sleep(0.5)\n\ndef keep_answer():\n\twhile True:\n\t\tprint('answer')\n\t\tdns_response = DNS(\n\t\t\t\tqr=1, # response packet\n\t\t\t\trd=1,\n\t\t\t\tid=random.randint(1, 65535),\n\t\t\t\tqd=DNSQR(qname='no-such-domain.com', qtype=2),\n\t\t\t\tan=DNSRR(\n\t\t\t\t\t\trrname='no-such-domain.com',\n\t\t\t\t\t\ttype=1,\n\t\t\t\t\t\trclass=1,\n\t\t\t\t\t\tttl=512,\n\t\t\t\t\t\trdata='192.168.0.1'\n\t\t\t\t\t)\n\t\t\t)\n\t\tfake_response = IP(dst='127.0.0.1')/UDP(dport=8000)/dns_response\n\t\tsend(fake_response)\n\t\ttime.sleep(0.2)\n\nif __name__ == '__main__':\n\tno_such_domain = 'no-such-domain.com'\n\tdns_query = IP(dst='127.0.0.1')/UDP()/DNS(rd=1,qd=DNSQR(qname=no_such_domain, qtype=1))\n\tdns_query.show()\n\tsend(dns_query)\n\t# query_thread = threading.Thread(target=keep_query)\n\t# answer_thread = threading.Thread(target=keep_answer)\n\t# answer_thread.setDaemon(True)\n\t# try:\n\t# \tquery_thread.start()\n\t# \tanswer_thread.start()\n\t# except KeyboardInterrupt:\n\t# \texit()\n\t\n","sub_path":"homework/KaminskyAttack.py","file_name":"KaminskyAttack.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"161146581","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\nfrom typing import Union\n\nimport numpy as np\n\n\ndef gen_batch_vectors(\n n_batches: int,\n n_features: int,\n batch_scale: float,\n bio_batch_angle: Union[float, None] = None,\n projection_to_bio: Union[np.ndarray, None] = None,\n) -> np.ndarray:\n \"\"\"Generates a batch-effect vector for each batch, optionally with some\n relation to the biological space\n\n :param n_batches: number of batches\n :param n_features: number of features\n :param batch_scale: size of batch effect relative to data\n :param bio_batch_angle: angle of batch effect w/ bio subspace\n :param projection_to_bio: projection from latent into gene space\n :return: array of shape (n_batches, n_features)\n \"\"\"\n\n norm = lambda X: np.linalg.norm(X, axis=1, keepdims=True)\n\n batch_vectors = np.random.randn(n_batches, n_features)\n batch_vectors = (\n batch_vectors / norm(batch_vectors) * np.mean(norm(expression)) * batch_scale\n )\n\n if bio_batch_angle is not None:\n v_projected = np.dot(batch_vectors, projection_to_bio)\n v_complement = batch_vectors - v_projected\n\n batch_vectors = norm(batch_vectors) * (\n np.sin(bio_batch_angle) * v_complement / norm(v_complement)\n + np.cos(bio_batch_angle) * v_projected / norm(v_projected)\n )\n\n return batch_vectors\n\n\ndef add_batch_vectors(\n expression: np.ndarray,\n batch: np.ndarray,\n batch_scale: Union[int, float],\n bio_batch_angle: Union[float, None],\n projection_to_bio: Union[np.ndarray, None],\n copy: bool = True,\n) -> np.ndarray:\n \"\"\"Generate batch-effect vectors and apply them to the expression data\n\n :param expression: array of true expression, in latent space\n :param batch: indicator of which obs belongs to which batch\n :param batch_scale: batch effect relative to data\n :param bio_batch_angle: angle of batch effect w/ bio subspace\n :param projection_to_bio: projection from latent into gene space\n :param copy: return a copy of the expression array or modify in-place\n :return: expression matrix with batch effect\n \"\"\"\n if copy:\n expression = expression.copy()\n\n n_batches = len(np.unique(batch))\n\n # add batch vector\n batch_vectors = gen_batch_vectors(\n n_batches, expression.shape[1], batch_scale, bio_batch_angle, projection_to_bio\n )\n\n for i in range(n_batches):\n expression[batch == i, :] += batch_vectors[i, :]\n\n return expression\n","sub_path":"src/simscity/batch.py","file_name":"batch.py","file_ext":"py","file_size_in_byte":2500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"176405158","text":"import json\nimport logging\nimport re\nfrom pathlib import Path\nfrom shutil import copy\nfrom typing import AnyStr, List, Optional, Dict, Any\n\nfrom src.python.review.common.file_system import new_temp_dir\nfrom src.python.review.common.subprocess_runner import run_in_subprocess\nfrom src.python.review.inspectors.base_inspector import BaseInspector\nfrom src.python.review.inspectors.inspector_type import InspectorType\nfrom src.python.review.inspectors.issue import BaseIssue, ChildrenNumberIssue, ClassResponseIssue, CodeIssue, \\\n CohesionIssue, \\\n CouplingIssue, InheritanceIssue, IssueType, MethodNumberIssue, WeightedMethodIssue, IssueData\nfrom src.python.review.inspectors.tips import get_child_number_tip, get_class_coupling_tip, get_class_response_tip, \\\n get_cohesion_tip, get_inheritance_depth_tip, get_method_number_tip, get_weighted_method_tip\n\nPATH_TOOLS_SPRINGLINT_FILES = Path(__file__).parent / 'files'\nPATH_SPRINGLINT_JAR = PATH_TOOLS_SPRINGLINT_FILES / 'springlint-0.6.jar'\nSPRINGLINT_OUTPUT_NAME = 'springlint-result.html'\n\nlogger = logging.getLogger(__name__)\n\n\nclass SpringlintInspector(BaseInspector):\n inspector_type = InspectorType.SPRINGLINT\n\n metric_name_to_property = {\n 'dit': 'inheritance_tree_depth',\n 'noc': 'children_number',\n 'wmc': 'weighted_method',\n 'cbo': 'class_objects_coupling',\n 'lcom': 'cohesion_lack',\n 'rfc': 'class_response',\n 'nom': 'method_number'\n }\n\n metric_name_to_description = {\n 'dit': get_inheritance_depth_tip(),\n 'noc': get_child_number_tip(),\n 'wmc': get_weighted_method_tip(),\n 'cbo': get_class_coupling_tip(),\n 'lcom': get_cohesion_tip(),\n 'rfc': get_class_response_tip(),\n 'nom': get_method_number_tip()\n }\n\n metric_name_to_issue_type = {\n 'dit': IssueType.INHERITANCE_DEPTH,\n 'noc': IssueType.CHILDREN_NUMBER,\n 'wmc': IssueType.WEIGHTED_METHOD,\n 'cbo': IssueType.COUPLING,\n 'lcom': IssueType.COHESION,\n 'rfc': IssueType.CLASS_RESPONSE,\n 'nom': IssueType.METHOD_NUMBER\n }\n\n @classmethod\n def _create_command(cls, path: Path, output_path: Path) -> List[str]:\n return [\n 'java', '-jar',\n PATH_SPRINGLINT_JAR,\n '--output', str(output_path),\n '-otype', 'html',\n '--project', str(path)\n ]\n\n def inspect(self, path: Path, config: dict) -> List[BaseIssue]:\n with new_temp_dir() as temp_dir:\n if path.is_file():\n return self._inspect_file(path, temp_dir)\n else:\n return self._inspect_project(path, temp_dir)\n\n @classmethod\n def _inspect_project(cls, path: Path, temp_dir: Path) -> List[BaseIssue]:\n output_path = temp_dir / SPRINGLINT_OUTPUT_NAME\n command = cls._create_command(path, temp_dir)\n run_in_subprocess(command)\n return cls._parse(output_path)\n\n @classmethod\n def _inspect_file(cls, path: Path, temp_dir: Path) -> List[BaseIssue]:\n output_path = temp_dir / SPRINGLINT_OUTPUT_NAME\n copy(str(path), str(temp_dir))\n command = cls._create_command(temp_dir, temp_dir)\n run_in_subprocess(command)\n return cls._parse(output_path, str(path))\n\n @classmethod\n def _parse(cls, output_path: Path, origin_path: str = '') -> List[BaseIssue]:\n if not output_path.is_file():\n logger.error('%s: error - no output file' % cls.inspector_type.value)\n return []\n\n with open(str(output_path)) as out_file:\n file_content = out_file.read()\n issues: List[BaseIssue] = cls._parse_smells(file_content, origin_path)\n issues.extend(cls._parse_metrics(file_content, origin_path))\n return issues\n\n @classmethod\n def _parse_smells(cls, file_content: AnyStr, origin_path: str = '') -> List[BaseIssue]:\n smells_re = re.compile(r'var smells=([^;]*);', re.S)\n smells_string = smells_re.findall(file_content)[0]\n smells = json.JSONDecoder().decode(smells_string)\n\n issues: List[BaseIssue] = []\n for file_smell in smells:\n if origin_path:\n file_path = origin_path\n else:\n file_path = file_smell['file']\n issues.extend([CodeIssue(\n file_path=Path(file_path),\n line_no=1,\n column_no=1,\n origin_class=smell['name'],\n inspector_type=cls.inspector_type,\n type=IssueType.ARCHITECTURE,\n description=smell['description']\n ) for smell in file_smell['smells']])\n\n return issues\n\n @classmethod\n def _parse_metrics(cls, file_content: AnyStr, origin_path: str = '') -> List[BaseIssue]:\n metrics_re = re.compile(r'var classes =([^;]*);', re.S)\n metrics_string = metrics_re.findall(file_content)[0]\n type_metrics_list = json.loads(metrics_string).items()\n\n issues: List[BaseIssue] = []\n for metrics_list in type_metrics_list:\n for metrics in metrics_list[1]:\n for metric_name in metrics:\n if metric_name not in cls.metric_name_to_property:\n continue\n if origin_path:\n file_path = origin_path\n else:\n file_path = metrics['file']\n issues.append(cls._create_issue(metric_name,\n metrics[metric_name],\n Path(file_path)))\n return issues\n\n @classmethod\n def _create_issue(cls, metric_name: str,\n metric_value: int, path: Path) -> Optional[BaseIssue]:\n property_name = cls.metric_name_to_property[metric_name]\n issue_data = cls._get_common_issue_data(path)\n issue_data[property_name] = metric_value\n issue_data['description'] = cls.metric_name_to_description[metric_name]\n issue_data['type'] = cls.metric_name_to_issue_type[metric_name]\n\n if metric_name == 'dit':\n return InheritanceIssue(**issue_data)\n if metric_name == 'noc':\n return ChildrenNumberIssue(**issue_data)\n if metric_name == 'wmc':\n return WeightedMethodIssue(**issue_data)\n if metric_name == 'cbo':\n return CouplingIssue(**issue_data)\n if metric_name == 'lcom':\n return CohesionIssue(**issue_data)\n if metric_name == 'rfc':\n return ClassResponseIssue(**issue_data)\n if metric_name == 'nom':\n return MethodNumberIssue(**issue_data)\n\n return None\n\n @classmethod\n def _get_common_issue_data(cls, file: Path) -> Dict[str, Any]:\n return IssueData.get_base_issue_data_dict(file, cls.inspector_type)\n","sub_path":"src/python/review/inspectors/springlint/springlint.py","file_name":"springlint.py","file_ext":"py","file_size_in_byte":6886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"641239280","text":"\n# encoding=utf-8\n\nfrom .models import Question, Choice\n\n\nQUESTIONS = [\n {\n 'text': u'西西里什么景点最好玩',\n 'choices': [u'海岛', u'山洞', u'卫城', u'小镇']\n }, {\n 'text': u'西西里在哪个国家',\n 'choices': [u'意大利', u'西班牙', u'法国', u'希腊']\n }, {\n 'text': u'西西里是什么气候',\n 'choices': [u'地中海气候', u'海洋性气候', u'季风气候', u'大陆性气候']\n }, {\n 'text': u'西西里和科西嘉是同一个地方么',\n 'choices': [u'一直不是', u'以前是现在不是', u'以前不是现在是', u'一直是']\n }, {\n 'text': u'西西里的有什么好吃的特产',\n 'choices': [u'香肠', u'匹萨', u'汉堡', u'牛肉']\n }, {\n 'text': u'下面哪个是法国著名球星',\n 'choices': [u'里贝里', u'外贝外', u'上贝上', u'下贝下']\n }, {\n 'text': u'下面哪个难题是NP完全问题',\n 'choices': [u'汉密尔顿回路', u'欧拉回路', u'最小生成树', u'单源最短路径']\n }, {\n 'text': u'邓布利多和甘道夫是同一个演员吗',\n 'choices': [u'不一直是', u'一直是', u'一直不是', u'选我肯定是错的']\n }, {\n 'text': u'坎昆和以下哪个城市最近',\n 'choices': [u'佛罗里达', u'纽约', u'莫斯科', u'伦敦']\n }, {\n 'text': u'以下哪支国家队没有出现在2008年欧洲杯中',\n 'choices': [u'英格兰', u'意大利', u'荷兰', u'德国']\n }\n]\n\n\ndef random_questions(city):\n for q in QUESTIONS:\n question = Question.objects.create(city = city,\n text = q['text'])\n choices = [Choice(question = question,\n text = text,\n right = (index == 0))\n for index, text in enumerate(q['choices'])]\n Choice.objects.bulk_create(choices)\n\n\nimport os\ndef insert_questions():\n f = open(os.path.join(os.path.dirname(__file__), 'questions.txt'))\n lines = f.readlines()\n c = 1\n q = 1\n for i in range(0, len(lines), 5):\n margin = 3 if q < 10 else 4\n question = Question.objects.create(city_id = c, text = lines[i][margin:])\n choices = [Choice(question = question, text = lines[i+j], right = False)\n for j in range(1, 5)]\n Choice.objects.bulk_create(choices)\n q += 1\n if q > 10:\n q = 1\n c += 1\n","sub_path":"polls/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"71701451","text":"\"\"\"\nMIT License\n\nCopyright (c) 2018 Edison Neto\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nfrom __future__ import print_function\n\nimport datetime as dt\nimport sys\n\nimport pandas as pd\n\n\nclass NoaaReport(object):\n \"\"\"Reads noaa report.\n\n Reads the last active region on the file from the previous day,\n and compares to the first one.\n\n Arguments:\n year {str or int} -- The report's year.\n month {str or int} -- The report's month.\n day {str or int} -- The report's day.\n \"\"\"\n\n def __init__(self, year, month, day, path):\n self._year = str(year)\n self._month = str(month)\n self._day = str(day)\n self._path = path\n self._filename = self.__set_filename()\n self._data = []\n self.df = None\n\n def __set_filename(self):\n \"\"\"Creates the file name, given the year, month and day.\n\n Returns:\n {str} -- The name of the file.\n \"\"\"\n\n if len(self._month) == 1:\n self._month = \"0\" + self._month\n if len(self._day) == 1:\n self._day = \"0\" + self._day\n\n filename = self._year + self._month + self._day + \"events.txt\"\n filename = self._path + filename\n return filename\n\n def __check_data(self):\n \"\"\"Checks if the data has already been saved.\n\n Returns:\n {bool} -- True if data has alredy been read.\n \"\"\"\n\n if len(self._data):\n return True\n\n self._read_data()\n\n def _read_data(self):\n \"\"\"Reads the file.\n \"\"\"\n\n with open(self._filename) as _file:\n for line in _file.readlines():\n sep = line.split()\n\n try:\n if (not sep[0].startswith(\":\") and\n not sep[0].startswith(\"#\")):\n self._data.append(sep)\n except IndexError:\n pass\n\n for event in self._data:\n if event[1] == \"+\":\n event[0] += \" +\"\n del event[1]\n\n def set_Qs(self):\n \"\"\"Sets the Q column.\n\n Returns:\n {list} -- Contains the value for each line for the column.\n \"\"\"\n\n self.__check_data()\n Qs = []\n for info in self._data:\n if len(info[5]) == 1:\n Qs.append(info[5])\n else:\n Qs.append(None)\n return Qs\n\n def set_observatories(self):\n \"\"\"Set the obs column, and deletes the line (not on the actual file)\n that doesn't contain it.\n\n Returns:\n {list} -- Contains the value for each line for the column.\n \"\"\"\n\n self.__check_data()\n index = 0\n observatories = []\n while index < len(self._data):\n if len(self._data[index][4]) == 3:\n observatories.append(self._data[index][4])\n index += 1\n else:\n del self._data[index]\n\n return observatories\n\n def set_particulars(self):\n \"\"\"I don't know how i made this work. But, \"it just works\"\n - Todd Howard.\n\n Returns:\n {list} -- Contains all the particulars and None if there was\n nothing registered at that moment (I guess that never)\n happens.\n \"\"\"\n\n self.__check_data()\n particulars = []\n index = 0\n regs = self.set_regions()\n while index < len(self._data):\n try:\n last_index = len(self._data[index]) - 1\n last_reg = \"\"\n for reg in regs:\n if reg is not None:\n last_reg = reg\n break\n\n # If the last thing in a row is a 4 digit number.\n if (self._data[index][last_index].isdigit()\n and len(self._data[index][last_index]) == 4):\n # If there are more than 10 things in a row.\n if len(self._data[index]) > 10:\n particular = (self._data[index][last_index - 2] + \" \" +\n self._data[index][last_index - 1])\n elif (int(self._data[index][last_index])+25 <= int(last_reg)\n and int(self._data[index][last_index])-25 >= int(last_reg)):\n particular = self._data[index][last_index]\n else:\n particular = self._data[index][last_index - 1]\n else:\n if len(self._data[index]) > 9:\n particular = (self._data[index][last_index - 1] + \" \" +\n self._data[index][last_index])\n else:\n particular = self._data[index][last_index]\n\n particulars.append(particular)\n except IndexError:\n particulars.append(None)\n\n index += 1\n\n return particulars\n\n def set_regions(self, valid_regions_day_before=None):\n \"\"\"Get the regions from the file.\n The region to be valid must be a 4 digit number.\n There's a range of 25 to check if the other number will be a region,\n or not.\n The function gets the active regions from the other day to compare and\n check if the number is truly and active region.\n\n Returns:\n {list} -- A list containing the regions and None if there is no\n region at that time.\n \"\"\"\n\n self.__check_data()\n reg = []\n valid_regions = []\n for info in self._data:\n try:\n last_index = len(info) - 1\n if info[last_index].isdigit() and len(info[last_index]) == 4:\n if len(valid_regions) == 0 and info[last_index] != \"0000\":\n if valid_regions_day_before is not None:\n if (int(info[last_index]) >= int(valid_regions_day_before[-1])-25\n and int(info[last_index]) <= int(valid_regions_day_before[-1])+25):\n reg.append(info[last_index])\n valid_regions.append(info[last_index])\n else:\n reg.append(None)\n else:\n reg.append(info[last_index])\n valid_regions.append(info[last_index])\n elif (int(info[last_index]) >= int(valid_regions[-1]) - 25\n and int(info[last_index]) <= int(valid_regions[-1]) + 25\n and info[last_index] != \"0000\"):\n reg.append(info[last_index])\n valid_regions.append(info[last_index])\n else:\n reg.append(None)\n else:\n reg.append(None)\n except IndexError:\n reg.append(None)\n\n return reg\n\n def set_event(self):\n \"\"\"Sets the event column.\n\n Returns:\n {list} -- Contains the value for each line for the column.\n \"\"\"\n\n self.__check_data()\n return [i[0] for i in self._data]\n\n def set_begin(self):\n \"\"\"Sets the begin column.\n\n Returns:\n {list} -- Contains the value for each line for the column.\n \"\"\"\n\n self.__check_data()\n return [i[1] for i in self._data]\n\n def set_max(self):\n \"\"\"Sets the max column.\n\n Returns:\n {list} -- Contains the value for each line for the column.\n \"\"\"\n\n self.__check_data()\n return [i[2] for i in self._data]\n\n def set_end(self):\n \"\"\"Sets the end column.\n\n Returns:\n {list} -- Contains the value for each line for the column.\n \"\"\"\n\n self.__check_data()\n return [i[3] for i in self._data]\n\n def set_type(self):\n \"\"\"Sets the type column.\n\n Returns:\n {list} -- Contains the value for each line for the column.\n \"\"\"\n\n self.__check_data()\n return [i[6] for i in self._data]\n\n def set_freq(self):\n \"\"\"Sets the loc/freq column.\n\n Returns:\n {list} -- Contains the value for each line for the column.\n \"\"\"\n\n self.__check_data()\n return [i[7] for i in self._data]\n\n @classmethod\n def get_regions_from_other_day(cls, year, month, day, path):\n \"\"\"Gets all the not None regions from the day before the one\n being read.\n\n Arguments:\n year {str or int} -- The yesr being read.\n month {str or int} -- The month being read.\n day {str or int} -- The day being read.\n path {str} -- File's path.\n\n Returns:\n {list} -- All the not None active regions from the day before.\n \"\"\"\n\n date = dt.date(int(year), int(month), int(day))\n day_before = date - dt.timedelta(days=1)\n\n report = cls(day_before.year, day_before.month, day_before.day, path)\n regs = report.set_regions()\n regs = [x for x in regs if x is not None]\n return regs\n\n def set_final_data(self):\n \"\"\"Stores all the data in a dataframe.\n\n Returns:\n {pd.DataFrame} - A DataFrame with the data.\n \"\"\"\n\n self.__check_data()\n\n regs = NoaaReport.get_regions_from_other_day(self._year, self._month,\n self._day, self._path)\n\n # observatories must be declared first, because it changes the\n # data list.\n final_data = {\n \"obs\": self.set_observatories(),\n \"event\": self.set_event(),\n \"begin\": self.set_begin(),\n \"max\": self.set_max(),\n \"end\": self.set_end(),\n \"Q\": self.set_Qs(),\n \"type\": self.set_type(),\n \"loc/freq\": self.set_freq(),\n \"particulars\": self.set_particulars(),\n \"reg\": self.set_regions(regs)\n }\n\n columns = [\"event\", \"begin\", \"max\",\n \"end\", \"obs\", \"Q\", \"type\",\n \"loc/freq\", \"particulars\", \"reg\"]\n\n self.df = pd.DataFrame(final_data, columns=columns)\n\n return self.df\n\n def get_active_region(self, start_time, end_time):\n \"\"\"Returns registered active region of a certain time range.\n\n Arguments:\n start_time {str} -- event's start time.\n end_time {str} -- event's end time.\n\n Returns:\n {list} -- All the not None active regions.\n \"\"\"\n\n start_time = str(start_time)\n end_time = str(end_time)\n start_time = start_time[11:16].replace(\":\", \"\")\n start_time = dt.timedelta(hours=int(start_time[0:2]),\n minutes=int(start_time[2:]))\n end_time = end_time[11:16].replace(\":\", \"\")\n end_time = dt.timedelta(hours=int(end_time[0:2]),\n minutes=int(end_time[2:]))\n ar = []\n\n for i in range(0, len(self.df)):\n\n if not self.df[\"begin\"][i][0].isnumeric():\n self.df[\"begin\"][i] = self.df[\"begin\"][i][1:]\n if not self.df[\"max\"][i][0].isnumeric():\n self.df[\"max\"][i] = self.df[\"max\"][i][1:]\n if not self.df[\"end\"][i][0].isnumeric():\n self.df[\"end\"][i] = self.df[\"end\"][i][1:]\n\n event_begin = dt.timedelta(hours=int(self.df[\"begin\"][i][0:2]),\n minutes=int(self.df[\"begin\"][i][2:]))\n\n event_end = dt.timedelta(hours=int(self.df[\"end\"][i][0:2]),\n minutes=int(self.df[\"end\"][i][2:]))\n\n eleven_oclock = dt.timedelta(hours=23, minutes=00)\n fifteen_minutes = dt.timedelta(minutes=15)\n if event_begin >= eleven_oclock:\n continue\n\n if event_begin >= start_time and event_end <= end_time + fifteen_minutes:\n print(\"\\nBegin: {}\".format(self.df[\"begin\"][i]))\n print(\"Max: {}\".format(self.df[\"max\"][i]))\n print(\"End: {}\".format(self.df[\"end\"][i]))\n print(\"Type: {}\".format(self.df[\"type\"][i]))\n print(\"Loc/Freq: {}\".format(self.df[\"loc/freq\"][i]))\n print(\"Region: {}\".format(self.df[\"reg\"][i]))\n\n ar.append(self.df[\"reg\"][i])\n\n ar = [x for x in ar if x is not None]\n if len(ar) == 0:\n print(\"No regions identified.\")\n\n return ar\n\n def stuff(self):\n saves = []\n for i in range(0, len(self.df)):\n if (self.df[\"type\"][i] == \"XRA\" and (\n self.df[\"particulars\"][i].startswith(\"M\")\n or self.df[\"particulars\"][i].startswith(\"X\"))):\n if (int(self.df[\"begin\"][i]) < 800\n or int(self.df[\"begin\"][i]) > 1800):\n continue\n saves.append(i)\n\n for sav in saves:\n if sav+5 > len(self.df[\"type\"]):\n df_max = (len(self.df[\"type\"])-1)\n for i in range(sav-5, df_max):\n if self.df[\"type\"][i] == \"RBR\":\n print(\"\\nBegin: {}\".format(self.df[\"begin\"][i]))\n print(\"Freq: {}\".format(self.df[\"loc/freq\"][i]))\n print(\"Particulars: {}\".format(self.df[\"particulars\"][i]))\n print(\"Index: {}\".format(i))\n\n if sav > 5:\n for i in range(sav-5, sav+5):\n if self.df[\"type\"][i] == \"RBR\":\n print(\"\\nBegin: {}\".format(self.df[\"begin\"][i]))\n print(\"Freq: {}\".format(self.df[\"loc/freq\"][i]))\n print(\"Particulars: {}\".format(self.df[\"particulars\"][i]))\n print(\"Index: {}\".format(i))\n else:\n for i in range(0, sav+5):\n if self.df[\"type\"][i] == \"RBR\":\n print(\"\\nBegin: {}\".format(self.df[\"begin\"][i]))\n print(\"Freq: {}\".format(self.df[\"loc/freq\"][i]))\n print(\"Particulars: {}\".format(self.df[\"particulars\"][i]))\n print(\"Index: {}\".format(i))\n\n\nif __name__ == \"__main__\":\n report = NoaaReport(sys.argv[1], sys.argv[2], sys.argv[3],\n sys.argv[4])\n report.set_final_data()\n if len(sys.argv) > 5:\n ars = report.get_active_region(sys.argv[5], sys.argv[6])\n print(ars)\n","sub_path":"noaareport/noaareport.py","file_name":"noaareport.py","file_ext":"py","file_size_in_byte":15616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"130982750","text":"# The MIT License (MIT)\n# \n# Copyright (c) 2015 addfor s.r.l.\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\"\"\"\nColor and color palette management helper functions.\n\nThis modules provides some simple functions to help with the management and\nuse of colors and color palettes. Although it was written to be used\nwith Bokeh, it doesn't really have any dependency, and can be used\nanywhere else it could be useful.\n\nFunctions:\n linear_map - map (linearly) a sequence of real values to the given palette\n sample_mpl_cmap - convert a Matplotlib-like colormap to a simple array of colors\n to_rgb_bytes - converts a color expressed as an RGB [0.0, 1.0]-ranged tuple to a RGB bytes (int 0-255) tuple\n to_hex - converts a color expressed as an RGB [0.0, 1.0]-ranged tuple to a hex representation #aabbcc\n\nVariables:\n mpl_cmap_jet - Colormap from Matplotlib: jet (deprecated)\n mpl_cmap_hot - Colormap from Matplotlib: hot\n\n jet_hex, hot_hex, jet_bytes, hot_bytes -\n *_hex: matplotlib colormap converted to hex representation\n *_bytes: matplotlib colormap converted to bytes (int 0-255) tuple\n\"\"\"\n\nmpl_cmap_jet = {'red': ((0., 0, 0), (0.35, 0, 0), (0.66, 1, 1), (0.89, 1, 1),\n (1, 0.5, 0.5)),\n 'green': ((0., 0, 0), (0.125, 0, 0), (0.375, 1, 1), (0.64, 1, 1),\n (0.91, 0, 0), (1, 0, 0)),\n 'blue': ((0., 0.5, 0.5), (0.11, 1, 1), (0.34, 1, 1),\n (0.65, 0, 0), (1, 0, 0))}\n\nmpl_cmap_hot = {'red': ((0. , 0.0416, 0.0416),\n (0.365079 , 1.000000, 1.000000),\n (1.0 , 1.0, 1.0)),\n 'green': ((0. , 0., 0.),\n (0.365079 , 0.000000, 0.000000),\n (0.746032 , 1.000000, 1.000000),\n (1.0 , 1.0, 1.0)),\n 'blue': ((0. , 0., 0.),\n (0.746032 , 0.000000, 0.000000),\n (1.0 , 1.0, 1.0))}\n\ndef sample(channel, pos):\n try:\n idx_b = next((idx for idx, it in enumerate(channel) if it[0] >= pos))\n except StopIteration:\n return channel[-1][1]\n\n idx_a = max(0, idx_b - 1)\n if idx_a == idx_b:\n return channel[idx_a][1]\n \n pos_a, val_a, _ = channel[idx_a]\n pos_b, val_b, _ = channel[idx_b]\n dx = (pos - pos_a) / (pos_b - pos_a)\n return val_a + dx * (val_b - val_a)\n\ndef sample_mpl_cmap(cmap, nsamples):\n #channels = map(list, [ cmap['red'], cmap['green'], cmap['blue'] ])\n channels = [list(b) for b in [ cmap['red'], cmap['green'], cmap['blue'] ] ]\n\n\n for chan in channels:\n # Sort stops by position\n chan.sort(key=lambda stop: stop[0])\n\n positions = [ 1.0 / nsamples * i for i in range(nsamples+1) ]\n \n samples = []\n for pos in positions:\n r, g, b = map(lambda chan: sample(chan, pos), channels)\n samples.append((r,g,b))\n \n return samples\n\njet = sample_mpl_cmap(mpl_cmap_jet, 80)\nhot = sample_mpl_cmap(mpl_cmap_hot, 80)\n\ndef to_rgb_bytes(rgb):\n r, g, b = rgb[:3]\n r = int(min(1, r) * 255)\n g = int(min(1, g) * 255)\n b = int(min(1, b) * 255)\n return (r,g,b)\n\njet_rgb = map(to_rgb_bytes, jet)\nhot_rgb = map(to_rgb_bytes, hot)\n\ndef to_hex(rgb):\n return \"#%02x%02x%02x\" % to_rgb_bytes(rgb)\n\njet_hex = map(to_hex, jet)\nhot_hex = map(to_hex, hot)\n\ndef linear_map(xs, palette, low=None, high=None):\n \"\"\"Map (linearly) a sequence of real values to the given palette.\n \n Parameters:\n xs - A list of numbers, in the range [low, high]\n palette - A list of colors\n\n Returns:\n A list of the same size of xs, with the color of each sample\n \"\"\"\n \n if xs == []: return []\n \n if low == None:\n low = min(xs)\n if high == None:\n high = max(xs)\n\n idx = lambda x: int( (float(x) - low)\n / (high - low)\n * (len(palette)-1) )\n clamped = [ max(low, min(high, x)) for x in xs ]\n return [ palette[ idx(x) ] for x in clamped ]\n\n","sub_path":"addutils/palette.py","file_name":"palette.py","file_ext":"py","file_size_in_byte":5148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"547875770","text":"# AsynQueue:\n# Asynchronous task queueing based on the Twisted framework, with task\n# prioritization and a powerful worker/manager interface.\n#\n# Copyright (C) 2006-2007, 2015 by Edwin A. Suominen,\n# http://edsuom.com/AsynQueue\n#\n# See edsuom.com for API documentation as well as information about\n# Ed's background and other projects, software and otherwise.\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the\n# License. You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an \"AS\n# IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language\n# governing permissions and limitations under the License.\n\n\"\"\"\nUnit tests for mcmandelbrot.runner\n\"\"\"\n\nimport png\n\nfrom twisted.internet import defer\n\nfrom mcmandelbrot import main\nfrom mcmandelbrot.test.testbase import TestCase\n\n \nclass TestRun(TestCase):\n verbose = True\n \n @defer.inlineCallbacks\n def test_basic(self):\n N = 100\n filePath = \"image.png\"\n runInfo = yield self.checkProducesFile(\n filePath, main.run,\n \"-o\", filePath, 100, -0.630, 0, 1.4,\n ignoreReactor=True)\n self.assertEqual(runInfo[1], N*N)\n\n","sub_path":"mcmandelbrot/test/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"445818289","text":"from selenium import webdriver\nfrom fixture.session import SessionHelper\n\n\n# Класс-менеджер, который инициализирует всех помощников\nclass Application:\n\n # создание фикстуры, инициализация драйвера\n def __init__(self, browser, base_url):\n if browser == \"firefox\":\n self.wd = webdriver.Firefox(capabilities={\"marionette\": False})\n elif browser == \"chrome\":\n self.wd = webdriver.Chrome()\n elif browser == \"ie\":\n self.wd = webdriver.Ie\n# self.wd.implicitly_wait(60)\n else:\n raise ValueError(\"Unrecognized browser %s\", browser)\n # конструирование помощников, передаем ссылку на саму фикстуру\n self.session = SessionHelper(self)# помощник сесссий получает ссылку на объект класса Application\n self.base_url = base_url\n\n def open_home_page(self): # метод навигации, кандидат на перенос в соответ.помощник\n wd = self.wd\n wd.get(self.base_url)\n\n # метод разрушает фикстуру, останавливает браузер\n def destroy(self):\n self.wd.quit()\n\n # метод проверяет валидность фикстуры\n def is_valid(self):\n try:\n self.wd.current_url\n return True\n except:\n return False\n\n\n","sub_path":"fixture/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"276187426","text":"\nclass readMKP:\n\n def read_MkpProblems():\n problems = dict();\n problems['data'] = []\n problems['capacidad'] = []\n problems['beneficio'] = []\n problems['pesos'] = []\n problems['optimo'] = []\n f = open(\"./mkp_problems.txt\", \"r\")\n lines = f.readlines()\n for line in lines:\n if '#' in line:\n data = lines[lines.index(line)+1].split()\n data = list(map(int, data))\n nmochilas = data[1]\n capacidad = lines[lines.index(line)+2].split()\n capacidad = list(map(float, capacidad))\n beneficio = lines[lines.index(line)+3].split()\n beneficio = list(map(float, beneficio))\n optimo = float(lines[lines.index(line)+4+nmochilas])\n pesos = []\n #print(data)\n problems['data'].append(data)\n #print(capacidad)\n problems['capacidad'].append(capacidad) \n #print(beneficio)\n problems['beneficio'].append(beneficio)\n for knapsack in range(lines.index(line)+4,lines.index(line)+4+nmochilas):\n mochila_pesos = lines[knapsack].split()\n mochila_pesos = list(map(float, mochila_pesos))\n pesos.append(mochila_pesos)\n #print(pesos)\n problems['pesos'].append(pesos)\n #print(optimo)\n problems['optimo'].append(optimo)\n\n f.close()\n return problems\n","sub_path":"repo/readMKP.py","file_name":"readMKP.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"136732847","text":"from django.shortcuts import render_to_response\nfrom django.shortcuts import render\nfrom django.template import RequestContext\nfrom django.http import HttpResponseRedirect\nfrom django.contrib.auth.decorators import user_passes_test\nfrom django.core.urlresolvers import reverse\nfrom django.contrib import messages\nimport forms\nimport django.forms as dforms\nfrom base import models\nfrom base.templatetags import diagram\nfrom browse import view_curation\n\n@user_passes_test(lambda u: u.is_superuser)\ndef home(request):\n \"\"\"Entry point for validate curation\"\"\"\n template_file = \"validate_curation_main.html\"\n return render_to_response(template_file, {}, context_instance=RequestContext(request))\n\ndef view_edit_validate(request):\n \"\"\"View main page for edit/validate curations\"\"\"\n template_file = \"validate_edit_or_validate.html\"\n # get all not validated curations\n curations = models.Curation.objects.\\\n filter(validated_by=None).\\\n order_by('created').all()\n template = {'curations': curations}\n return render_to_response(template_file, template,\n context_instance=RequestContext(request))\n\ndef view_validated_curations(request):\n \"\"\"View page to view validated curations.\"\"\"\n template_file = \"validate_view_curations.html\"\n # get all validated curation objects\n curations = models.Curation.objects.\\\n exclude(validated_by=None).\\\n order_by('created').all()\n template = {'curations': curations}\n return render_to_response(template_file, template,\n context_instance=RequestContext(request))\n\n@user_passes_test(lambda u: u.is_superuser)\ndef edit_curation(request, curation_id):\n return edit_curation.edit_curation(request, curation_id)\n\n\n@user_passes_test(lambda u: u.is_superuser)\ndef validate_curation(request, curation_id):\n \"\"\"Validate curation handler.\"\"\"\n if request.method == 'POST':\n curation = models.Curation.objects.get(pk=request.POST[\"curation_id\"])\n form = forms.EditCurationForm(request.POST, curation=curation)\n \n if form.is_valid():\n validate_form_done(request, form, curation)\n messages.add_message(request, messages.SUCCESS, \"Curation was modified/validated successfully.\")\n return HttpResponseRedirect(reverse(browseapp.view_curation.view_curation, kwargs={'cid': curation.pk}))\n else:\n curation = models.Curation.objects.get(pk=curation_id)\n # initial data preparation functions\n form = validate_get_form(curation)\n template = {'form': form,\n 'curation': curation}\n \n return render(request, \"validate_curation.html\",\n {'form': form, 'curation': curation},\n context_instance=RequestContext(request))\n\n@user_passes_test(lambda u: u.is_superuser)\ndef edit_validated_curation(request, curation_id):\n if request.method == 'POST':\n curation = models.Curation.objects.get(pk=request.POST[\"curation_id\"])\n form = forms.EditCurationForm(request.POST, curation=curation)\n if form.is_valid():\n validate_form_done(request, form, curation)\n messages.add_message(request, messages.SUCCESS, \"Curation was modified/validated successfully.\")\n return HttpResponseRedirect(reverse(browseapp.view_curation.view_curation, kwargs={'cid': curation.pk}))\n else:\n curation = models.Curation.objects.get(pk=curation_id)\n form = validate_get_form(curation)\n # check if any of the sites has been submitted to NCBI.\n ncbi_submitted = False\n csis = curation.curation_siteinstance_set.all()\n if models.NCBISubmission.objects.filter(curation_site_instance__in=csis):\n ncbi_submitted = True\n\n template = {'form': form,\n 'curation': curation,\n 'ncbi_submitted': ncbi_submitted,}\n \n return render(request, \"validate_curation.html\",\n template,\n context_instance=RequestContext(request))\n\n\ndef validate_get_form(curation):\n def get_genome_accession():\n if curation.site_instances.all():\n return curation.site_instances.all()[0].genome.genome_accession\n return \"\"\n def get_used_techniques():\n ts = curation.experimental_techniques.all()\n return [str(t.technique_id) for t in ts]\n def get_external_db():\n try:\n external_db = models.Curation_ExternalDatabase.objects.get(curation=curation)\n except models.Curation_ExternalDatabase.DoesNotExist:\n external_db = None\n return external_db\n\n def populate_site_instances(form):\n for csi in curation.curation_siteinstance_set.all():\n site_instance = csi.site_instance\n seq = csi.site_instance.seq\n strand = '+' if site_instance.strand == 1 else '-'\n loc = '[%d,%d]' % (site_instance.start+1, site_instance.end+1)\n label = pretty_print.site2label(csi.pk, seq+' '+strand+loc)\n help_text = gene_diagram.regulation_diagram(csi.regulation_set.all(), csi.site_instance)\n form.fields[\"site_instance_%d\"%csi.pk] = dforms.BooleanField(label=label,\n help_text=help_text,\n required=False)\n form.fields[\"site_instance_%d\"%csi.pk].initial = True\n \n external_db = get_external_db()\n data = dict(\n # genome/TF initialization\n TF = curation.TF,\n TF_type = curation.TF_type,\n genome_accession = get_genome_accession(),\n TF_accession = curation.TF_instance.protein_accession,\n TF_species = curation.TF_species,\n site_species = curation.site_species,\n # techniques initialization\n techniques = get_used_techniques(),\n experimental_process = curation.experimental_process,\n forms_complex = curation.forms_complex,\n complex_notes = curation.complex_notes,\n external_db_type = (external_db.external_database.ext_database_id\n if external_db else None),\n external_db_accession = (external_db.accession_number\n if external_db else \"\"),\n # curation review initialization\n revision_reasons = curation.requires_revision,\n confidence = curation.confidence,\n paper_complete = curation.publication.curation_complete,\n NCBI_submission_ready = curation.NCBI_submission_ready,\n notes = curation.notes,\n )\n #form = forms.EditCurationForm(data)\n # add sites\n #populate_site_instances(form)\n kwargs = {'curation': curation}\n form = forms.EditCurationForm(data, **kwargs)\n return form\n","sub_path":"curate/validate_curation.py","file_name":"validate_curation.py","file_ext":"py","file_size_in_byte":6865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"67242663","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nIntakes the sequence or fasta string of a protein using the standard, single letter alphabet,\ngets the orthologs from an external (online) database, the OMA browser. It then generates a\nmultiple sequence alignment (MSA) using T-Coffee, and calculates the conservation score of each\namino acid at each position using Rate4Site, with respect to the entered sequence.\n\nCitations\nOMA database:\nAltenhoff A et al., The OMA orthology database in 2018: retrieving evolutionary relationships among\nall domains of life through richer web and programmatic interfaces Nucleic Acids Research, 2018,\n46 (D1): D477-D485 (doi:10.1093/nar/gkx1019).\n\nT-Coffee:\nT-Coffee: A novel method for multiple sequence alignments.\nNotredame,Higgins,Heringa,JMB,302(205-217)2000\n\nRate4Site:\nMayrose, I., Graur, D., Ben-Tal, N., and Pupko, T. 2004. Comparison of site-specific rate-inference methods:\nBayesian methods are superior. Mol Biol Evol 21: 1781-1791.\n\"\"\"\n\nimport oma\nimport aminoCons\nimport argparse\nimport os\n\nOLD_DIR = os.getcwd()\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"sequence\", help=\"Input the sequence of the protein of interest\")\nparser.add_argument(\"--hogs\", action=\"store_true\", help=\"When specified, the Hierarchical Orthologous Group (HOGs) of the sequence is returned\")\nparser.add_argument(\"--name\", default=\"Protein_sequence\", help=\"The name of the protein. All files generated will be based on this name\")\nparser.add_argument(\"--identity\", action=\"store_true\", help=\"The identity of the amino acid (Single letter code) at each position\")\nparser.add_argument(\"--score\", action=\"store_true\", help=\"The conservation scores. lower value = higher conservation\")\nparser.add_argument(\"--qqint\", action=\"store_true\", help=\"QQ-INTERVAL, the confidence interval for the rate estimates. The default interval is 25-75 percentiles\")\nparser.add_argument(\"--std\", action=\"store_true\", help=\"The standard deviation of the posterior rate distribution\")\nparser.add_argument(\"--gapped\", action=\"store_true\", help=\"MSA DATA, the number of aligned sequences having an amino acid (non-gapped) from the overall number of sequences at each position\")\nargs = parser.parse_args()\n\nwith open(args.sequence, 'r') as prot_file:\n prot_seq = prot_file.read()\n\nif args.hogs:\n seq2ortho = oma.OrthologFinder(prot_seq)\n orthologs = seq2ortho.get_HOGs()\nelse:\n seq2ortho = oma.OrthologFinder(prot_seq)\n orthologs = seq2ortho.get_orthologs()\n\nwith open(\"%s.txt\" %(args.name), 'w') as seq_file:\n seq_file.write(orthologs)\n\nalignment = aminoCons.build_alignment(os.getcwd() + os.sep + \"%s.txt\"%(args.name))\n\ncons_dict = aminoCons.Rate4Site(msa= (alignment + os.sep+ \"%s.aln\"%(args.name)), identity=args.identity,\n score=args.score, qqint=args.qqint,std=args.std, gapped=args.gapped)\ncons_dict = cons_dict.run()\n\n\nwith open(\"%s data\"%(args.name), 'w') as mat_file:\n output = str(cons_dict)\n mat_file.write(output)\n","sub_path":"ortho_to_cons_score.py","file_name":"ortho_to_cons_score.py","file_ext":"py","file_size_in_byte":2995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"298545689","text":"from flask import jsonify\n# from lin import route_meta, group_required, login_required\n# from lin.exception import Success\nfrom lin.redprint import Redprint\nfrom lin.util import paginate\n\nfrom app.models.article import Article\n\narticle_api = Redprint('article')\n\n\n@article_api.route('/', methods=['GET'])\ndef get_all():\n start, count = paginate()\n res = Article.get_all(start, count)\n for val in res:\n try:\n val.logo = \"https://qnhszm.obs.cn-north-1.myhuaweicloud.com/images/\" + val.logo.split('/')[-1]\n val.img1 = \"https://qnhszm.obs.cn-north-1.myhuaweicloud.com/images/\" + val.img1.split('/')[-1]\n val.img2 = \"https://qnhszm.obs.cn-north-1.myhuaweicloud.com/images/\" + val.img2.split('/')[-1]\n val.img3 = \"https://qnhszm.obs.cn-north-1.myhuaweicloud.com/images/\" + val.img3.split('/')[-1]\n val.img4 = \"https://qnhszm.obs.cn-north-1.myhuaweicloud.com/images/\" + val.img4.split('/')[-1]\n val.img5 = \"https://qnhszm.obs.cn-north-1.myhuaweicloud.com/images/\" + val.img5.split('/')[-1]\n except:\n continue\n return jsonify(res)\n\n\n@article_api.route('/', methods=['GET'])\ndef get_article(aid):\n res = Article.get_article(aid)\n return jsonify(res)\n","sub_path":"app/api/v1/article.py","file_name":"article.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"168279473","text":"# Python Tkinter Build A text Editor V - Undo Redo and Horizontal Scrollbar\n# Python Tkinter Build A editor de texto\n\nfrom tkinter import *\nfrom tkinter import filedialog\nfrom tkinter import font\n\nroot = Tk()\nroot.title('Python Tkinter Build A text Editor V')\nroot.iconbitmap('Python Tkinter Build A text Editor V/icons/document.ico')\nroot.geometry(\"1000x680\")\n\n# Set Variable for opne file name\nglobal open_status_name\nopen_status_name = False\n\nglobal selected\nselected = False\n\n# Create New File Function\ndef new_file():\n # Delete previos text\n my_text.delete(\"1.0\", END)\n # Update status bars\n root.title(\"New File - TextPad!\")\n status_bar.config(text=\"New File \")\n\n global open_status_name\n open_status_name = False\n\n# Open Files\ndef open_file():\n # Delete Precios Text\n my_text.delete(\"1.0\", END)\n\n # Grab Filename\n text_file = filedialog.askopenfilename(initialdir=\"Python Tkinter Build A text Editor V/documents/\", title=\"Open File\", filetypes=((\"Text Files\", \"*.txt\"), (\"HTML Files\", \"*.html\"), (\"Python Files\", \"*.py\"), (\"All Files\", \"*.*\")))\n \n # Check to see if there is a file name\n if text_file:\n # Make filename global so we can access it later\n global open_status_name\n open_status_name = text_file\n\n # Updaet status bars\n name = text_file\n status_bar.config(text=f'{name} ')\n name = name.replace(\"C:/Users/brian/Documents/Python-Course/Python Tkinter Build A text Editor V/documents/\", \"\")\n root.title(f'{name} - TextPad!')\n\n # Open the File\n text_file = open(text_file, 'r')\n stuff = text_file.read()\n\n # Close the opened file\n text_file.close()\n\n # Add File textbox\n my_text.insert(END, stuff)\n\n#Save as file\ndef save_as_file():\n text_file = filedialog.asksaveasfilename(defaultextension=\".*\", initialdir=\"C:/Users/brian/Documents/Python-Course/Python Tkinter Build A text Editor V/documents/\", title=\"Save File\", filetypes=((\"Text Files\", \"*.txt\"), (\"HTML Files\", \"*.html\"), (\"Python Files\", \"*.py\"), (\"All Files\", \"*.*\")))\n if text_file:\n # Updates Status Bars\n name = text_file\n status_bar.config(text=f'{name} ')\n name = name.replace(\"C:/Users/brian/Documents/Python-Course/Python Tkinter Build A text Editor V/documents/\", \"\")\n root.title(f'{name} - TextPad!')\n \n # Save File\n text_file = open(text_file, \"w\")\n text_file.write(my_text.get(1.0, END))\n #close the file\n text_file.close()\n\n# Save File\ndef save_file():\n global open_status_name\n if open_status_name:\n # Save File\n text_file = open(open_status_name, \"w\")\n text_file.write(my_text.get(1.0, END))\n #close the file\n text_file.close()\n # put status\n status_bar.config(text=f'{open_status_name} ')\n else:\n save_as_file()\n\n# cut Text\ndef cut_text(e):\n global selected\n \n if e:\n selected = root.clipboard_get()\n\n else:\n if my_text.selection_get():\n selected = my_text.selection_get()\n # Delected selected text from box\n my_text.delete(\"sel.first\", \"sel.last\")\n #clear the clipboard then append\n root.clipboard_clear()\n root.clipboard_append(selected)\n\n# copy Text\ndef copy_text(e):\n global selected\n #CHECK TO SEE IF WE USED KEYBOARD SHORTCUTS\n if e:\n selected = root.clipboard_get()\n\n if my_text.selection_get():\n # Grab selected text from text box\n selected = my_text.selection_get()\n root.clipboard_clear()\n root.clipboard_append(selected)\n\n# paste Text\ndef paste_text(e):\n global selected\n if e:\n selected = root.clipboard_get()\n else:\n if selected:\n position = my_text.index(INSERT)\n my_text.insert(position, selected)\n\n\n# Creare Main Frame\nmy_frame = Frame(root)\nmy_frame.pack(pady=5)\n\n# Create our Scrollbar For the Text Box\ntext_scroll = Scrollbar(my_frame)\ntext_scroll.pack(side=RIGHT, fill=Y)\n\n# Horizontal Scrollbar\nhor_scroll = Scrollbar(my_frame, orient='horizontal')\nhor_scroll.pack(side=BOTTOM, fill=X)\n\n# Create Text Box\nmy_text = Text(my_frame, width=97, height=25, font=(\"Helvetica\", 16), selectbackground=\"#4FDECD\", selectforeground=\"black\", undo=True, yscrollcommand=text_scroll.set, wrap=\"none\", xscrollcommand=hor_scroll.set)\nmy_text.pack()\n\n# Configure our Scroolbar\ntext_scroll.config(command=my_text.yview)\nhor_scroll.config(command=my_text.xview)\n\n# Create Menu\nmy_menu = Menu(root)\nroot.config(menu=my_menu)\n\n#A Add File Menu\nfile_menu = Menu(my_menu, tearoff=False)\nmy_menu.add_cascade(label=\"File\", menu=file_menu)\nfile_menu.add_command(label=\"New\", command=new_file)\nfile_menu.add_command(label=\"Open\", command=open_file)\nfile_menu.add_command(label=\"Save\", command=save_file)\nfile_menu.add_command(label=\"Save As\", command=save_as_file)\nfile_menu.add_separator()\nfile_menu.add_command(label=\"Exit\", command=root.quit)\n\n# Add Edit Menu\nedit_menu = Menu(my_menu, tearoff=False)\nmy_menu.add_cascade(label=\"Edit\", menu=edit_menu)\nedit_menu.add_command(label=\"Cut\", command=lambda: cut_text(False), accelerator=\"(Ctrl+x)\")\nedit_menu.add_command(label=\"Copy\", command=lambda: copy_text(False), accelerator=\"(Ctrl+c)\")\nedit_menu.add_command(label=\"Paste\", command=lambda: paste_text(False), accelerator=\"(Ctrl+v)\")\nedit_menu.add_separator()\nedit_menu.add_command(label=\"Undo\", command=my_text.edit_undo, accelerator=\"(Ctrl+z)\")\nedit_menu.add_command(label=\"Redo\", command=my_text.edit_redo, accelerator=\"(Ctrl+y)\")\n\n# Add Status Bar To Botton of App\nstatus_bar = Label(root, text=\"Ready \", anchor=E)\nstatus_bar.pack(fill=X, side=BOTTOM, ipady=15)\n\n# Edit Bindings\nroot.bind('', cut_text)\nroot.bind('', copy_text)\nroot.bind('', paste_text)\n\nroot.mainloop()\n","sub_path":"Python Tkinter Build A text Editor V/BuildTextEditorV.py","file_name":"BuildTextEditorV.py","file_ext":"py","file_size_in_byte":5873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"394026522","text":"from __future__ import print_function\nimport nltk\nimport random\nimport string\nimport numpy as np\nfrom time import time\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom sklearn.decomposition import NMF, LatentDirichletAllocation\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn import svm, preprocessing\nfrom nltk import word_tokenize,sent_tokenize\nfrom nltk.stem.porter import PorterStemmer\nfrom nltk.corpus import movie_reviews\nfrom nltk.tokenize import RegexpTokenizer\n\nfrom nmf_kl import KLdivNMF\nfrom rlx_nmf_kl import RlxKLdivNMF\n\n\n\nrandom.seed(0)\ntoken_dict = {}\n\ni=0\nfor category in movie_reviews.categories():\n\tfor fileid in movie_reviews.fileids(category):\n\t\ttoken_dict[i] = movie_reviews.raw(fileid)\n\t\ti = i+1\n\ndef stem_tokens(tokens, stemmer):\n stemmed = []\n for item in tokens:\n stemmed.append(stemmer.stem(item))\n return stemmed\n\ndef tokenize(text):\n\ttokenizer = RegexpTokenizer(r'\\w+')\n\ttokens = tokenizer.tokenize(text)\n\t#stems = stem_tokens(tokens, stemmer)\n\treturn tokens\n\ndef print_top_words(model, feature_names, n_top_words):\n for topic_idx, topic in enumerate(model.components_):\n print(\"Topic #%d:\" % topic_idx)\n print(\" \".join([feature_names[i]\n for i in topic.argsort()[:-n_top_words - 1:-1]]))\n print()\n\n#print token_dict.values()\n\nn_features = 5000\nn_topics = 80\nn_top_words = 20\nmax_iter = 300\n\n\ncountvec = CountVectorizer(tokenizer=tokenize)\nraw_tdmatrix = countvec.fit_transform(token_dict.values())\nraw_vocab = countvec.vocabulary_\nfeature_names = countvec.get_feature_names()\n\nsorted_idx = raw_tdmatrix.sum(0).argsort().tolist()[0]\nvocab_idx = sorted_idx[-5050:-50]\n\nvocab = []\nfor idx in vocab_idx:\n\tvocab.append(feature_names[idx])\n\ncountvec = CountVectorizer(tokenizer=tokenize, vocabulary=vocab)\ntdmatrix = countvec.fit_transform(token_dict.values())\nfeature_names = countvec.get_feature_names()\n\n# Fit the Relaxed NMF model\nprint(\"Fitting the Relaxed NMF model\")\nt0 = time()\nrlx_nmf = RlxKLdivNMF(n_components=n_topics, random_state=1, max_iter=max_iter, init='random', rho=500.0)\nrlx_nmf.fit(tdmatrix)\nprint(\"done in %0.3fs.\" % (time() - t0))\n#print(\"\\nTopics in L2-NMF model:\")\n#print_top_words(rlx_nmf, feature_names, n_top_words)\n\n\n# Fit the L2-NMF model\nprint(\"Fitting the L2-NMF model\")\nt0 = time()\nnmf = NMF(n_components=n_topics, random_state=1, max_iter=max_iter, init='nndsvd', solver='cd')\nnmf.fit(tdmatrix)\nprint(\"done in %0.3fs.\" % (time() - t0))\n#print(\"\\nTopics in L2-NMF model:\")\n#print_top_words(nmf, feature_names, n_top_words)\n\n# Fit the NMF model\nprint(\"Fitting the KL-NMF model\")\nt0 = time()\nkl_nmf = KLdivNMF(n_components=n_topics, random_state=1, max_iter=max_iter, init='nndsvd')\nkl_nmf.fit(tdmatrix)\nprint(\"done in %0.3fs.\" % (time() - t0))\n#print(\"\\nTopics in KL-NMF model:\")\n#print_top_words(nmf, feature_names, n_top_words)\n\n# Fit the LDA model\nt0 = time()\nprint(\"Fitting LDA models\")\nlda = LatentDirichletAllocation(n_topics=n_topics, max_iter=max_iter,\n learning_method='batch', n_jobs=1,\n evaluate_every=5, random_state=0)\nlda.fit(tdmatrix)\nprint(\"done in %0.3fs.\" % (time() - t0))\n\n#print(\"\\nTopics in LDA model:\")\n#print_top_words(lda, feature_names, n_top_words)\n\n\n# extract features\npermute = random.sample(range(2000), 2000)\nlabels = np.ones(2000)\nlabels[1000:] = -1\nraw_rlx_nmf_features = rlx_nmf.transform(tdmatrix)\nraw_nmf_features = nmf.transform(tdmatrix)\nraw_kl_nmf_features = kl_nmf.transform(tdmatrix)\nraw_lda_features = lda.transform(tdmatrix)\n\n# scale the raw features\nmin_max_scaler = preprocessing.MinMaxScaler()\n\nlabels = labels[permute];\nrlx_nmf_features = min_max_scaler.fit_transform(raw_rlx_nmf_features[permute])\nnmf_features = min_max_scaler.fit_transform(raw_nmf_features[permute])\nkl_nmf_features = min_max_scaler.fit_transform(raw_kl_nmf_features[permute])\nlda_features = raw_lda_features[permute]\n\n# train svms on scaled features\nprint(\"10-fold cross-validation acc of Relaxed NMF:\")\nclf = svm.SVC(kernel='linear', C=1)\nscores = cross_val_score(clf, rlx_nmf_features, labels, cv=10)\nprint(np.mean(scores))\n\nprint(\"10-fold cross-validation acc of L2-NMF:\")\nclf = svm.SVC(kernel='linear', C=1)\nscores = cross_val_score(clf, nmf_features, labels, cv=10)\nprint(np.mean(scores))\n\nprint(\"10-fold cross-validation acc of KL-NMF:\")\nclf = svm.SVC(kernel='linear', C=1)\nscores = cross_val_score(clf, kl_nmf_features, labels, cv=10)\nprint(np.mean(scores))\n\nprint(\"10-fold cross-validation acc of LDA:\")\nclf = svm.SVC(kernel='linear', C=1)\nscores = cross_val_score(clf, lda_features, labels, cv=10)\nprint(np.mean(scores))\n\n","sub_path":"non-negative-matrix-factorization/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"454027330","text":"\n# ##### BEGIN GPL LICENSE BLOCK #####\n#\n# This program is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the Free\n# Software Foundation; either version 2 of the License, or (at your option)\n# any later version.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for\n# more details.\n#\n# You should have received a copy of the GNU General Public License along with\n# this program; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n# ##### END GPL LICENSE BLOCK #####\n\n# imports\nimport bpy\nfrom bpy.types import PropertyGroup\nfrom bpy.props import EnumProperty, BoolProperty, StringProperty, IntProperty\n\n###########\n## LISTS ##\n###########\n\n# list\nclass menuList:\n '''\n Contains Lists;\n objects\n modifiers\n constraints\n '''\n # object\n objects = [\n ('ALL', 'All Objects', '', 'OBJECT_DATA', 0),\n ('MESH', 'Mesh', '', 'OUTLINER_OB_MESH', 1),\n ('CURVE', 'Curve', '', 'OUTLINER_OB_CURVE', 2),\n ('SURFACE', 'Surface', '', 'OUTLINER_OB_SURFACE', 3),\n ('META', 'Meta', '', 'OUTLINER_OB_META', 4),\n ('FONT', 'Text', '', 'OUTLINER_OB_FONT', 5),\n ('ARMATURE', 'Armature', '', 'OUTLINER_OB_ARMATURE', 6),\n ('LATTICE', 'Lattice', '', 'OUTLINER_OB_LATTICE', 7),\n ('EMPTY', 'Empty', '', 'OUTLINER_OB_EMPTY', 8),\n ('SPEAKER', 'Speaker', '', 'OUTLINER_OB_SPEAKER', 9),\n ('CAMERA', 'Camera', '', 'OUTLINER_OB_CAMERA', 10),\n ('LAMP', 'Lamp', '', 'OUTLINER_OB_LAMP', 11)\n ]\n\n # constraint\n constraints = [\n ('ALL', 'All Constraints', '', 'CONSTRAINT', 0),\n\n # motion tracking\n ('CAMERA_SOLVER', 'Camera Solver', '', 'CONSTRAINT_DATA', 1),\n ('FOLLOW_TRACK', 'Follow Track', '', 'CONSTRAINT_DATA', 2),\n ('OBJECT_SOLVER', 'Object Solver', '', 'CONSTRAINT_DATA', 3),\n\n # transform\n ('COPY_LOCATION', 'Copy Location', '', 'CONSTRAINT_DATA', 4),\n ('COPY_ROTATION', 'Copy Rotation', '', 'CONSTRAINT_DATA', 5),\n ('COPY_SCALE', 'Copy Scale', '', 'CONSTRAINT_DATA', 6),\n ('COPY_TRANSFORMS', 'Copy Transforms', '', 'CONSTRAINT_DATA', 7),\n ('LIMIT_DISTANCE', 'Limit Distance', '', 'CONSTRAINT_DATA', 8),\n ('LIMIT_LOCATION', 'Limit Location', '', 'CONSTRAINT_DATA', 9),\n ('LIMIT_ROTATION', 'Limit Rotation', '', 'CONSTRAINT_DATA', 10),\n ('LIMIT_SCALE', 'Limit Scale', '', 'CONSTRAINT_DATA', 11),\n ('MAINTAIN_VOLUME', 'Maintain Volume', '', 'CONSTRAINT_DATA', 12),\n ('TRANSFORM', 'Transformation', '', 'CONSTRAINT_DATA', 13),\n\n # tracking\n ('CLAMP_TO', 'Clamp To', '', 'CONSTRAINT_DATA', 14),\n ('DAMPED_TRACK', 'Damped Track', '', 'CONSTRAINT_DATA', 15),\n ('IK', 'Inverse Kinematics', '', 'CONSTRAINT_DATA', 16),\n ('LOCKED_TRACK', 'Locked Track', '', 'CONSTRAINT_DATA', 17),\n ('SPLINE_IK', 'Spline IK', '', 'CONSTRAINT_DATA', 18),\n ('STRETCH_TO', 'Stretch To', '', 'CONSTRAINT_DATA', 19),\n ('TRACK_TO', 'Track To', '', 'CONSTRAINT_DATA', 20),\n\n # relationship\n ('ACTION', 'Action', '', 'CONSTRAINT_DATA', 21),\n ('CHILD_OF', 'Child Of', '', 'CONSTRAINT_DATA', 22),\n ('FLOOR', 'Floor', '', 'CONSTRAINT_DATA', 23),\n ('FOLLOW_PATH', 'Follow Path', '', 'CONSTRAINT_DATA', 24),\n ('PIVOT', 'Pivot', '', 'CONSTRAINT_DATA', 25),\n ('RIGID_BODY_JOINT', 'Rigid Body Joint', '', 'CONSTRAINT_DATA', 26),\n ('SHRINKWRAP', 'Shrinkwrap', '', 'CONSTRAINT_DATA', 27)\n ]\n\n # modifier\n modifiers = [\n ('ALL', 'All Modifiers', '', 'MODIFIER', 0),\n\n # modify\n ('DATA_TRANSFER', 'Data Transfer', '', 'MOD_DATA_TRANSFER', 1),\n ('MESH_CACHE', 'Mesh Cache', '', 'MOD_MESHDEFORM', 2),\n ('NORMAL_EDIT', 'Normal Edit', '', 'MOD_NORMALEDIT', 3),\n ('UV_PROJECT', 'UV Project', '', 'MOD_UVPROJECT', 4),\n ('UV_WARP', 'UV Warp', '', 'MOD_UVPROJECT', 5),\n ('VERTEX_WEIGHT_EDIT', 'Vertex Weight Edit', '', 'MOD_VERTEX_WEIGHT', 6),\n ('VERTEX_WEIGHT_MIX', 'Vertex Weight Mix', '', 'MOD_VERTEX_WEIGHT', 7),\n ('VERTEX_WEIGHT_PROXIMITY', 'Vertex Weight Proximity', '', 'MOD_VERTEX_WEIGHT', 8),\n\n # generate\n ('ARRAY', 'Array', '', 'MOD_ARRAY', 9),\n ('BEVEL', 'Bevel', '', 'MOD_BEVEL', 10),\n ('BOOLEAN', 'Boolean', '', 'MOD_BOOLEAN', 11),\n ('BUILD', 'Build', '', 'MOD_BUILD', 12),\n ('DECIMATE', 'Decimate', '', 'MOD_DECIM', 13),\n ('EDGE_SPLIT', 'Edge Split', '', 'MOD_EDGESPLIT', 14),\n ('MASK', 'Mask', '', 'MOD_MASK', 15),\n ('MIRROR', 'Mirror', '', 'MOD_MIRROR', 16),\n ('MULTIRES', 'Multiresolution', '', 'MOD_MULTIRES', 17),\n ('REMESH', 'Remesh', '', 'MOD_REMESH', 18),\n ('SCREW', 'Screw', '', 'MOD_SCREW', 19),\n ('SKIN', 'Skin', '', 'MOD_SKIN', 20),\n ('SOLIDIFY', 'Solidify', '', 'MOD_SOLIDIFY', 21),\n ('SUBSURF', 'Subdivision Surface', '', 'MOD_SUBSURF', 22),\n ('TRIANGULATE', 'Triangulate', '', 'MOD_TRIANGULATE', 23),\n ('WIREFRAME', 'Wireframe', '', 'MOD_WIREFRAME', 24),\n\n # deform\n ('ARMATURE', 'Armature', '', 'MOD_ARMATURE', 25),\n ('CAST', 'Cast', '', 'MOD_CAST', 26),\n ('CORRECTIVE_SMOOTH', 'Corrective Smooth', '', 'MOD_SMOOTH', 27),\n ('CURVE', 'Curve', '', 'MOD_CURVE', 28),\n ('DISPLACE', 'Displace', '', 'MOD_DISPLACE', 29),\n ('HOOK', 'Hook', '', 'HOOK', 30),\n ('LAPLACIANSMOOTH', 'Laplacian Smooth', '', 'MOD_SMOOTH', 31),\n ('LAPLACIANDEFORM', 'Laplacian Deform', '', 'MOD_MESHDEFORM', 32),\n ('LATTICE', 'Lattice', '', 'MOD_LATTICE', 33),\n ('MESH_DEFORM', 'Mesh Deform', '', 'MOD_MESHDEFORM', 34),\n ('SHRINKWRAP', 'Shrinkwrap', '', 'MOD_SHRINKWRAP', 35),\n ('SIMPLE_DEFORM', 'Simple Deform', '', 'MOD_SIMPLEDEFORM', 36),\n ('SMOOTH', 'Smooth', '', 'MOD_SMOOTH', 37),\n ('WARP', 'Warp', '', 'MOD_WARP', 38),\n ('WAVE', 'Wave', '', 'MOD_WAVE', 39),\n\n # simulate\n ('CLOTH', 'Cloth', '', 'MOD_CLOTH', 40),\n ('COLLISION', 'Collision', '', 'MOD_PHYSICS', 41),\n ('DYNAMIC_PAINT', 'Dynamic Paint', '', 'MOD_DYNAMICPAINT', 42),\n ('EXPLODE', 'Explode', '', 'MOD_EXPLODE', 43),\n ('FLUID_SIMULATION', 'Fluid Simulation', '', 'MOD_FLUIDSIM', 44),\n ('OCEAN', 'Ocean', '', 'MOD_OCEAN', 45),\n ('PARTICLE_INSTANCE', 'Particle Instance', '', 'MOD_PARTICLES', 46),\n ('PARTICLE_SYSTEM', 'Particle System', '', 'MOD_PARTICLES', 47),\n ('SMOKE', 'Smoke', '', 'MOD_SMOKE', 48),\n ('SOFT_BODY', 'Soft Body', '', 'MOD_SOFT', 49)\n ]\n\n#####################\n## PROPERTY GROUPS ##\n#####################\n\n# panel\nclass panel(PropertyGroup):\n '''\n Properties that effect how item panel displays the datablocks within the users current selection.\n '''\n\n # filters\n filters = BoolProperty(\n name = 'Filters',\n description = 'Show options for whether datablock names are displayed.',\n default = False\n )\n\n # options\n options = BoolProperty(\n name = 'Options',\n description = 'Show shortcut options next to datablock names.',\n default = False\n )\n\n # selected\n selected = BoolProperty(\n name = 'Selected',\n description = 'Display all possible object related datablock names within your current selection inside the item panel.',\n default = False\n )\n\n # groups\n groups = BoolProperty(\n name = 'Groups',\n description = 'Display group name.',\n default = False\n )\n\n # action\n action = BoolProperty(\n name = 'Action',\n description = 'Display action name.',\n default = False\n )\n\n # grease pencil\n greasePencil = BoolProperty(\n name = 'Grease Pencil',\n description = 'Display grease pencil and layer names',\n default = False\n )\n\n # constraints\n constraints = BoolProperty(\n name = 'Constraints',\n description = 'Display constraint names.',\n default = False\n )\n\n # modifiers\n modifiers = BoolProperty(\n name = 'Modifiers',\n description = 'Display modifier names.',\n default = False\n )\n\n # bone groups\n boneGroups = BoolProperty(\n name = 'Bone Groups',\n description = 'Display bone group names.',\n default = False\n )\n\n # bone constraints\n boneConstraints = BoolProperty(\n name = 'Bone Constraints',\n description = 'Display bone constraint names.',\n default = False\n )\n\n # vertex groups\n vertexGroups = BoolProperty(\n name = 'Vertex Groups',\n description = 'Display vertex group names.',\n default = False\n )\n\n # shapekeys\n shapekeys = BoolProperty(\n name = 'Shapekeys',\n description = 'Display shapekey names.',\n default = False\n )\n\n # uvs\n uvs = BoolProperty(\n name = 'UV\\'s',\n description = 'Display uv names.',\n default = False\n )\n\n # vertex color\n vertexColors = BoolProperty(\n name = 'Vertex Colors',\n description = 'Display vertex color names.',\n default = False\n )\n\n # materials\n materials = BoolProperty(\n name = 'Materials',\n description = 'Display material names.',\n default = False\n )\n\n # textures\n textures = BoolProperty(\n name = 'Textures.',\n description = 'Display material texture names.',\n default = False\n )\n\n # particle systems\n particleSystems = BoolProperty(\n name = 'Particle Systems',\n description = 'Display the particle system and setting names. (Modifier filter must be active)',\n default = False\n )\n\n # selected bones\n selectedBones = BoolProperty(\n name = 'Selected',\n description = 'Display selected bone names.',\n default = False\n )\n\nclass batch:\n '''\n Contains Classes;\n auto\n name (PropertyGroup)\n copy (PropertyGroup)\n '''\n # auto\n class auto:\n '''\n Contains Classes;\n name (PropertyGroup)\n objects (PropertyGroup)\n constraints (PropertyGroup)\n modifiers (PropertyGroup)\n objectData (PropertyGroup)\n '''\n # options\n class name(PropertyGroup):\n '''\n Main properties that effect how the batch auto name operator is performed.\n '''\n\n # batch type\n batchType = EnumProperty(\n name = 'Batch Type',\n description = '',\n items = [\n ('SELECTED', 'Selected', 'Batch auto name will only effect the object related datablock names within the current selection.'),\n ('OBJECTS', 'All Objects', 'Batch auto name will effect all object related datablock names in the file.')\n ],\n default = 'SELECTED'\n )\n\n # objects\n objects = BoolProperty(\n name = 'Objects',\n description = 'Name objects.',\n default = False\n )\n\n # constraints\n constraints = BoolProperty(\n name = 'Constraints',\n description = 'Name constraints.',\n default = False\n )\n\n # modifiers\n modifiers = BoolProperty(\n name = 'Modifiers',\n description = 'Name modifiers.',\n default = False\n )\n\n # objectData\n objectData = BoolProperty(\n name = 'Object Data',\n description = 'Name object data.',\n default = False\n )\n\n # bone Constraints\n boneConstraints = BoolProperty(\n name = 'Bone Constraints',\n description = 'Name bone constraints.'\n )\n\n # object type\n objectType = EnumProperty(\n name = 'Object Type',\n description = 'Type of objects to be effected.',\n items = menuList.objects,\n default = 'ALL'\n )\n\n # constraint type\n constraintType = EnumProperty(\n name = 'Constraint Type',\n description = 'Type of constraints to be effected.',\n items = menuList.constraints,\n default = 'ALL'\n )\n\n # modifier type\n modifierType = EnumProperty(\n name = 'Modifier Type',\n description = 'Type of modifiers to be effected.',\n items = menuList.modifiers,\n default = 'ALL'\n )\n\n # object\n class objects(PropertyGroup):\n '''\n Properties that effect the names used when auto naming objects.\n '''\n # mesh\n mesh = StringProperty(\n name = 'Mesh',\n description = 'Name used for mesh objects.',\n default = 'Mesh'\n )\n\n # curve\n curve = StringProperty(\n name = 'Curve',\n description = 'Name used for curve objects.',\n default = 'Curve'\n )\n\n # surface\n surface = StringProperty(\n name = 'Surface',\n description = 'Name used for surface objects.',\n default = 'Surface'\n )\n\n # meta\n meta = StringProperty(\n name = 'Meta',\n description = 'Name used for meta objects.',\n default = 'Meta'\n )\n\n # font\n font = StringProperty(\n name = 'Text',\n description = 'Name used for font objects.',\n default = 'Text'\n )\n\n # armature\n armature = StringProperty(\n name = 'Armature',\n description = 'Name used for armature objects.',\n default = 'Armature'\n )\n\n # lattice\n lattice = StringProperty(\n name = 'Lattice',\n description = 'Name used for lattice objects.',\n default = 'Lattice'\n )\n\n # empty\n empty = StringProperty(\n name = 'Empty',\n description = 'Name used for empty objects.',\n default = 'Empty'\n )\n\n # speaker\n speaker = StringProperty(\n name = 'Speaker',\n description = 'Name used for speaker objects.',\n default = 'Speaker'\n )\n\n # camera\n camera = StringProperty(\n name = 'Camera',\n description = 'Name used for camera objects.',\n default = 'Camera'\n )\n\n # lamp\n lamp = StringProperty(\n name = 'Lamp',\n description = 'Name used for lamp objects.',\n default = 'Lamp'\n )\n\n # constraint\n class constraints(PropertyGroup):\n '''\n Properties that effect the names used when auto naming constraints.\n '''\n\n # camera solver\n cameraSolver = StringProperty(\n name = 'Camera Solver',\n description = 'Name used for camera solver constraints.',\n default = 'Camera Solver'\n )\n\n # follow track\n followTrack = StringProperty(\n name = 'Follow Track',\n description = 'Name used for follow track constraints.',\n default = 'Follow Track'\n )\n\n # object solver\n objectSolver = StringProperty(\n name = 'Object Solver',\n description = 'Name used for object solver constraints.',\n default = 'Object Solver'\n )\n\n # copy location\n copyLocation = StringProperty(\n name = 'Copy Location',\n description = 'Name used for copy location constraints.',\n default = 'Copy Location'\n )\n\n # copy rotation\n copyRotation = StringProperty(\n name = 'Copy Rotation',\n description = 'Name used for copy rotation constraints.',\n default = 'Copy Rotation'\n )\n\n # copy scale\n copyScale = StringProperty(\n name = 'Copy Scale',\n description = 'Name used for copy scale constraints.',\n default = 'Copy Scale'\n )\n\n # copy transforms\n copyTransforms = StringProperty(\n name = 'Copy Transforms',\n description = 'Name used for copy transforms constraints.',\n default = 'Copy Transforms'\n )\n\n # limit distance\n limitDistance = StringProperty(\n name = 'Limit Distance',\n description = 'Name used for limit distance constraints.',\n default = 'Limit Distance'\n )\n\n # limit location\n limitLocation = StringProperty(\n name = 'Limit Location',\n description = 'Name used for limit location constraints.',\n default = 'Limit Location'\n )\n\n # limit rotation\n limitRotation = StringProperty(\n name = 'Limit Rotation',\n description = 'Name used for limit rotation constraints.',\n default = 'Limit Rotation'\n )\n\n # limit scale\n limitScale = StringProperty(\n name = 'Limit Scale',\n description = 'Name used for limit scale constraints.',\n default = 'Limit Scale'\n )\n\n # maintain volume\n maintainVolume = StringProperty(\n name = 'Maintain Volume',\n description = 'Name used for maintain volume constraints.',\n default = 'Maintain Volume'\n )\n\n # transform\n transform = StringProperty(\n name = 'Transform',\n description = 'Name used for transform constraints.',\n default = 'Transform'\n )\n\n # clamp to\n clampTo = StringProperty(\n name = 'Clamp To',\n description = 'Name used for clamp to constraints.',\n default = 'Clamp To'\n )\n\n # damped track\n dampedTrack = StringProperty(\n name = 'Damped Track',\n description = 'Name used for damped track constraints.',\n default = 'Damped Track'\n )\n\n # inverse kinematics\n inverseKinematics = StringProperty(\n name = 'Inverse Kinematics',\n description = 'Name used for inverse kinematics constraints.',\n default = 'Inverse Kinematics'\n )\n\n # locked track\n lockedTrack = StringProperty(\n name = 'Locked Track',\n description = 'Name used for locked track constraints.',\n default = 'Locked Track'\n )\n\n # spline inverse kinematics\n splineInverseKinematics = StringProperty(\n name = 'Spline Inverse Kinematics',\n description = 'Name used for spline inverse kinematics constraints.',\n default = 'Spline Inverse Kinematics'\n )\n\n # stretch to\n stretchTo = StringProperty(\n name = 'Stretch To',\n description = 'Name used for stretch to constraints.',\n default = 'Stretch To'\n )\n\n # track to\n trackTo = StringProperty(\n name = 'Track To',\n description = 'Name used for track to constraints.',\n default = 'Track To'\n )\n\n # action\n action = StringProperty(\n name = 'Action',\n description = 'Name used for action constraints.',\n default = 'Action'\n )\n\n # child of\n childOf = StringProperty(\n name = 'Child Of',\n description = 'Name used for child of constraints.',\n default = 'Child Of'\n )\n\n # floor\n floor = StringProperty(\n name = 'Floor',\n description = 'Name used for floor constraints.',\n default = 'Floor'\n )\n\n # follow path\n followPath = StringProperty(\n name = 'Follow Path',\n description = 'Name used for follow path constraints.',\n default = 'Follow Path'\n )\n\n # pivot\n pivot = StringProperty(\n name = 'Pivot',\n description = 'Name used for pivot constraints.',\n default = 'Pivot'\n )\n\n # rigid body joint\n rigidBodyJoint = StringProperty(\n name = 'Rigid Body Joint',\n description = 'Name used for rigid body joint constraints.',\n default = 'Rigid Body Joint'\n )\n\n # shrinkwrap\n shrinkwrap = StringProperty(\n name = 'Shrinkwrap',\n description = 'Name used for shrinkwrap constraints.',\n default = 'Shrinkwrap'\n )\n\n # modifier\n class modifiers(PropertyGroup):\n '''\n Properties that effect the names used when auto naming modifiers.\n '''\n # data transfer\n dataTransfer = StringProperty(\n name = 'Data Transfer',\n description = 'Name used for data transfer modifiers.',\n default = 'Data Transfer'\n )\n\n # mesh cache\n meshCache = StringProperty(\n name = 'Mesh Cache',\n description = 'Name used for mesh cache modifiers.',\n default = 'Mesh Cache'\n )\n\n # normal edit\n normalEdit = StringProperty(\n name = 'Normal Edit',\n description = 'Name used for normal edit modifiers.',\n default = 'Normal Edit'\n )\n\n # uv project\n uvProject = StringProperty(\n name = 'UV Project',\n description = 'Name used for uv project modifiers.',\n default = 'UV Project'\n )\n\n # uv warp\n uvWarp = StringProperty(\n name = 'UV Warp',\n description = 'Name used for uv warp modifiers.',\n default = 'UV Warp'\n )\n\n # vertex weight edit\n vertexWeightEdit = StringProperty(\n name = 'Vertex Weight Edit',\n description = 'Name used for vertex weight edit modifiers.',\n default = 'Vertex Weight Edit'\n )\n\n # vertex weight mix\n vertexWeightMix = StringProperty(\n name = 'Vertex Weight Mix',\n description = 'Name used for vertex weight mix modifiers.',\n default = 'Vertex Weight Mix'\n )\n\n # vertex weight proximity\n vertexWeightProximity = StringProperty(\n name = 'Vertex Weight Proximity',\n description = 'Name used for vertex weight proximity modifiers.',\n default = 'Vertex Weight Proximity'\n )\n\n # array\n array = StringProperty(\n name = 'Array',\n description = 'Name used for array modifiers.',\n default = 'Array'\n )\n\n # bevel\n bevel = StringProperty(\n name = 'Bevel',\n description = 'Name used for bevel modifiers.',\n default = 'Bevel'\n )\n\n # boolean\n boolean = StringProperty(\n name = 'Boolean',\n description = 'Name used for boolean modifiers.',\n default = 'Boolean'\n )\n\n # build\n build = StringProperty(\n name = 'Build',\n description = 'Name used for build modifiers.',\n default = 'Build'\n )\n\n # decimate\n decimate = StringProperty(\n name = 'Decimate',\n description = 'Name used for decimate modifiers.',\n default = 'Decimate'\n )\n\n # edge split\n edgeSplit = StringProperty(\n name = 'Edge Split',\n description = 'Name used for edge split modifiers.',\n default = 'Edge Split'\n )\n\n # mask\n mask = StringProperty(\n name = 'Mask',\n description = 'Name used for mask modifiers.',\n default = 'Mask'\n )\n\n # mirror\n mirror = StringProperty(\n name = 'Mirror',\n description = 'Name used for mirror modifiers.',\n default = 'Mirror'\n )\n\n # multiresolution\n multiresolution = StringProperty(\n name = 'Multiresolution',\n description = 'Name used for multiresolution modifiers.',\n default = 'Multiresolution'\n )\n\n # remesh\n remesh = StringProperty(\n name = 'Remesh',\n description = 'Name used for remesh modifiers.',\n default = 'Remesh'\n )\n\n # screw\n screw = StringProperty(\n name = 'Screw',\n description = 'Name used for screw modifiers.',\n default = 'Screw'\n )\n\n # skin\n skin = StringProperty(\n name = 'Skin',\n description = 'Name used for skin modifiers.',\n default = 'Skin'\n )\n\n # solidify\n solidify = StringProperty(\n name = 'Solidify',\n description = 'Name used for solidify modifiers.',\n default = 'Solidify'\n )\n\n # subdivision surface\n subdivisionSurface = StringProperty(\n name = 'Subdivision Surface',\n description = 'Name used for subdivision surface modifiers.',\n default = 'Subdivision Surface'\n )\n\n # triangulate\n triangulate = StringProperty(\n name = 'Triangulate',\n description = 'Name used for triangulate modifiers.',\n default = 'Triangulate'\n )\n\n # wireframe\n wireframe = StringProperty(\n name = 'Wireframe',\n description = 'Name used for wireframe modifiers.',\n default = 'Wireframe'\n )\n\n # armature\n armature = StringProperty(\n name = 'Armature',\n description = 'Name used for armature modifiers.',\n default = 'Armature'\n )\n\n # cast\n cast = StringProperty(\n name = 'Cast',\n description = 'Name used for cast modifiers.',\n default = 'Cast'\n )\n\n # corrective smooth\n correctiveSmooth = StringProperty(\n name = 'Corrective Smooth',\n description = 'Name used for corrective smooth modifiers.',\n default = 'Corrective Smooth'\n )\n\n # curve\n curve = StringProperty(\n name = 'Curve',\n description = 'Name used for curve modifiers.',\n default = 'Curve'\n )\n\n # displace\n displace = StringProperty(\n name = 'Displace',\n description = 'Name used for displace modifiers.',\n default = 'Displace'\n )\n\n # hook\n hook = StringProperty(\n name = 'Hook',\n description = 'Name used for hook modifiers.',\n default = 'Hook'\n )\n\n # laplacian smooth\n laplacianSmooth = StringProperty(\n name = 'Laplacian Smooth',\n description = 'Name used for laplacian smooth modifiers.',\n default = 'Laplacian Smooth'\n )\n\n # laplacian deform\n laplacianDeform = StringProperty(\n name = 'Laplacian Deform',\n description = 'Name used for laplacian deform modifiers.',\n default = 'Laplacian Deform'\n )\n\n # lattice\n lattice = StringProperty(\n name = 'Lattice',\n description = 'Name used for lattice modifiers.',\n default = 'Lattice'\n )\n\n # mesh deform\n meshDeform = StringProperty(\n name = 'Mesh Deform',\n description = 'Name used for mesh deform modifiers.',\n default = 'Mesh Deform'\n )\n\n # shrinkwrap\n shrinkwrap = StringProperty(\n name = 'Shrinkwrap',\n description = 'Name used for shrinkwrap modifiers.',\n default = 'Shrinkwrap'\n )\n\n # simple deform\n simpleDeform = StringProperty(\n name = 'Simple Deform',\n description = 'Name used for simple deform modifiers.',\n default = 'Simple Deform'\n )\n\n # smooth\n smooth = StringProperty(\n name = 'Smooth',\n description = 'Name used for smooth modifiers.',\n default = 'Smooth'\n )\n\n # warp\n warp = StringProperty(\n name = 'Warp',\n description = 'Name used for warp modifiers.',\n default = 'Warp'\n )\n\n # wave\n wave = StringProperty(\n name = 'Wave',\n description = 'Name used for wave modifiers.',\n default = 'Wave'\n )\n\n # cloth\n cloth = StringProperty(\n name = 'Cloth',\n description = 'Name used for cloth modifiers.',\n default = 'Cloth'\n )\n\n # collision\n collision = StringProperty(\n name = 'Collision',\n description = 'Name used for collision modifiers.',\n default = 'Collision'\n )\n\n # dynamic paint\n dynamicPaint = StringProperty(\n name = 'Dynamic Paint',\n description = 'Name used for dynamic paint modifiers.',\n default = 'Dynamic Paint'\n )\n\n # explode\n explode = StringProperty(\n name = 'Explode',\n description = 'Name used for explode modifiers.',\n default = 'Explode'\n )\n\n # fluid simulation\n fluidSimulation = StringProperty(\n name = 'Fluid Simulation',\n description = 'Name used for fluid simulation modifiers.',\n default = 'Fluid Simulation'\n )\n\n # ocean\n ocean = StringProperty(\n name = 'Ocean',\n description = 'Name used for ocean modifiers.',\n default = 'Ocean'\n )\n\n # particle instance\n particleInstance = StringProperty(\n name = 'Particle Instance',\n description = 'Name used for particle instance modifiers.',\n default = 'Particle Instance'\n )\n\n # particle system\n particleSystem = StringProperty(\n name = 'Particle System',\n description = 'Name used for particle system modifiers.',\n default = 'Particle System'\n )\n\n # smoke\n smoke = StringProperty(\n name = 'Smoke',\n description = 'Name used for smoke modifiers.',\n default = 'Smoke'\n )\n\n # soft body\n softBody = StringProperty(\n name = 'Soft Body',\n description = 'Name used for soft body modifiers.',\n default = 'Soft Body'\n )\n\n # object data\n class objectData(PropertyGroup):\n '''\n Properties that effect the names used when auto naming objects.\n '''\n # mesh\n mesh = StringProperty(\n name = 'Mesh',\n description = 'Name used for mesh objects.',\n default = 'Mesh'\n )\n\n # curve\n curve = StringProperty(\n name = 'Curve',\n description = 'Name used for curve objects.',\n default = 'Curve'\n )\n\n # surface\n surface = StringProperty(\n name = 'Surface',\n description = 'Name used for surface objects.',\n default = 'Surface'\n )\n\n # meta\n meta = StringProperty(\n name = 'Meta',\n description = 'Name used for meta objects.',\n default = 'Meta'\n )\n\n # font\n font = StringProperty(\n name = 'Text',\n description = 'Name used for font objects.',\n default = 'Text'\n )\n\n # armature\n armature = StringProperty(\n name = 'Armature',\n description = 'Name used for armature objects.',\n default = 'Armature'\n )\n\n # lattice\n lattice = StringProperty(\n name = 'Lattice',\n description = 'Name used for lattice objects.',\n default = 'Lattice'\n )\n\n # empty\n empty = StringProperty(\n name = 'Empty',\n description = 'Name used for empty objects.',\n default = 'Empty'\n )\n\n # speaker\n speaker = StringProperty(\n name = 'Speaker',\n description = 'Name used for speaker objects.',\n default = 'Speaker'\n )\n\n # camera\n camera = StringProperty(\n name = 'Camera',\n description = 'Name used for camera objects.',\n default = 'Camera'\n )\n\n # lamp\n lamp = StringProperty(\n name = 'Lamp',\n description = 'Name used for lamp objects.',\n default = 'Lamp'\n )\n\n # name\n class name(PropertyGroup):\n '''\n Properties that effect how the batch name operation is performed.\n '''\n\n # tag\n tag = BoolProperty(\n name = 'Tag',\n description = 'Used by batch name internally. (keep it off)',\n default = False\n )\n\n # batch type\n batchType = EnumProperty(\n name = 'Batch Type',\n description = '',\n items = [\n ('SELECTED', 'Selected', 'Batch name will only effect the object related datablock names within the current selection.'),\n ('OBJECTS', 'All Objects', 'Batch name will effect all object related datablock names in the file.'),\n ('GLOBAL', 'Global', 'Batch name will effect all datablocks in the file. (Disables type filter menus.)')\n ],\n default = 'SELECTED'\n )\n\n # objects\n objects = BoolProperty(\n name = 'Objects',\n description = 'Name objects.',\n default = False\n )\n\n # groups\n groups = BoolProperty(\n name = 'Groups',\n description = 'Name groups.',\n default = False\n )\n\n # actions\n actions = BoolProperty(\n name = 'Actions',\n description = 'Name actions.',\n default = False\n )\n\n # grease pencil\n greasePencil = BoolProperty(\n name = 'Grease Pencil',\n description = 'Name grease pencils and layers.',\n default = False\n )\n\n # constraints\n constraints = BoolProperty(\n name = 'Object Constraints',\n description = 'Name constraints.',\n default = False\n )\n\n # modifiers\n modifiers = BoolProperty(\n name = 'Modifiers',\n description = 'Name modifiers.',\n default = False\n )\n\n # object data\n objectData = BoolProperty(\n name = 'Object Data',\n description = 'Name object data.',\n default = False\n )\n\n # bone groups\n boneGroups = BoolProperty(\n name = 'Bone Groups',\n description = 'Name bone groups.',\n default = False\n )\n\n # bones\n bones = BoolProperty(\n name = 'Bones',\n description = 'Name bones.',\n default = False\n )\n\n # bone constraints\n boneConstraints = BoolProperty(\n name = 'Bone Constraints',\n description = 'Name bone constraints.',\n default = False\n )\n\n # vertex groups\n vertexGroups = BoolProperty(\n name = 'Vertex Groups',\n description = 'Name vertex groups.',\n default = False\n )\n\n # shapekeys\n shapekeys = BoolProperty(\n name = 'Shapekeys',\n description = 'Name shapekeys.',\n default = False\n )\n\n # uvs\n uvs = BoolProperty(\n name = 'UV Maps',\n description = 'Name uv maps.',\n default = False\n )\n\n # vertex colors\n vertexColors = BoolProperty(\n name = 'Vertex Colors',\n description = 'Name vertex colors.',\n default = False\n )\n\n # materials\n materials = BoolProperty(\n name = 'Materials',\n description = 'Name materials.',\n default = False\n )\n\n # textures\n textures = BoolProperty(\n name = 'Textures',\n description = 'Name material textures.',\n default = False\n )\n\n # particle systems\n particleSystems = BoolProperty(\n name = 'Particle Systems',\n description = 'Name particle systems.',\n default = False\n )\n\n # particle settings\n particleSettings = BoolProperty(\n name = 'Particle Settings',\n description = 'Name particle settings.',\n default = False\n )\n\n # object type\n objectType = EnumProperty(\n name = 'Object Type',\n description = 'Type of objects to be effected.',\n items = menuList.objects,\n default = 'ALL'\n )\n\n # constraint type\n constraintType = EnumProperty(\n name = 'Constraint Type',\n description = 'Type of constraints to be effected.',\n items = menuList.constraints,\n default = 'ALL'\n )\n\n # modifier type\n modifierType = EnumProperty(\n name = 'Modifier Type',\n description = 'Type of modifiers to be effected.',\n items = menuList.modifiers,\n default = 'ALL'\n )\n\n # scenes\n scenes = BoolProperty(\n name = 'scenes',\n description = 'Name scenes. (Must use \\'Global\\' batch type option)',\n default = False\n )\n\n # render layers\n renderLayers = BoolProperty(\n name = 'Render Layers',\n description = 'Name render layers. (Must use \\'Global\\' batch type option)',\n default = False\n )\n\n # worlds\n worlds = BoolProperty(\n name = 'Worlds',\n description = 'Name worlds. (Must use \\'Global\\' batch type option)',\n default = False\n )\n\n # libraries\n libraries = BoolProperty(\n name = 'Libraries',\n description = 'Name libraries. (Must use \\'Global\\' batch type option)',\n default = False\n )\n\n # images\n images = BoolProperty(\n name = 'Images',\n description = 'Name images. (Must use \\'Global\\' batch type option)',\n default = False\n )\n\n # masks\n masks = BoolProperty(\n name = 'Masks',\n description = 'Name masks. (Must use \\'Global\\' batch type option)',\n default = False\n )\n\n # sequences\n sequences = BoolProperty(\n name = 'Sequences',\n description = 'Name sequences. (Must use \\'Global\\' batch type option)',\n default = False\n )\n\n # movie clips\n movieClips = BoolProperty(\n name = 'Movie Clips',\n description = 'Name movie clips. (Must use \\'Global\\' batch type option)',\n default = False\n )\n\n # sounds\n sounds = BoolProperty(\n name = 'Sounds',\n description = 'Name sounds. (Must use \\'Global\\' batch type option)',\n default = False\n )\n\n # screens\n screens = BoolProperty(\n name = 'Screens',\n description = 'Name screens. (Must use \\'Global\\' batch type option)',\n default = False\n )\n\n # keying sets\n keyingSets = BoolProperty(\n name = 'Keying Sets',\n description = 'Name keying sets. (Must use \\'Global\\' batch type option)',\n default = False\n )\n\n # palettes\n palettes = BoolProperty(\n name = 'Palettes',\n description = 'Name color palettes. (Must use \\'Global\\' batch type option)',\n default = False\n )\n\n # brushes\n brushes = BoolProperty(\n name = 'Brushes',\n description = 'Name brushes. (Must use \\'Global\\' batch type option)',\n default = False\n )\n\n # linestyles\n linestyles = BoolProperty(\n name = 'Linestyles',\n description = 'Name linestyles. (Must use \\'Global\\' batch type option)',\n default = False\n )\n\n # nodes\n nodes = BoolProperty(\n name = 'Nodes',\n description = 'Name nodes. (Must use \\'Global\\' batch type option)',\n default = False\n )\n\n # node labels\n nodeLabels = BoolProperty(\n name = 'Node Labels',\n description = 'Name node labels. (Must use \\'Global\\' batch type option)',\n default = False\n )\n\n # node groups\n nodeGroups = BoolProperty(\n name = 'Node Groups',\n description = 'Name node groups. (Must use \\'Global\\' batch type option)',\n default = False\n )\n\n # texts\n texts = BoolProperty(\n name = 'Texts',\n description = 'Name text documents. (Must use \\'Global\\' batch type option)',\n default = False\n )\n\n # custom name\n customName = StringProperty(\n name = 'Custom Name',\n description = 'Designate a new name.'\n )\n\n # find\n find = StringProperty(\n name = 'Find',\n description = 'Find this string in the datablock name and remove it.'\n )\n\n # regex\n regex = BoolProperty(\n name = 'Regular Expressions',\n description = 'Use regular expressions.',\n default = False\n )\n\n # replace\n replace = StringProperty(\n name = 'Replace',\n description = 'Replace found string with the string entered here.'\n )\n\n # prefix\n prefix = StringProperty(\n name = 'Prefix',\n description = 'Place this string at the beginning of the name.'\n )\n\n # suffix\n suffix = StringProperty(\n name = 'Suffix',\n description = 'Place this string at the end of the name.'\n )\n\n # trim start\n trimStart = IntProperty(\n name = 'Trim Start',\n description = 'Trim the beginning of the name.',\n min = 0,\n max = 50,\n default = 0\n )\n\n # trim end\n trimEnd = IntProperty(\n name = 'Trim End',\n description = 'Trim the ending of the name.',\n min = 0,\n max = 50,\n default = 0\n )\n\n # copy\n class copy(PropertyGroup):\n '''\n Properties that effect how the batch copy name operation is performed.\n '''\n\n # batch type\n batchType = EnumProperty(\n name = 'Batch Type',\n description = '',\n items = [\n ('SELECTED', 'Selected', 'Batch name copy will only effect the object related datablock names within the current selection.'),\n ('OBJECTS', 'All Objects', 'Batch name copy will effect all object related datablock names in the file.')\n ],\n default = 'SELECTED'\n )\n\n # source\n source = EnumProperty(\n name = 'Copy',\n description = 'Type of datablock to copy the name from.',\n items = [\n ('OBJECT', 'Object', 'Use the name from the object.', 'OBJECT_DATA', 0),\n ('DATA', 'Object Data', 'Use the name from the object\\'s data.', 'MESH_DATA', 1),\n ('MATERIAL', 'Material', 'Use the name from the active material of the object.', 'MATERIAL', 2),\n ('TEXTURE', 'Texture', 'Use the name from the active material\\'s active texture of the object.', 'TEXTURE', 3),\n ('PARTICLE_SYSTEM', 'Particle System', 'Use the name from the active particle system of the object.', 'PARTICLES', 4),\n ('PARTICLE_SETTINGS', 'Particle Settings', 'Use the name from the active particle system\\'s settings of the object.', 'MOD_PARTICLES', 5)\n ],\n default = 'OBJECT'\n )\n\n # objects\n objects = BoolProperty(\n name = 'Object',\n description = 'Paste to objects.',\n default = False\n )\n\n # object data\n objectData = BoolProperty(\n name = 'Object Data',\n description = 'Paste to object data.',\n default = False\n )\n\n # materials\n materials = BoolProperty(\n name = 'Material',\n description = 'Paste to materials.',\n default = False\n )\n\n # textures\n textures = BoolProperty(\n name = 'Texture',\n description = 'Paste to textures.',\n default = False\n )\n\n # particle systems\n particleSystems = BoolProperty(\n name = 'Particle System',\n description = 'Paste to particle systems.',\n default = False\n )\n\n # particle settings\n particleSettings = BoolProperty(\n name = 'Particle Settings',\n description = 'Paste to particle settings.',\n default = False\n )\n\n # use active object\n useActiveObject = BoolProperty(\n name = 'Use active object',\n description = 'Use the names available from the active object to paste to the other datablock names.',\n default = False\n )\n","sub_path":"scripts/addons_extern/item_panel/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":40988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"590158359","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 23 16:31:43 2015\n\n@author: adler\n\"\"\"\n\nfrom os.path import isfile as isfile\nfrom os.path import isdir as isdir\nimport sys\nfrom os import popen as system\n\nanimeinfofilelocation='animeInfo.txt'\n\ndef parseInfo(string):\n l=[k.split(': ')[1] for k in string.strip().strip('\\n').strip().split('\\n')]\n l[2]=int(l[2])\n l[3]=int(l[3])\n return l\n\ndef readAllFile(loc):\n f=open(loc,'rt')\n a=f.read()\n f.close()\n return a\n\ndef readList(loc):\n return [a for a in readAllFile(loc).strip('\\n').strip(' ').strip('\\n').split('\\n')]\n\ndef run(cmd):\n return system('bash -c \"'+cmd+'\"').read()\n\ndef cp(f,p):\n run('cp '+f+' '+p)\n\ndef mkdir_ondemand(a):\n if not isdir(a):\n run('mkdir '+'./%s/'%a)\n\ndef main():\n downfoldername='Downloads'\n downfolder='./%s/'%downfoldername\n archfn='archieved'\n sys.stdout.flush()\n cont=readAllFile(animeinfofilelocation)\n infoParsed=parseInfo(cont)\n fnList=readList(infoParsed[7]+'-vid-fns.txt')\n finalLoc=[downfolder+a for a in fnList]\n aafn=archfn+'/'+infoParsed[7]\n adafn=aafn+'/'+downfoldername\n mkdir_ondemand(archfn)\n mkdir_ondemand(aafn)\n mkdir_ondemand(adafn)\n print('Starting file movimentation...')\n sys.stdout.flush()\n cp('animeInfo.txt',aafn)\n mv(infoParsed[7]+'.txt',aafn)\n mv(infoParsed[7]+'-pag-url.txt',aafn)\n mv(infoParsed[7]+'-vid-url.txt',aafn)\n mv(infoParsed[7]+'-vid-fns.txt',aafn)\n [mv(f,adafn) for f in finalLoc]\n print('This script done its duty.')\n sys.stdout.flush()\n pass\n\nif __name__=='__main__':\n main()\n","sub_path":"simpleAnimeFetch_moveToArchieve.py","file_name":"simpleAnimeFetch_moveToArchieve.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"584743605","text":"import os\n\nfrom rlbot.agents.base_agent import BOT_CONFIG_AGENT_HEADER\nfrom rlbot.agents.base_independent_agent import BaseIndependentAgent\nfrom rlbot.botmanager.helper_process_request import HelperProcessRequest\nfrom rlbot.parsing.custom_config import ConfigObject\n\n\nclass ScratchBot(BaseIndependentAgent):\n\n def __init__(self, name, team, index):\n super().__init__(name, team, index)\n self.port: int = None\n self.spawn_browser: bool = False\n self.sb3file: str = None\n self.headless: bool = False\n\n def get_helper_process_request(self):\n file = os.path.realpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'scratch_manager.py'))\n self.logger.info(self.sb3file)\n key = 'scratch_helper' + (self.sb3file or '') + str(self.port)\n options = {\n 'port': self.port,\n 'spawn_browser': self.spawn_browser,\n 'sb3-file': self.sb3file,\n 'headless': self.headless\n }\n return HelperProcessRequest(file, key, options=options)\n\n def run_independently(self, terminate_request_event):\n pass\n\n def load_config(self, config_header):\n self.port = config_header.getint('port')\n self.spawn_browser = config_header.getint('spawn_browser')\n self.sb3file = config_header.getpath('sb3file')\n self.headless = config_header.getboolean('headless')\n\n @staticmethod\n def create_agent_configurations(config: ConfigObject):\n params = config.get_header(BOT_CONFIG_AGENT_HEADER)\n params.add_value('port', int, default=42008,\n description='Port to use for websocket communication')\n params.add_value('spawn_browser', bool, default=False,\n description='True if we should automatically open google chrome to the scratch page.')\n params.add_value('sb3file', str, default=None,\n description='Location of the scratch .sb3 file to load automatically')\n params.add_value('headless', bool, default=False,\n description='If true, bot will run automatically with no visible web browser')\n","sub_path":"RLBotPack/PacificScienceScratcher/scratch_bot.py","file_name":"scratch_bot.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"452831211","text":"import sys\n\nsys.path.append(\"..\")\n\nimport os\nimport pickle\nimport time\nimport matplotlib.pyplot as plt\nfrom tensorflow.python.keras.models import Sequential, load_model, Model\nfrom evaluate.helper_functions import layerwise_activations\nfrom evaluate.plot import plot_confusion_matrix\nfrom tensorflow.keras.layers import Dropout, Dense, Activation\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras import backend as K\nfrom lstm.lstm_helper_functions import *\nfrom sklearn.metrics import confusion_matrix\n\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\nFORWARD_PATH = '/home/jonas/Desktop/testing/convnet/stateful/5length_64size_1538406857/best_model'\nREVERSE_PATH = '/home/jonas/Desktop/testing/convnet/stateful/5length_64size_1538407083_Reverse/best_model'\n\n# set paramters\nNUM_TIME_STEPS = 5\nBATCH_SIZE = 32\nLSTM_SIZE = 64\nWINDOW_LENGTH = 30\nSOFTMAX_DROPOUT = 0.5\n\nSAVE_PATH = \"/home/jonas/Desktop/testing/convnet\"\n\n# set FEATURE_MODEL to None if no keras model is used\nFEATURE_MODEL = \"/home/jonas/Desktop/testing/convnet/test1/Model.hdf5\"\n# LAYER_NAME can be obtained from calling model.summary()\nLAYER_NAME = \"global_average_pooling1d\"\nCONV_NET = True\n\n# set DBN_MODEL to None if no dbn is used\nDBN_MODEL = None\n# LAYER_INDEX is only relevant for DBN models\nLAYER_INDEX = -1 # -1 for last layer\n\nif FEATURE_MODEL is not None and DBN_MODEL is not None:\n raise AttributeError(\"Keras model and DBN model given, set one or both to None!\")\n\n# get training and validation files\nLOAD_PATH = \"/home/jonas/Desktop/testing/raw_data_30s_intervals/\"\nKEYS = [\"sample\", \"one_hot_label\"]\nDATA_TYPES = [\"float32\", \"int32\"]\n\ntraining_files = []\nvalidation_files = []\n\n# only works if there is now dataset number higher than 50!\nfor file in os.listdir(LOAD_PATH):\n if \"dataset5\" in file:\n validation_files.append(LOAD_PATH + file)\n elif \"dataset10\" in file:\n validation_files.append(LOAD_PATH + file)\n elif \"dataset15\" in file:\n validation_files.append(LOAD_PATH + file)\n elif \"dataset20\" in file:\n validation_files.append(LOAD_PATH + file)\n elif \"dataset25\" in file:\n validation_files.append(LOAD_PATH + file)\n else:\n training_files.append(LOAD_PATH + file)\n\ntraining_files = sorted(training_files)\nvalidation_files = sorted(validation_files)\nprint(\"Num training files: \", len(training_files))\nprint(\"Num validation files: \", len(validation_files))\n\n# extract samples from files\nall_train_samples, all_train_labels, all_val_samples, all_val_labels = extract_samples(training_files,\n validation_files,\n KEYS,\n DATA_TYPES,\n False)\nif CONV_NET and FEATURE_MODEL is not None:\n for d, train_samples in enumerate(all_train_samples):\n all_train_samples[d] = train_samples.reshape([-1, train_samples.shape[-1] // 3, 3])\n\n for d, val_samples in enumerate(all_val_samples):\n all_val_samples[d] = val_samples.reshape([-1, val_samples.shape[-1] // 3, 3])\n\nprint(\"after file reading:\\n___________________\")\nfor s, l in zip(all_train_samples, all_train_labels):\n print(s.shape, l.shape)\n\nprint(\"val files: \")\nfor s, l in zip(all_val_samples, all_val_labels):\n print(s.shape, l.shape)\n\n# get outputs from model if required\nif FEATURE_MODEL is not None:\n model = load_model(FEATURE_MODEL)\n model.summary()\n last_layer_model = Model(inputs=model.input, outputs=model.get_layer(LAYER_NAME).output)\n\n for d, train_samples in enumerate(all_train_samples):\n all_train_samples[d] = last_layer_model.predict(train_samples)\n\n for d, val_samples in enumerate(all_val_samples):\n all_val_samples[d] = last_layer_model.predict(val_samples)\n K.clear_session()\n\nif DBN_MODEL is not None:\n pickle_in = open(DBN_MODEL, \"rb\")\n dbn = pickle.load(pickle_in)\n pickle_in.close()\n\n # calculate layerwise activations\n for d, train_samples in enumerate(all_train_samples):\n all_train_samples[d] = layerwise_activations(dbn, train_samples, num_activations=1)[LAYER_INDEX]\n\n for d, val_samples in enumerate(all_val_samples):\n all_val_samples[d] = layerwise_activations(dbn, val_samples, num_activations=1)[LAYER_INDEX]\n\n# cut all datasets to have a (whole number * BATCH_SIZE * time_steps) samples:\nnum_samples_batch = BATCH_SIZE * NUM_TIME_STEPS\n\nall_train_samples = [train_samples[:train_samples.shape[0] // num_samples_batch * num_samples_batch, :] for\n train_samples in all_train_samples]\n\nall_train_labels = [train_labels[:train_labels.shape[0] // num_samples_batch * num_samples_batch, :] for\n train_labels in all_train_labels]\n\nall_val_samples = [val_samples[:val_samples.shape[0] // num_samples_batch * num_samples_batch, :] for\n val_samples in all_val_samples]\n\nall_val_labels = [val_labels[:val_labels.shape[0] // num_samples_batch * num_samples_batch, :] for\n val_labels in all_val_labels]\n\nprint(\"after cutting of unusable samples:\\n___________________\")\nfor s, l in zip(all_train_samples, all_train_labels):\n print(s.shape, l.shape)\n\nprint(\"val files: \")\nfor s, l in zip(all_val_samples, all_val_labels):\n print(s.shape, l.shape)\n\nnum_x_signals = all_train_samples[0].shape[1]\nnum_labels = all_train_labels[0].shape[1]\n\n# get forward outputs:\n\n# reshape to match shape (num_series, num_time_steps, num_x_signals):\nall_train_samples_forward = [\n np.reshape(train_samples, [train_samples.shape[0] // NUM_TIME_STEPS, NUM_TIME_STEPS, num_x_signals]) for\n train_samples in all_train_samples]\n\nall_val_samples_forward = [\n np.reshape(val_samples, [val_samples.shape[0] // NUM_TIME_STEPS, NUM_TIME_STEPS, num_x_signals]) for\n val_samples in all_val_samples]\n\nfor counter, train_samples in enumerate(all_train_samples_forward):\n batches = make_batches(train_samples, BATCH_SIZE)\n train_samples = np.concatenate(batches)\n all_train_samples_forward[counter] = train_samples\n\nfor counter, val_samples in enumerate(all_val_samples_forward):\n batches = make_batches(val_samples, BATCH_SIZE)\n val_samples = np.concatenate(batches)\n all_val_samples_forward[counter] = val_samples\n\nlength_train_datasets = [d.shape[0] for d in all_train_samples_forward]\nlength_val_datasets = [d.shape[0] for d in all_val_samples_forward]\n\nmodel = load_model(FORWARD_PATH)\nmodel.summary()\nlayer_name = 'lstm'\nlast_layer_model = Model(inputs=model.input, outputs=model.get_layer(layer_name).output)\n\nall_train_outputs = []\nfor d, length in enumerate(length_train_datasets):\n train_samples = all_train_samples_forward[d]\n num_samples = length // BATCH_SIZE\n train_outputs = []\n for i in range(num_samples):\n x_batch = train_samples[i * BATCH_SIZE:(i + 1) * BATCH_SIZE]\n outputs = last_layer_model.predict_on_batch(x_batch)\n train_outputs.append(outputs)\n train_outputs = np.concatenate(train_outputs, axis=1)\n train_outputs = train_outputs.reshape([-1, LSTM_SIZE])\n last_layer_model.reset_states()\n all_train_outputs.append(train_outputs)\n\nall_val_outputs = []\nfor d, length in enumerate(length_val_datasets):\n val_samples = all_val_samples_forward[d]\n num_samples = length // BATCH_SIZE\n val_outputs = []\n for i in range(num_samples):\n x_batch = val_samples[i * BATCH_SIZE:(i + 1) * BATCH_SIZE]\n outputs = last_layer_model.predict_on_batch(x_batch)\n val_outputs.append(outputs)\n val_outputs = np.concatenate(val_outputs, axis=1)\n val_outputs = val_outputs.reshape([-1, LSTM_SIZE])\n last_layer_model.reset_states()\n all_val_outputs.append(val_outputs)\nK.clear_session()\n\nforward_train_outputs = all_train_outputs\nforward_val_outputs = all_val_outputs\n\n# get reverse outputs:\n\n# flip datasets:\nall_train_samples_reverse = [np.flip(train_samples, axis=0) for train_samples in all_train_samples]\nall_val_samples_reverse = [np.flip(val_samples, axis=0) for val_samples in all_val_samples]\n\n# reshape to match shape (num_series, num_time_steps, num_x_signals):\nall_train_samples_reverse = [\n np.reshape(train_samples, [train_samples.shape[0] // NUM_TIME_STEPS, NUM_TIME_STEPS, num_x_signals]) for\n train_samples in all_train_samples_reverse]\n\nall_val_samples_reverse = [\n np.reshape(val_samples, [val_samples.shape[0] // NUM_TIME_STEPS, NUM_TIME_STEPS, num_x_signals]) for\n val_samples in all_val_samples_reverse]\n\nfor counter, train_samples in enumerate(all_train_samples_reverse):\n batches = make_batches(train_samples, BATCH_SIZE)\n train_samples = np.concatenate(batches)\n all_train_samples_reverse[counter] = train_samples\n\nfor counter, val_samples in enumerate(all_val_samples_reverse):\n batches = make_batches(val_samples, BATCH_SIZE)\n val_samples = np.concatenate(batches)\n all_val_samples_reverse[counter] = val_samples\n\nlength_train_datasets = [d.shape[0] for d in all_train_samples_reverse]\nlength_val_datasets = [d.shape[0] for d in all_val_samples_reverse]\n\nmodel = load_model(REVERSE_PATH)\nmodel.summary()\nlayer_name = 'lstm'\nlast_layer_model = Model(inputs=model.input, outputs=model.get_layer(layer_name).output)\n\nall_train_outputs = []\nfor d, length in enumerate(length_train_datasets):\n train_samples = all_train_samples_reverse[d]\n num_samples = length // BATCH_SIZE\n train_outputs = []\n for i in range(num_samples):\n x_batch = train_samples[i * BATCH_SIZE:(i + 1) * BATCH_SIZE]\n outputs = last_layer_model.predict_on_batch(x_batch)\n train_outputs.append(outputs)\n train_outputs = np.concatenate(train_outputs, axis=1)\n train_outputs = train_outputs.reshape([-1, LSTM_SIZE])\n last_layer_model.reset_states()\n all_train_outputs.append(train_outputs)\n\nall_val_outputs = []\nfor d, length in enumerate(length_val_datasets):\n val_samples = all_val_samples_reverse[d]\n num_samples = length // BATCH_SIZE\n val_outputs = []\n for i in range(num_samples):\n x_batch = val_samples[i * BATCH_SIZE:(i + 1) * BATCH_SIZE]\n outputs = last_layer_model.predict_on_batch(x_batch)\n val_outputs.append(outputs)\n val_outputs = np.concatenate(val_outputs, axis=1)\n val_outputs = val_outputs.reshape([-1, LSTM_SIZE])\n last_layer_model.reset_states()\n all_val_outputs.append(val_outputs)\nK.clear_session()\n\n# reflip\nreverse_train_outputs = [np.flip(train_samples, axis=0) for train_samples in all_train_outputs]\nreverse_val_outputs = [np.flip(val_samples, axis=0) for val_samples in all_val_outputs]\n\n# train combined softmax layer:\n\n# combine outputs\nall_train_outputs_combined = [np.concatenate([x, y], axis=1) for x, y in\n zip(forward_train_outputs, reverse_train_outputs)]\nfor train_outputs in all_train_outputs_combined:\n print(train_outputs.shape)\n\nall_val_outputs_combined = [np.concatenate([x, y], axis=1) for x, y in zip(forward_val_outputs, reverse_val_outputs)]\nfor val_outputs in all_val_outputs_combined:\n print(val_outputs.shape)\n\nmodel = Sequential()\nmodel.add(Dropout(SOFTMAX_DROPOUT))\nmodel.add(Dense(num_labels, input_shape=(2 * LSTM_SIZE,)))\nmodel.add(Activation('softmax'))\n\nmodel.compile(loss='categorical_crossentropy', optimizer='Adam', metrics=['accuracy'])\nmodel.fit(x=np.concatenate(all_train_outputs_combined, axis=0),\n y=np.concatenate(all_train_labels, axis=0),\n epochs=10,\n batch_size=64,\n validation_data=(np.concatenate(all_val_outputs_combined, axis=0), np.concatenate(all_val_labels, axis=0)),\n verbose=1, callbacks=[EarlyStopping()])\n\nall_outputs = []\nfor d, val_samples in enumerate(all_val_outputs_combined):\n all_outputs.append(model.predict(val_samples))\n print(f'Shape outputs dataset {d}', all_outputs[d].shape)\nK.clear_session()\n\nall_output_classes_reduced, all_true_classes_reduced = get_accuracies_and_plot_labels(all_outputs,\n all_val_labels,\n time_window_length=WINDOW_LENGTH,\n save_path=SAVE_PATH)\n\ncm = confusion_matrix(np.concatenate(all_true_classes_reduced), np.concatenate(all_output_classes_reduced))\nnp.set_printoptions(precision=2)\n\n# Plot normalized confusion matrix\nclass_names = ['awake', 'N1', 'N2', 'N3', 'REM']\nplt.figure(figsize=(5.79, 5.79))\nplot_confusion_matrix(cm, classes=class_names, normalize=True,\n title='Normalized confusion matrix')\nif SAVE_PATH is not None:\n plt.savefig(os.path.join(SAVE_PATH, \"confusion_matrix.pdf\"), format='pdf', bbox_inches='tight')\nplt.show()\n","sub_path":"lstm/combine_forward_and_reverse.py","file_name":"combine_forward_and_reverse.py","file_ext":"py","file_size_in_byte":13000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"562965356","text":"import FWCore.ParameterSet.Config as cms\nimport FWCore.ParameterSet.VarParsing as VarParsing\n\nprocess = cms.Process(\"FakeSyncExercise\")\noptions = VarParsing.VarParsing ('analysis')\n\n#set default arguments\noptions.inputFiles= 'file:/nfs-3/userdata/jgran/qcd_mu_file1.root, file:/nfs-3/userdata/jgran/qcd_mu_file2.root'\noptions.maxEvents = -1 # -1 means all events\n#options.maxEvents = 100 \n\n# get and parse the command line arguments\noptions.parseArguments()\n\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(options.maxEvents) )\n\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(options.inputFiles),\n)\n\nprocess.out = cms.OutputModule(\n \"PoolOutputModule\",\n fileName = cms.untracked.string('ntuple.root'),\n)\n\nprocess.outpath = cms.EndPath(process.out)\nprocess.out.outputCommands = cms.untracked.vstring( 'drop *' )\nprocess.out.outputCommands.extend(cms.untracked.vstring('keep *_*fakeSync*_*_*'))\n\nprocess.load(\"Configuration.StandardSequences.Reconstruction_cff\")\nprocess.load('Configuration.StandardSequences.Services_cff')\nprocess.load(\"Configuration.StandardSequences.FrontierConditions_GlobalTag_cff\")\nprocess.load(\"Configuration.StandardSequences.MagneticField_cff\")\nprocess.load(\"Configuration.Geometry.GeometryIdeal_cff\")\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\n\nprocess.GlobalTag.globaltag = \"START53_V7::All\"\n\nprocess.load(\"SUSYFakes.Base.bTaggingSequence_cfi\")\nprocess.load(\"SUSYFakes.Base.fakeSync_cfi\")\n\nprocess.p = cms.Path(process.CSVSequence*process.fakeSync)\n","sub_path":"Base/python/run_cfg.py","file_name":"run_cfg.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"370117275","text":"import re\nfrom Metrics.BaseMetric import BaseMetric\n\n\nclass JilbaMetric(BaseMetric):\n\n __ifs = []\n __fores = []\n __whiles = []\n __operators = 0\n __max_depth = 0\n\n def __init__(self, source_code, operators):\n self.__operators = [operator.rstrip('\\n') for operator in operators if operator != '\\n']\n super().__init__(source_code)\n\n def __find_if_count(self):\n self.__ifs += re.findall(r'if ', self.source_code)\n #self.__ifs += re.findall(r'else', ''.join(self.__source_code).rstrip('\\n'))\n\n def __find_while_count(self):\n self.__whiles += re.findall(r'while', self.source_code)\n\n def __find_for_count(self):\n self.__fores += re.findall(r'for', self.source_code)\n\n def __get_all_operators_count(self):\n words = ''.join(self.source_code.split(' '))\n self.__using_operators = [word for word in words if word in self.__operators]\n\n @classmethod\n def get_first_spaces_count(cls, line):\n spaces_count = 0\n for symbol in line:\n if symbol == ' ':\n spaces_count += 1\n else:\n return spaces_count\n\n def __get_max_depth(self):\n all_depths = []\n for line in self.source_code:\n if re.findall(r'if', line) or re.findall(r'else', line) or re.findall(r'while', line) \\\n or re.findall(r'for', line):\n all_depths.append(JilbaMetric.get_first_spaces_count(line))\n\n all_depths = list(filter(lambda element: element != 0, all_depths))\n all_depths = list(filter(lambda element: element / 2, all_depths))\n print(all_depths)\n if len(all_depths) == 0:\n self.__max_depth = 0\n return\n max_spaces_count = max(all_depths)\n min_spaces_count = min(all_depths)\n print('max = {}, min = {}'.format(max_spaces_count, min_spaces_count))\n self.__max_depth = max_spaces_count/min_spaces_count\n\n def __prepare_result(self):\n return {\n 'if count: ': self.__ifs,\n #'while count: ': len(self.__whiles),\n #'for count: ': len(self.__fores),\n #'all_operators: ': self.__using_operators,\n #'all_operators_count: ': len(self.__using_operators),\n 'CL: ': (len(self.__ifs) + len(self.__fores) + len(self.__whiles)),\n 'cl: ': (len(self.__ifs) + len(self.__fores) + len(self.__whiles)) / len(self.__using_operators),\n 'max_depth: ': self.__max_depth\n }\n\n def prepare_to_metric(self):\n self.__find_for_count()\n self.__find_if_count()\n self.__find_while_count()\n self.__get_all_operators_count()\n self.__get_max_depth()\n return self.__prepare_result()\n\n def get_metric(self):\n return self.prepare_to_metric()\n","sub_path":"Metrics/JilbaMetric.py","file_name":"JilbaMetric.py","file_ext":"py","file_size_in_byte":2811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"218619635","text":"import unittest\nimport json\nfrom data.environment import Environment\n\n\nclass Test_Environment(unittest.TestCase):\n\n def setUp(self):\n self.env = Environment()\n\n #def tearDown(self):\n #self.widget.dispose()\n\n def test_create_environment(self): \n \n self.assertNotEqual(self.env, None)\n\n def test_get_data(self): \n with open('config.json') as f:\n config=json.load(f)\n start_date = config['session']['start_date']\n end_date = config['session']['end_date']\n codes_num = config['session']['codes']\n market = config['session']['market_types']\n features = config['session']['features']\n train_start_date, train_end_date, test_start_date, test_end_date, codes = self.env.get_repo(start_date, end_date,\n codes_num, market)\n window_length=10\n self.env.get_data(train_start_date, train_end_date, features, window_length, market, codes) \n self.assertTrue(len(self.env.states)>0) # states has shape (1,6,10,2) 1,codes_num+1,window_length, features\n self.assertTrue(len(self.env.price_history)>0) #price_history has shape (6,1) codes_num + 1 ; \n #First element in price_history is always 1, means cash\n #print (self.env.states[0].shape)\n #print (self.env.price_history[0].shape)\n #print (self.env.price_history[0])\n\n def test_get_repo(self):\n with open('config.json') as f:\n config=json.load(f)\n start_date = config['session']['start_date']\n end_date = config['session']['end_date']\n codes_num = config['session']['codes']\n market = config['session']['market_types']\n self.train_start_date, self.train_end_date, test_start_date, test_end_date, self.codes = self.env.get_repo(start_date, end_date,\n codes_num, market)\n self.assertTrue(len(self.env.data)>0)\n self.assertTrue(len(self.env.date_set)>0)\n\n # step requires get_data to have been called first to fill the environment.\n def test_step(self):\n self.test_get_data()\n self.env.reset()\n noise_flag = False\n info = self.env.step(None,None,noise_flag)\n # dict_keys(['reward', 'continue', 'next state', 'weight vector', 'price', 'risk'])\n #print (info.keys())\n #print (info['reward']) # Reward is an integer\n #print (info['continue']) # continue is True/False\n #print (info['next state'].shape) # Shape for next state is (1,6,10,2)\n #print (info['weight vector'].shape) # Shape for weight vector is (1,6)\n #print (info['risk']) #Risk is an integer\n #print (info['price'].shape) #Shape for price is 6,1)\n self.assertEqual(len(info.keys(),6))\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"test/test_environment.py","file_name":"test_environment.py","file_ext":"py","file_size_in_byte":2961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"631320663","text":"# =============================================================================\n# pre_migrate.py - plugin for preparing for migrating classic XR to eXR/fleXR\n#\n# Copyright (c) 2013, Cisco Systems\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# 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# 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; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n# THE POSSIBILITY OF SUCH DAMAGE.\n# =============================================================================\n\nimport csv\nimport os\nimport re\nimport subprocess\n\nimport pexpect\n\nfrom csmpe.plugins import CSMPlugin\nfrom csmpe.core_plugins.csm_install_operations.utils import ServerType, is_empty, concatenate_dirs\nfrom simple_server_helper import TFTPServer, FTPServer, SFTPServer\nfrom hardware_audit import Plugin as HardwareAuditPlugin\nfrom migration_lib import log_and_post_status, compare_version_numbers\nfrom csmpe.core_plugins.csm_get_inventory.ios_xr.plugin import get_package, get_inventory\n\nMINIMUM_RELEASE_VERSION_FOR_MIGRATION = \"6.1.3\"\n\nNOX_FOR_MAC = \"nox-mac64.bin\"\nNOX_64_BINARY = \"nox-linux-64.bin\"\n\nTIMEOUT_FOR_COPY_CONFIG = 36000\nTIMEOUT_FOR_COPY_IMAGE = 36000\nTIMEOUT_FOR_FPD_UPGRADE = 36000\n\nIMAGE_LOCATION = \"harddisk:/\"\nCONFIG_LOCATION = \"harddiskb:/\"\n\nXR_CONFIG_IN_CSM = \"xr.cfg\"\nADMIN_CONFIG_IN_CSM = \"admin.cfg\"\n\nCONVERTED_XR_CONFIG_IN_CSM = \"xr.iox\"\nCONVERTED_ADMIN_CAL_CONFIG_IN_CSM = \"admin.cal\"\nCONVERTED_ADMIN_XR_CONFIG_IN_CSM = \"admin.iox\"\n\nFINAL_CAL_CONFIG = \"cXR_admin_plane_converted_eXR.cfg\"\nFINAL_XR_CONFIG = \"cXR_xr_plane_converted_eXR.cfg\"\n\nCRYPTO_KEY_FILENAME = \"crypto_auto_key_gen.txt\"\n\n# XR_CONFIG_ON_DEVICE = \"iosxr.cfg\"\n# ADMIN_CAL_CONFIG_ON_DEVICE = \"admin_calvados.cfg\"\n# ADMIN_XR_CONFIG_ON_DEVICE = \"admin_iosxr.cfg\"\n\n\nclass Plugin(CSMPlugin):\n \"\"\"\n A plugin for preparing device for migration from\n ASR9K IOS-XR (a.k.a. XR) to ASR9K IOS-XR 64 bit (a.k.a. eXR)\n\n This plugin does the following:\n 1. Check several pre-requisites\n 2. Resize the eUSB partition(/harddiskb:/ on XR)\n 3. Migrate the configurations with NoX and upload them to device\n 4. Copy the eXR image to /harddiskb:/\n 5. Upgrade some FPD's if needed.\n\n Console access is needed.\n \"\"\"\n name = \"Pre-Migrate Plugin\"\n platforms = {'ASR9K'}\n phases = {'Pre-Migrate'}\n os = {'XR'}\n\n node_pattern = re.compile(r\"^\\d+(/\\w+)+$\")\n repo_ip_search_pattern = re.compile(r\"[/@](\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})(;.*?)?/\")\n\n def _save_show_platform(self):\n \"\"\"Save the output of 'show platform' to session log\"\"\"\n\n cmd = \"show platform\"\n # show platform can take more than 1 minute after router reload. Issue No. 47\n output = self.ctx.send(cmd, timeout=600)\n file_name = self.ctx.save_to_file(cmd, output)\n if file_name is None:\n self.ctx.warning(\"Unable to save '{}' output to file: {}\".format(cmd, file_name))\n\n def _ping_repository_check(self, repo_url):\n \"\"\"Test ping server repository ip from device\"\"\"\n repo_ip = re.search(self.repo_ip_search_pattern, repo_url)\n if not repo_ip:\n self.ctx.error(\"Bad hostname for server repository. Please check the settings in CSM.\")\n\n if not repo_ip.group(2):\n vrf = ''\n else:\n vrf = repo_ip.group(2)[1:]\n\n if vrf:\n output = self.ctx.send(\"ping vrf {} {}\".format(vrf, repo_ip.group(1)))\n else:\n output = self.ctx.send(\"ping {}\".format(repo_ip.group(1)))\n\n if \"100 percent\" not in output:\n self.ctx.error(\"Failed to ping server repository {} on device.\".format(repo_ip.group(1)) +\n \"Please check session.log.\")\n\n def _all_configs_supported(self, nox_output):\n \"\"\"Check text output from running NoX on system. Only return True if all configs are supported by eXR.\"\"\"\n pattern = r\"Filename[\\sA-Za-z\\n]*[-\\s]*\\S*\\s+\\d*\\s+\\d*\\(\\s*\\d*%\\)\\s+\\d*\\(\\s*\\d*%\\)\\s+\\d*\\(\\s*\\d*%\\)\\s+(\\d*)\"\n match = re.search(pattern, nox_output)\n\n if match:\n if match.group(1) != \"0\":\n return False\n\n return True\n\n def _upload_files_to_server_repository(self, sourcefiles, server, destfilenames):\n \"\"\"\n Upload files from their locations in the host linux system to the FTP/TFTP/SFTP server repository.\n\n Arguments:\n :param sourcefiles: a list of string file paths that each points to a file on the system where CSM is hosted.\n The paths are all relative to csm/csmserver/.\n For example, if the source file is in csm_data/migration/filename,\n sourcefiles = [\"../../csm_data/migration/filename\"]\n :param server: the associated server repository object stored in CSM database\n :param destfilenames: a list of string filenames that the source files should be named after being copied to\n the designated directory in the server repository. i.e., [\"thenewfilename\"]\n :return: True if no error occurred.\n \"\"\"\n\n server_type = server.server_type\n selected_server_directory = self.ctx._csm.install_job.server_directory\n if server_type == ServerType.TFTP_SERVER:\n tftp_server = TFTPServer(server)\n for x in range(0, len(sourcefiles)):\n log_and_post_status(self.ctx, \"Copying file {} to {}/{}/{}.\".format(sourcefiles[x],\n server.server_directory,\n selected_server_directory,\n destfilenames[x]))\n try:\n tftp_server.upload_file(sourcefiles[x], destfilenames[x],\n sub_directory=selected_server_directory)\n except:\n self.ctx.error(\"Exception was thrown while \" +\n \"copying file {} to {}/{}/{}.\".format(sourcefiles[x],\n server.server_directory,\n selected_server_directory,\n destfilenames[x]))\n\n elif server_type == ServerType.FTP_SERVER:\n ftp_server = FTPServer(server)\n for x in range(0, len(sourcefiles)):\n log_and_post_status(self.ctx, \"Copying file {} to {}/{}/{}.\".format(sourcefiles[x],\n server.server_directory,\n selected_server_directory,\n destfilenames[x]))\n try:\n ftp_server.upload_file(sourcefiles[x], destfilenames[x],\n sub_directory=selected_server_directory)\n except:\n self.ctx.error(\"Exception was thrown while \" +\n \"copying file {} to {}/{}/{}.\".format(sourcefiles[x],\n server.server_directory,\n selected_server_directory,\n destfilenames[x]))\n elif server_type == ServerType.SFTP_SERVER:\n sftp_server = SFTPServer(server)\n for x in range(0, len(sourcefiles)):\n log_and_post_status(self.ctx, \"Copying file {} to {}/{}/{}.\".format(sourcefiles[x],\n server.server_directory,\n selected_server_directory,\n destfilenames[x]))\n try:\n sftp_server.upload_file(sourcefiles[x], destfilenames[x],\n sub_directory=selected_server_directory)\n except:\n self.ctx.error(\"Exception was thrown while \" +\n \"copying file {} to {}/{}/{}.\".format(sourcefiles[x],\n server.server_directory,\n selected_server_directory,\n destfilenames[x]))\n else:\n self.ctx.error(\"Pre-Migrate does not support {} server repository.\".format(server_type))\n\n return True\n\n def _copy_files_to_device(self, server, repository, source_filenames, dest_files, timeout=3600):\n \"\"\"\n Copy files from their locations in the user selected server directory in the FTP/TFTP/SFTP server repository\n to locations on device.\n\n Arguments:\n :param server: the server object fetched from database\n :param repository: the string url link that points to the location of files in the SFTP server repository\n :param source_filenames: a list of string filenames in the designated directory in the server repository.\n :param dest_files: a list of string file paths that each points to a file to be created on device.\n i.e., [\"harddiskb:/asr9k-mini-x64.tar\"]\n :param timeout: the timeout for the sftp copy operation on device. The default is 10 minutes.\n :return: None if no error occurred.\n \"\"\"\n\n if server.server_type == ServerType.FTP_SERVER or server.server_type == ServerType.TFTP_SERVER:\n self._copy_files_from_ftp_tftp_to_device(repository, source_filenames, dest_files, timeout=timeout)\n\n elif server.server_type == ServerType.SFTP_SERVER:\n self._copy_files_from_sftp_to_device(server, source_filenames, dest_files, timeout=timeout)\n\n else:\n self.ctx.error(\"Pre-Migrate does not support {} server repository.\".format(server.server_type))\n\n def _copy_files_from_ftp_tftp_to_device(self, repository, source_filenames, dest_files, timeout=3600):\n \"\"\"\n Copy files from their locations in the user selected server directory in the FTP or TFTP server repository\n to locations on device.\n\n Arguments:\n :param repository: the string url link that points to the location of files in the FTP/TFTP server repository,\n with no extra '/' in the end. i.e., tftp://223.255.254.245/tftpboot\n :param source_filenames: a list of string filenames in the designated directory in the server repository.\n :param dest_files: a list of string file paths that each points to a file to be created on device.\n i.e., [\"harddiskb:/asr9k-mini-x64.tar\"]\n :param timeout: the timeout for the 'copy' CLI command on device. The default is 10 minutes.\n :return: None if no error occurred.\n \"\"\"\n\n def send_repo_ip(ctx):\n repo_ip = re.search(self.repo_ip_search_pattern, repository)\n ctx.ctrl.sendline(repo_ip.group(1))\n return True\n\n def send_newline(ctx):\n ctx.ctrl.sendline()\n return True\n\n def error(ctx):\n ctx.message = \"Error copying file.\"\n return False\n\n for x in range(0, len(source_filenames)):\n\n command = \"copy {}/{} {}\".format(repository, source_filenames[x], dest_files[x])\n\n CONFIRM_HOST = re.compile(r\"Address or name of remote host\")\n CONFIRM_FILENAME = re.compile(r\"Destination filename.*\\?\")\n CONFIRM_OVERWRITE = re.compile(r\"Copy : Destination exists, overwrite \\?\\[confirm\\]\")\n COPIED = re.compile(r\".+bytes copied in.+ sec\")\n COPYING = re.compile(r\"C\" * 50)\n NO_SUCH_FILE = re.compile(r\"%Error copying.*\\(Error opening source file\\): No such file or directory\")\n ERROR_COPYING = re.compile(r\"%Error copying\")\n\n PROMPT = self.ctx.prompt\n TIMEOUT = self.ctx.TIMEOUT\n\n events = [PROMPT, CONFIRM_HOST, CONFIRM_FILENAME, CONFIRM_OVERWRITE, COPIED, COPYING,\n TIMEOUT, NO_SUCH_FILE, ERROR_COPYING]\n transitions = [\n (CONFIRM_HOST, [0], 0, send_repo_ip, 120),\n (CONFIRM_FILENAME, [0], 1, send_newline, 120),\n (CONFIRM_OVERWRITE, [1], 2, send_newline, timeout),\n (COPIED, [0, 1, 2], 3, None, 60),\n (COPYING, [0, 1, 2], 2, send_newline, timeout),\n (PROMPT, [3], -1, None, 0),\n (TIMEOUT, [0, 1, 2, 3], -1, error, 0),\n (NO_SUCH_FILE, [0, 1, 2, 3], -1, error, 0),\n (ERROR_COPYING, [0, 1, 2, 3], -1, error, 0),\n ]\n\n log_and_post_status(self.ctx, \"Copying {}/{} to {} on device\".format(repository,\n source_filenames[x],\n dest_files[x]))\n\n if not self.ctx.run_fsm(\"Copy file from tftp/ftp to device\", command, events, transitions,\n timeout=80, max_transitions=200):\n self.ctx.error(\"Error copying {}/{} to {} on device\".format(repository,\n source_filenames[x],\n dest_files[x]))\n\n output = self.ctx.send(\"dir {}\".format(dest_files[x]))\n if \"No such file\" in output:\n self.ctx.error(\"Failed to copy {}/{} to {} on device\".format(repository,\n source_filenames[x],\n dest_files[x]))\n\n def _copy_files_from_sftp_to_device(self, server, source_filenames, dest_files, timeout=3600):\n \"\"\"\n Copy files from their locations in the user selected server directory in the SFTP server repository\n to locations on device.\n\n Arguments:\n :param server: the sftp server object\n :param source_filenames: a list of string filenames in the designated directory in the server repository.\n :param dest_files: a list of string file paths that each points to a file to be created on device.\n i.e., [\"harddiskb:/asr9k-mini-x64.tar\"]\n :param timeout: the timeout for the sftp copy operation on device. The default is 10 minutes.\n :return: None if no error occurred.\n \"\"\"\n source_path = server.server_url\n\n remote_directory = concatenate_dirs(server.server_directory, self.ctx._csm.install_job.server_directory)\n if not is_empty(remote_directory):\n source_path += \":{}\".format(remote_directory)\n\n def send_password(ctx):\n ctx.ctrl.sendline(server.password)\n \"\"\"\n This was made necessary because during sftp download, when file is large,\n the number of transferred bytes keeps changing and session log takes so much\n time in reading and writing the changing number that it is still doing that\n long after the operation is complete.\n \"\"\"\n self.ctx.pause_session_logging()\n return True\n\n def send_yes(ctx):\n ctx.ctrl.sendline(\"yes\")\n self.ctx.pause_session_logging()\n return True\n\n def reinstall_logfile(ctx):\n self.ctx.resume_session_logging()\n return True\n\n def timeout_error(ctx):\n reinstall_logfile(ctx)\n ctx.message = \"Timed out while copying file from sftp.\"\n return False\n\n def no_such_file_error(ctx):\n reinstall_logfile(ctx)\n ctx.message = \"Copying the file from sftp failed because it is not found in the specified path.\"\n return False\n\n def download_abort_error(ctx):\n reinstall_logfile(ctx)\n ctx.message = \"Copying the file from sftp failed. Download was aborted.\"\n return False\n\n for x in range(0, len(source_filenames)):\n if is_empty(server.vrf):\n command = \"sftp {}@{}/{} {}\".format(server.username, source_path, source_filenames[x], dest_files[x])\n else:\n command = \"sftp {}@{}/{} {} vrf {}\".format(server.username, source_path, source_filenames[x],\n dest_files[x], server.vrf)\n\n PASSWORD = re.compile(r\"Password:\")\n CONFIRM_OVERWRITE = re.compile(r\"Overwrite.*\\[yes/no\\]\\:\")\n COPIED = re.compile(r\"bytes copied in\", re.MULTILINE)\n NO_SUCH_FILE = re.compile(r\"src.*does not exist\")\n DOWNLOAD_ABORTED = re.compile(r\"Download aborted.\")\n\n PROMPT = self.ctx.prompt\n TIMEOUT = self.ctx.TIMEOUT\n\n events = [PROMPT, PASSWORD, CONFIRM_OVERWRITE, COPIED, TIMEOUT, NO_SUCH_FILE, DOWNLOAD_ABORTED]\n transitions = [\n (PASSWORD, [0], 1, send_password, timeout),\n (CONFIRM_OVERWRITE, [1], 2, send_yes, timeout),\n (COPIED, [1, 2], -1, reinstall_logfile, 0),\n (PROMPT, [1, 2], -1, reinstall_logfile, 0),\n (TIMEOUT, [0, 1, 2], -1, timeout_error, 0),\n (NO_SUCH_FILE, [0, 1, 2], -1, no_such_file_error, 0),\n (DOWNLOAD_ABORTED, [0, 1, 2], -1, download_abort_error, 0),\n ]\n\n log_and_post_status(self.ctx, \"Copying {}/{} to {} on device\".format(source_path,\n source_filenames[x],\n dest_files[x]))\n\n if not self.ctx.run_fsm(\"Copy file from sftp to device\", command, events, transitions, timeout=80):\n self.ctx.error(\"Error copying {}/{} to {} on device\".format(source_path,\n source_filenames[x],\n dest_files[x]))\n\n output = self.ctx.send(\"dir {}\".format(dest_files[x]))\n if \"No such file\" in output:\n self.ctx.error(\"Failed to copy {}/{} to {} on device\".format(source_path,\n source_filenames[x],\n dest_files[x]))\n\n def _run_migration_on_config(self, fileloc, filename, nox_to_use, hostname):\n \"\"\"\n Run the migration tool - NoX - on the configurations copied out from device.\n\n The conversion/migration is successful if the number under 'Total' equals to\n the number under 'Known' in the text output.\n\n If it's successful, but not all existing configs are supported by eXR, create two\n new log files for the supported and unsupported configs in session log directory.\n The unsupported configs will not appear on the converted configuration files.\n Log a warning about the removal of unsupported configs, but this is not considered\n as error.\n\n If it's not successful, meaning that there are some configurations not known to\n the NoX tool, in this case, create two new log files for the supported and unsupported\n configs in session log directory. After that, error out.\n\n :param fileloc: string location where the config needs to be converted/migrated is,\n without the '/' in the end. This location is relative to csm/csmserver/\n :param filename: string filename of the config\n :param nox_to_use: string name of NoX binary executable.\n :param hostname: hostname of device, as recorded on CSM.\n :return: None if no error occurred.\n \"\"\"\n\n try:\n commands = [subprocess.Popen([\"chmod\", \"+x\", nox_to_use]),\n subprocess.Popen([nox_to_use, \"-f\", os.path.join(fileloc, filename)],\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n ]\n\n nox_output, nox_error = commands[1].communicate()\n except OSError:\n self.ctx.error(\"Failed to run the configuration migration tool {} on config file {} - OSError.\".format(\n nox_to_use,\n os.path.join(fileloc, filename))\n )\n\n if nox_error:\n self.ctx.error(\"Failed to run the configuration migration tool on the admin configuration \" +\n \"we retrieved from device - {}.\".format(nox_error))\n\n if filename.split('.')[0] == 'admin':\n if (not os.path.isfile(os.path.join(fileloc, CONVERTED_ADMIN_CAL_CONFIG_IN_CSM))) or \\\n (not os.path.isfile(os.path.join(fileloc, CONVERTED_ADMIN_XR_CONFIG_IN_CSM))):\n self.ctx.error(\"Failed to convert the ASR9K admin configuration with NoX tool.\")\n\n elif not os.path.isfile(os.path.join(fileloc, CONVERTED_XR_CONFIG_IN_CSM)):\n self.ctx.error(\"Failed to convert the ASR9K IOS-XR configuration with NoX tool.\")\n\n conversion_success = False\n\n match = re.search(r\"Filename[\\sA-Za-z\\n]*[-\\s]*\\S*\\s+(\\d*)\\s+\\d*\\(\\s*\\d*%\\)\\s+\\d*\\(\\s*\\d*%\\)\\s+(\\d*)\",\n nox_output)\n\n if match:\n if match.group(1) == match.group(2):\n conversion_success = True\n\n if filename == ADMIN_CONFIG_IN_CSM:\n supported_log_name = \"supported_config_in_admin_configuration\"\n unsupported_log_name = \"unsupported_config_in_admin_configuration\"\n else:\n supported_log_name = \"supported_config_in_xr_configuration\"\n unsupported_log_name = \"unsupported_config_in_xr_configuration\"\n\n if conversion_success:\n\n if self._all_configs_supported(nox_output):\n log_and_post_status(self.ctx, \"Configuration {} was migrated successfully. \".format(filename) +\n \"No unsupported configurations found.\")\n else:\n self._create_config_logs(os.path.join(fileloc, filename.split(\".\")[0] + \".csv\"),\n supported_log_name, unsupported_log_name,\n hostname, filename)\n\n log_and_post_status(self.ctx, \"Configurations that are unsupported in eXR were removed in \" +\n \"{}. Please look into {} and {}.\".format(filename,\n unsupported_log_name,\n supported_log_name))\n else:\n self._create_config_logs(os.path.join(fileloc, filename.split(\".\")[0] + \".csv\"),\n supported_log_name, unsupported_log_name, hostname, filename)\n\n self.ctx.error(\"Unknown configurations found. Please look into {} \".format(unsupported_log_name) +\n \"for unprocessed configurations, and {} for known/supported configurations\".format(\n unsupported_log_name, supported_log_name)\n )\n\n def _resize_eusb(self):\n \"\"\"Resize the eUSB partition on device - Run the /pkg/bin/resize_eusb script on device(from ksh).\"\"\"\n\n output = self.ctx.send(\"run /pkg/bin/resize_eusb\")\n\n if \"Pre-Migration Operation Completed.\" not in output:\n self.ctx.error(\"Pre-Migrate partition check failed. Please check session.log.\")\n # output = self.ctx.send(\"show media\")\n\n # eusb_size = re.search(\"/harddiskb:.* ([.\\d]+)G\", output)\n\n # if not eusb_size:\n # self.ctx.error(\"Unexpected output from CLI 'show media'.\")\n\n # if eusb_size.group(1) < \"1.0\":\n # self.ctx.error(\"/harddiskb:/ is smaller than 1 GB after running /pkg/bin/resize_eusb. \" +\n # \"Please make sure that the device has either RP2 or RSP4.\")\n\n def _check_fpd(self, fpd_relevant_nodes):\n \"\"\"\n Check the versions of migration related FPD's on device. Return a dictionary\n that tells which FPD's on which nodes require successful FPD upgrade later on.\n\n :param fpd_relevant_nodes: a dictionary. Keys are strings representing all node locations\n on device parsed from output of \"admin show platform\".\n Values are integers. Value can either be 0 or 1.\n value 1 means that we actually will need to make sure that the\n FPD upgrade later on for this node location completes successfully,\n value 0 means that we don't need to check if the\n FPD upgrade later on for this node location is successful or not.\n :return: a dictionary with string FPD type as key, and a set of the string names of\n node locations as value.\n \"\"\"\n fpdtable = self.ctx.send(\"show hw-module fpd location all\")\n\n subtype_to_locations_need_upgrade = {}\n\n last_location = None\n for line in fpdtable.split('\\n'):\n\n first_word = line.split(' ', 1)[0]\n\n if self.node_pattern.match(first_word):\n # since fpd_relevant_nodes is loaded from db, the keys are\n # unicode instead of byte strings\n indicator = fpd_relevant_nodes.get(unicode(first_word, encoding=\"latin1\"))\n # indicator is 1:\n # Detect a new node(RSP/RP/LC/FC) of which fpds we'll need to check\n # if upgrade goes successful\n # indicator is None:\n # Detect node that is not found in output of \"admin show platform\"\n # we need to check if FPD upgrade goes successful in this case\n if indicator == 1 or indicator is None:\n last_location = first_word\n # indicator is 0:\n # Detect node to be PEM/FAN or some other unsupported hardware in eXR.\n # we don't care if the FPD upgrade for these is successful or not\n # so we update last_location to None\n else:\n last_location = None\n\n # Found some fpd that needs upgrade\n if last_location and len(line) >= 79 and line[76:79] == \"Yes\":\n fpdtype_end_idx = 51\n while line[fpdtype_end_idx] != ' ':\n fpdtype_end_idx += 1\n\n fpdtype = line[51:fpdtype_end_idx]\n\n if fpdtype not in subtype_to_locations_need_upgrade:\n # it is possible to have duplicates, so using set here\n subtype_to_locations_need_upgrade[fpdtype] = set()\n subtype_to_locations_need_upgrade[fpdtype].add(last_location)\n\n return subtype_to_locations_need_upgrade\n\n def _check_if_fpd_package_installed(self):\n \"\"\"\n Check if the FPD package is already active on device.\n Error out if not.\n\n :return: None if FPD package is active, error out if not.\n \"\"\"\n active_packages = self.ctx.send(\"show install active summary\")\n\n match = re.search(\"fpd\", active_packages)\n\n if not match:\n self.ctx.error(\"No FPD package is active on device. Please install the FPD package on device first.\")\n\n return\n\n def _ensure_updated_fpd(self, fpd_relevant_nodes):\n \"\"\"\n Upgrade FPD's if needed.\n Steps:\n 1. Check version of the migration related FPD's. Get the dictionary\n of FPD types mapped to locations for which we need to check for\n upgrade successs.\n 2. Force install the FPD types that need upgrade on all locations.\n Check FPD related sys log to make sure all necessary upgrades\n defined by the dictionary complete successfully.\n\n :param fpd_relevant_nodes: a dictionary. Keys are strings representing all node locations\n on device parsed from output of \"admin show platform\".\n Values are integers. Value can either be 0 or 1.\n value 1 means that we actually will need to make sure that the\n FPD upgrade later on for this node location completes successfully,\n value 0 means that we don't need to check if the\n FPD upgrade later on for this node location is successful or not.\n\n :return: True if no error occurred.\n \"\"\"\n # check for the FPD version, if FPD needs upgrade,\n log_and_post_status(self.ctx, \"Checking FPD versions...\")\n subtype_to_locations_need_upgrade = self._check_fpd(fpd_relevant_nodes)\n\n if subtype_to_locations_need_upgrade:\n\n # Force upgrade all FPD's in RP and Line card that need upgrade, with the FPD pie or both the FPD\n # pie and FPD SMU depending on release version\n self._upgrade_all_fpds(subtype_to_locations_need_upgrade)\n\n return True\n\n def _upgrade_all_fpds(self, subtype_to_locations_need_upgrade):\n \"\"\"Force upgrade certain FPD's on all locations. Check for success. \"\"\"\n def send_newline(ctx):\n ctx.ctrl.sendline()\n return True\n\n def send_yes(ctx):\n ctx.ctrl.sendline(\"yes\")\n return True\n\n def error(ctx):\n ctx.message = \"Error upgrading FPD.\"\n return False\n\n def timeout(ctx):\n ctx.message = \"Timeout upgrading FPD.\"\n return False\n\n for fpdtype in subtype_to_locations_need_upgrade:\n\n log_and_post_status(self.ctx, \"FPD upgrade - start to upgrade FPD {} on all locations\".format(fpdtype))\n\n CONFIRM_CONTINUE = re.compile(r\"Continue\\? \\[confirm\\]\")\n CONFIRM_SECOND_TIME = re.compile(r\"Continue \\? \\[no\\]:\")\n UPGRADE_END = re.compile(r\"FPD upgrade has ended.\")\n\n PROMPT = self.ctx.prompt\n TIMEOUT = self.ctx.TIMEOUT\n\n events = [PROMPT, CONFIRM_CONTINUE, CONFIRM_SECOND_TIME, UPGRADE_END, TIMEOUT]\n transitions = [\n (CONFIRM_CONTINUE, [0], 1, send_newline, TIMEOUT_FOR_FPD_UPGRADE),\n (CONFIRM_SECOND_TIME, [0, 1], 2, send_yes, TIMEOUT_FOR_FPD_UPGRADE),\n (UPGRADE_END, [1, 2], 3, None, 120),\n (PROMPT, [3], -1, None, 0),\n (PROMPT, [1, 2], -1, error, 0),\n (TIMEOUT, [0, 1, 2], -1, timeout, 0),\n\n ]\n\n if not self.ctx.run_fsm(\"Upgrade FPD\",\n \"admin upgrade hw-module fpd {} location all\".format(fpdtype),\n events, transitions, timeout=80):\n self.ctx.error(\"Error while upgrading FPD subtype {}. Please check session.log\".format(fpdtype))\n\n fpd_log = self.ctx.send(\"show log | include fpd\", timeout=1800)\n\n for location in subtype_to_locations_need_upgrade[fpdtype]:\n\n pattern = r\"Successfully\\s*(?:downgrade|upgrade)\\s*{}.*location\\s*{}\".format(fpdtype, location)\n fpd_upgrade_success = re.search(pattern, fpd_log)\n\n if not fpd_upgrade_success:\n self.ctx.error(\"Failed to upgrade FPD subtype {} on location {}. \".format(fpdtype, location) +\n \"Please check session.log.\")\n return True\n\n def _create_config_logs(self, csvfile, supported_log_name, unsupported_log_name, hostname, filename):\n \"\"\"\n Create two logs for migrated configs that are unsupported and supported by eXR.\n They are stored in the same directory as session log, for user to view.\n\n :param csvfile: the string csv filename generated by running NoX on original config.\n :param supported_log_name: the string filename for the supported configs log\n :param unsupported_log_name: the string filename for the unsupported configs log\n :param hostname: string hostname of device, as recorded on CSM.\n :param filename: string filename of original config\n :return: None if no error occurred\n \"\"\"\n\n if not os.path.isfile(os.path.join(csvfile)):\n self.ctx.error(\"Missing the csv file {} that should have been generated by the NoX tool\".format(csvfile) +\n \" during the configuration conversion. Failed to write diagnostic files.\")\n supported_config_log = os.path.join(self.ctx.log_directory, supported_log_name)\n unsupported_config_log = os.path.join(self.ctx.log_directory, unsupported_log_name)\n try:\n with open(supported_config_log, 'w') as supp_log:\n with open(unsupported_config_log, 'w') as unsupp_log:\n supp_log.write('Configurations Known and Supported to the NoX Conversion Tool \\n \\n')\n\n unsupp_log.write('Configurations Unprocessed by the NoX Conversion Tool (Comments, Markers,' +\n ' or Unknown/Unsupported Configurations) \\n \\n')\n\n supp_log.write('{0[0]:<8} {0[1]:^20} \\n'.format((\"Line No.\", \"Configuration\")))\n unsupp_log.write('{0[0]:<8} {0[1]:^20} \\n'.format((\"Line No.\", \"Configuration\")))\n with open(csvfile, 'rb') as csvfile:\n reader = csv.reader(csvfile)\n for row in reader:\n if len(row) >= 3 and row[1].strip() == \"KNOWN_SUPPORTED\":\n supp_log.write('{0[0]:<8} {0[1]:<} \\n'.format((row[0], row[2])))\n elif len(row) >= 3:\n unsupp_log.write('{0[0]:<8} {0[1]:<} \\n'.format((row[0], row[2])))\n\n msg = \"\\n \\nPlease find original configuration in csm_data/migration/{}/{} \\n\".format(hostname,\n filename)\n supp_log.write(msg)\n unsupp_log.write(msg)\n if filename.split('.')[0] == 'admin':\n msg2 = \"The final converted configuration is in csm_data/migration/\" + \\\n hostname + \"/\" + CONVERTED_ADMIN_CAL_CONFIG_IN_CSM + \\\n \" and csm_data/migration/\" + hostname + \"/\" + CONVERTED_ADMIN_XR_CONFIG_IN_CSM\n else:\n msg2 = \"The final converted configuration is in csm_data/migration/\" + \\\n hostname + \"/\" + CONVERTED_XR_CONFIG_IN_CSM\n supp_log.write(msg2)\n unsupp_log.write(msg2)\n csvfile.close()\n unsupp_log.close()\n supp_log.close()\n except:\n self.ctx.error(\"Error writing diagnostic files - in \" + self.ctx.log_directory +\n \" during configuration migration.\")\n\n def _filter_server_repository(self, server):\n \"\"\"Filter out LOCAL server repositories and only keep TFTP, FTP and SFTP\"\"\"\n if not server:\n self.ctx.error(\"Pre-Migrate missing server repository object.\")\n if server.server_type != ServerType.FTP_SERVER and server.server_type != ServerType.TFTP_SERVER and \\\n server.server_type != ServerType.SFTP_SERVER:\n self.ctx.error(\"Pre-Migrate does not support \" + server.server_type + \" server repository.\")\n\n def _save_config_to_csm_data(self, files, admin=False):\n \"\"\"\n Copy the admin configuration or IOS-XR configuration\n from device to csm_data.\n\n :param files: the full local file paths for configs.\n :param admin: True if asking for admin config, False otherwise.\n :return: None\n \"\"\"\n\n try:\n cmd = \"admin show run\" if admin else \"show run\"\n output = self.ctx.send(cmd, timeout=TIMEOUT_FOR_COPY_CONFIG)\n init_line = 'Building configuration...'\n ind = output.rfind(init_line)\n\n except pexpect.TIMEOUT:\n self.ctx.error(\"CLI '{}' timed out after 1 hour.\".format(cmd))\n\n for file_path in files:\n # file = '../../csm_data/migration/' + filename\n file_to_write = open(file_path, 'w+')\n if ind >= 0:\n file_to_write.write(output[(ind + len(init_line)):])\n else:\n file_to_write.write(output)\n file_to_write.close()\n\n def _handle_configs(self, hostname, server, repo_url, fileloc, nox_to_use, config_filename):\n \"\"\"\n 1. Copy admin and XR configs from device to TFTP/FTP/SFTP server repository.\n 2. Copy admin and XR configs from server repository to csm_data/migration//\n 3. Copy admin and XR configs from server repository to session log directory as\n show-running-config.txt and admin-show-running-config.txt for comparisons\n after Migrate or Post-Migrate. (Diff will be generated.)\n 4. Run NoX on admin config first. This run generates 1) eXR admin/calvados config\n and POSSIBLY 2) eXR XR config.\n 5. Run NoX on XR config if no custom eXR config has been selected by user when\n Pre-Migrate is scheduled. This run generates eXR XR config.\n 6. Merge either the selected eXR custom config or the converted XR config with the converted\n eXR XR config to form a new file - cXR_xr_plane_converted_eXR.cfg\n 7. Copy the eXR admin/calvados config and the cXR_xr_plane_converted_eXR.cfg to the server\n repository and then from there to device.\n Note if user selected custom eXR XR config, that will be uploaded instead of\n the NoX migrated original XR config.\n\n :param hostname: string hostname of device, as recorded on CSM.\n :param repo_url: the URL of the selected server repository. i.e., tftp://223.255.254.245/tftpboot\n :param fileloc: the string path ../../csm_data/migration/\n :param nox_to_use: the name of the NoX binary executable\n :param config_filename: the user selected string filename of custom eXR XR config.\n If it's '', nothing was selected.\n If selected, this file must be in the server repository.\n :return: None if no error occurred.\n \"\"\"\n\n log_and_post_status(self.ctx, \"Cleaning up previously saved configuration files for this host in csm_data\")\n for old_file in os.listdir(fileloc):\n try:\n os.remove(os.path.join(fileloc, old_file))\n except:\n self.ctx.warning(\"Failed to remove the old configuration conversion file \" +\n \"{}\".format(os.path.join(fileloc, old_file)))\n pass\n\n log_and_post_status(self.ctx, \"Saving the current configurations on device into server repository and csm_data\")\n\n self._save_config_to_csm_data([os.path.join(fileloc, ADMIN_CONFIG_IN_CSM),\n os.path.join(self.ctx.log_directory,\n self.ctx.normalize_filename(\"admin show running-config\"))\n ], admin=True)\n\n self._save_config_to_csm_data([os.path.join(fileloc, XR_CONFIG_IN_CSM),\n os.path.join(self.ctx.log_directory,\n self.ctx.normalize_filename(\"show running-config\"))\n ], admin=False)\n\n log_and_post_status(self.ctx, \"Converting admin configuration file with configuration migration tool\")\n self._run_migration_on_config(fileloc, ADMIN_CONFIG_IN_CSM, nox_to_use, hostname)\n\n # [\"admin.cal\"]\n config_files = [CONVERTED_ADMIN_CAL_CONFIG_IN_CSM]\n # [\"cXR_admin_plane_converted_eXR.cfg\"]\n config_names_on_device = [FINAL_CAL_CONFIG]\n if not config_filename:\n\n log_and_post_status(self.ctx, \"Converting IOS-XR configuration file with configuration migration tool\")\n self._run_migration_on_config(fileloc, XR_CONFIG_IN_CSM, nox_to_use, hostname)\n\n # admin.iox and xr.iox\n files_to_merge = [os.path.join(fileloc, CONVERTED_ADMIN_XR_CONFIG_IN_CSM),\n os.path.join(fileloc, CONVERTED_XR_CONFIG_IN_CSM)]\n\n with open(os.path.join(fileloc, FINAL_XR_CONFIG), 'w') as merged_file:\n for fname in files_to_merge:\n with open(fname) as infile:\n for line in infile:\n merged_file.write(line)\n\n # \"cXR_xr_plane_converted_eXR.cfg\" - product of files_to_merge, merging will be done\n config_files.append(FINAL_XR_CONFIG)\n # \"cXR_xr_plane_converted_eXR.cfg\"\n config_names_on_device.append(FINAL_XR_CONFIG)\n\n log_and_post_status(self.ctx, \"Uploading the migrated configuration files to server repository and device.\")\n\n config_names_in_repo = [hostname + \"_\" + config_name for config_name in config_files]\n\n if self._upload_files_to_server_repository([os.path.join(fileloc, config_name)\n for config_name in config_files],\n server, config_names_in_repo):\n\n if config_filename:\n config_names_in_repo.append(config_filename)\n # \"cXR_xr_plane_converted_eXR.cfg\"\n config_names_on_device.append(FINAL_XR_CONFIG)\n\n self._copy_files_to_device(server, repo_url, config_names_in_repo,\n [CONFIG_LOCATION + config_name\n for config_name in config_names_on_device],\n timeout=TIMEOUT_FOR_COPY_CONFIG)\n\n def _get_packages(self, packages):\n \"\"\"Find out which package is eXR tar file, which is crypto_auto_key_gen.txt\"\"\"\n if len(packages) > 2:\n self.ctx.error(\"More than two packages are selected, however, only the ASR9K IOS XR 64 Bit tar file and the crypto key generation file should be selected.\")\n if len(packages) == 0:\n self.ctx.error(\"No ASR9K IOS XR 64 Bit tar file selected for Pre-Migrate.\")\n image_pattern = re.compile(r\"asr9k.*\\.tar.*\")\n exr_tar = None\n crypto_file = None\n for package in packages:\n if image_pattern.match(package):\n exr_tar = package\n else:\n crypto_file = package\n return exr_tar, crypto_file\n\n def _find_nox_to_use(self):\n \"\"\"\n Find out if the linux system is 32 bit or 64 bit. NoX currently only has a binary executable\n compiled for 64 bit.\n \"\"\"\n check_32_or_64_system = subprocess.Popen(['uname', '-a'], stdout=subprocess.PIPE)\n\n out, err = check_32_or_64_system.communicate()\n\n if err:\n self.ctx.error(\"Failed to execute 'uname -a' on the linux system.\")\n\n if \"x86_64\" in out:\n return NOX_64_BINARY\n else:\n self.ctx.error(\"The configuration migration tool NoX is currently not available for 32 bit linux system.\")\n\n def run(self):\n\n server_repo_url = None\n try:\n server_repo_url = self.ctx.server_repository_url\n except AttributeError:\n pass\n\n if server_repo_url is None:\n self.ctx.error(\"No repository provided.\")\n\n try:\n packages = self.ctx.software_packages\n except AttributeError:\n self.ctx.error(\"No package list provided\")\n\n config_filename_tuple = self.ctx.load_job_data('config_filename')\n if config_filename_tuple:\n config_filename = config_filename_tuple[0]\n\n server = None\n try:\n server = self.ctx.get_server\n except AttributeError:\n self.ctx.error(\"No server repository selected\")\n\n if server is None:\n self.ctx.error(\"No server repository selected\")\n\n if not self.ctx.load_job_data('override_hw_req'):\n self.ctx.error(\"Missing indication of whether to override hardware requirement or not.\")\n\n exr_image, crypto_file = self._get_packages(packages)\n\n version_match = re.findall(r\"\\d+\\.\\d+\\.\\d+\", exr_image)\n if version_match:\n exr_version = version_match[0]\n else:\n self.ctx.error(\"The selected tar file is missing release number in its filename.\")\n\n self._filter_server_repository(server)\n\n hostname_for_filename = re.sub(r\"[()\\s]\", \"_\", self.ctx._csm.host.hostname)\n hostname_for_filename = re.sub(r\"_+\", \"_\", hostname_for_filename)\n\n fileloc = self.ctx.migration_directory + hostname_for_filename\n\n if not os.path.exists(fileloc):\n os.makedirs(fileloc)\n\n self.ctx.save_job_data('hardware_audit_version', exr_version)\n hardware_audit_plugin = HardwareAuditPlugin(self.ctx)\n hardware_audit_plugin.run()\n\n fpd_relevant_nodes_tuple = self.ctx.load_job_data('fpd_relevant_nodes')\n if fpd_relevant_nodes_tuple:\n fpd_relevant_nodes = fpd_relevant_nodes_tuple[0]\n else:\n self.ctx.error(\"No data field fpd_relevant_nodes after completing hardware audit successfully.\")\n\n log_and_post_status(self.ctx, \"Checking current software version.\")\n\n match_version = re.search(r\"(\\d\\.\\d\\.\\d).*\", self.ctx.os_version)\n\n if not match_version:\n self.ctx.error(\"Bad os_version.\")\n\n version = match_version.group(1)\n\n if compare_version_numbers(version, MINIMUM_RELEASE_VERSION_FOR_MIGRATION) < 0:\n self.ctx.error(\"The minimal release version required for migration is {0}. Please upgrade to at lease {0} before scheduling migration.\".format(MINIMUM_RELEASE_VERSION_FOR_MIGRATION))\n\n # log_and_post_status(self.ctx, \"Testing ping to selected server repository IP.\")\n # self._ping_repository_check(server_repo_url)\n\n log_and_post_status(self.ctx, \"Checking if FPD package is active on device.\")\n self._check_if_fpd_package_installed()\n\n nox_to_use = self.ctx.migration_directory + self._find_nox_to_use()\n\n if not os.path.isfile(nox_to_use):\n self.ctx.error(\"The configuration conversion tool {} is missing. \".format(nox_to_use) +\n \"CSM should have downloaded it from CCO when migration actions were scheduled.\")\n\n self._save_show_platform()\n\n log_and_post_status(self.ctx, \"Partition check and disk clean-up.\")\n self._resize_eusb()\n\n self._handle_configs(hostname_for_filename, server,\n server_repo_url, fileloc, nox_to_use, config_filename)\n\n log_and_post_status(self.ctx, \"Copying the ASR9K-X64 image from server repository to device.\")\n self._copy_files_to_device(server, server_repo_url, [exr_image],\n [IMAGE_LOCATION + exr_image], timeout=TIMEOUT_FOR_COPY_IMAGE)\n\n if crypto_file:\n log_and_post_status(self.ctx, \"Copying the crypto key generation file from server repository to device.\")\n self._copy_files_to_device(server, server_repo_url, [crypto_file],\n [CONFIG_LOCATION + CRYPTO_KEY_FILENAME], timeout=600)\n\n self._ensure_updated_fpd(fpd_relevant_nodes)\n\n # Refresh package and inventory information\n get_package(self.ctx)\n get_inventory(self.ctx)\n\n return True\n","sub_path":"csmpe/core_plugins/csm_install_operations/ios_xr/pre_migrate.py","file_name":"pre_migrate.py","file_ext":"py","file_size_in_byte":49662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"401252875","text":"# -*- coding: UTF-8 -*-\n# осортировка файлов, файловыми ключами\n\nimport itertools\n\nimport tkinter.ttk as ttk\n\nimport lr_lib.gui.wrsp.win_maxmin\nimport lr_lib.core.var.vars as lr_vars\n\n\nclass WinFileSort(lr_lib.gui.wrsp.win_maxmin.WinMaxMin):\n \"\"\"сортировка файлов, файловыми ключами\"\"\"\n def __init__(self):\n lr_lib.gui.wrsp.win_maxmin.WinMaxMin.__init__(self)\n\n self.sortKey1 = ttk.Combobox(\n self.last_frame, textvariable=lr_vars.VarFileSortKey1, justify='center', width=10,\n font=lr_vars.DefaultFont + ' italic', style=\"BW.TButton\")\n\n self.sortKey2 = ttk.Combobox(\n self.last_frame, textvariable=lr_vars.VarFileSortKey2, justify='center',\n font=lr_vars.DefaultFont + ' italic', style=\"BW.TButton\")\n\n self.sortKey1.bind(\"<>\", self.setSortKey1)\n self.sortKey2.bind(\"<>\", self.setSortKey2)\n return\n\n def setSortKeys(self) -> None:\n \"\"\"задать комбо(1/2) сортировки\"\"\"\n k1 = set(k for f in lr_vars.AllFiles for k in f)\n self.sortKey1['values'] = sorted(k for k in k1 if (not ((k[0] == 't') and all(map(str.isnumeric, k[1:])))))\n self.sortKey1.set(lr_vars.VarFileSortKey1.get())\n self.setSortKey1()\n\n self.sortKey2.set(lr_vars.VarFileSortKey2.get())\n return\n\n def setSortKey1(self, *args) -> None:\n \"\"\"комбо сортировки 1\"\"\"\n lr_vars.VarFileSortKey1.set(self.sortKey1.get())\n s = set(k for f in itertools.chain(lr_vars.AllFiles, lr_vars.FilesWithParam)\n for k in f.get(self.sortKey1.get(), ()))\n\n self.sortKey2['values'] = list(s)\n self.sortKey2.set('')\n return\n\n def setSortKey2(self, *args) -> None:\n \"\"\"комбо сортировки файлов\"\"\"\n lr_vars.VarFileSortKey2.set(self.sortKey2.get())\n if lr_vars.FilesWithParam:\n self.get_files() # сортировка при поиске\n return\n","sub_path":"lr_lib/gui/wrsp/win_filesort.py","file_name":"win_filesort.py","file_ext":"py","file_size_in_byte":2080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"450795674","text":"import os, string\n\nschool = raw_input(\"School abbreviation? \")\nseason = str(raw_input('Season (e.g., \"2017 Fall\")? '))\ndate = raw_input(\"Shoot date? \")\nnum_img = int(raw_input(\"How many images of each child? \"))\n\nfile_to_write = \"/Users/eddieatkinson/Desktop/%s.csv\" % (school)\n\ngroup = 1\ngroups = [] # numbers to group images\n# list_from_file = os.listdir(\"/Users/eddieatkinson/Desktop/%s/%s/%s Exports\" % (season, school, school))\nlist_from_file = os.listdir(\"/Users/eddieatkinson/Desktop/%s/%s/%s Exports\" % (season, school, school))\nfile_names = [] # names of the jpgs\nnew_file_names = [] # the final list\njust_first_names = []\nfor item in list_from_file:\n\tif \".jpg\" or \".JPG\" in item: # make sure we only have jpgs\n\t\tfile_names.append(item)\nfor item in file_names:\n\tnew_item = item.replace(\".JPG\", \".jpg\") # in case caps are used in extension\n\tnew_item = item.replace(\".jpg\", \"\") # remove the extension\n\tnewer_item = new_item.replace(\" \", \",\", 1) # remove first space (class prefix)\n\tnewest_item = newer_item.rstrip(\"-0123456789\") # remove numbers and dash from end\n\tnew_file_names.append(newest_item)\nfor j in range (0, len(new_file_names)):\n\tjust_first_names.append(new_file_names[j].split(',', 1)[-1])\nfor k in range (0, len(just_first_names)):\n\tif k == 0:\n\t\tgroups.append(group)\n\telif just_first_names[k] != just_first_names[k - 1]:\n\t\tgroup += 1\n\t\tgroups.append(group)\n\telse:\n\t\tgroups.append(group)\nfor i in set(new_file_names):\n\tif (4 * num_img + 1) > new_file_names.count(i) >= (3 * num_img + 1): # if there are more than 6, for multiple proofs\n\t\ti += \"_II\" # add a _II to the name, so it won't get erased\n\t\tnew_file_names.append(i)\n\t\ti += \"I\" \n\t\tnew_file_names.append(i)\n\t\ti += \"I\" \n\t\tnew_file_names.append(i)\n\tif (3 * num_img + 1) > new_file_names.count(i) >= (2 * num_img + 1):\n\t\ti += \"_II\" \n\t\tnew_file_names.append(i)\n\t\ti += \"I\" \n\t\tnew_file_names.append(i)\n\tif new_file_names.count(i) >= (num_img + 1):\n\t\ti += \"_II\"\n\t\tnew_file_names.append(i)\nnew_list = list(set(new_file_names)) # change it back to a list\nnew_list_sorted = sorted(new_list) # put it in alphabetical order\nthe_file = open(file_to_write, \"w\")\nfor item in new_list_sorted:\n\tthe_file.write(\"%s\\n\" % item)\nimage_data_file = open(\"/Users/eddieatkinson/Desktop/%s/%s.txt\" % (season, school), \"w\")\nimage_data_file.write(\"Filename,FirstName,LastName,FullName,GroupTest,Class,Packages,ShootDate,SchoolName\\n\")\nfor i in range (0, len(file_names)):\n\timage_data_file.write(\"%s,%s,,%s ,%d,,,%s,%s\\n\" % (file_names[i], just_first_names[i], just_first_names[i], groups[i], date, school))","sub_path":"CPQ_image_csv.py","file_name":"CPQ_image_csv.py","file_ext":"py","file_size_in_byte":2554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"142155580","text":"import numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\n\nfrom Line import Line\n\n\ndef segment_lines(bw_img):\n # Calculates bounding boxes for all lines of text inside of image\n \n # Invert binary so text is 1s \n bw_inv = cv2.bitwise_not(bw_img)\n \n # dilate to glue individual lines together\n kernel = np.ones((5,50), np.uint8) #for post-its\n dilated_img = cv2.dilate(bw_inv, kernel, iterations=1)\n \n # Get contours and sort by bounding box length\n im2, ctrs, hier = cv2.findContours(dilated_img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n #sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[1])\n \n lines = []\n for i, ctr in enumerate(ctrs):\n # Get bounding box\n x, y, w, h = cv2.boundingRect(ctr)\n if w * h > 5000:\n # Getting line image\n line_img = bw_img[y:y+h, x:x+w]\n lines.append(Line(line_img, i)) # append line object\n \n return lines\n \n \n ","sub_path":"src/line_segmentation.py","file_name":"line_segmentation.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"470815977","text":"#!/usr/bin/env python3.5\n# -*- coding: utf-8 -*-\nimport bisect\nimport gmpy2\nimport primesieve\n\n\ndef factorial(n):\n def product(s, n, m):\n if (n > m):\n return 1\n if (n == m):\n return s[n]\n k = (n + m) // 2\n return product(s, n, k) * product(s, k + 1, m)\n\n def swing(m, primes):\n if m < 4:\n return [1, 1, 1, 3][m]\n s = bisect.bisect_left(primes, 1 + gmpy2.isqrt(m))\n d = bisect.bisect_left(primes, 1 + m // 3)\n e = bisect.bisect_left(primes, 1 + m // 2)\n g = bisect.bisect_left(primes, 1 + m)\n\n factors = primes[e:g]\n factors += filter(lambda x: (m // x) & 1 == 1, primes[s:d])\n for prime in primes[1:s]:\n p, q = 1, m\n while True:\n q //= prime\n if q == 0:\n break\n if q & 1 == 1:\n p *= prime\n if p > 1:\n factors.append(p)\n return product(factors, 0, len(factors) - 1)\n\n def odd_factorial(n, primes):\n if n < 2:\n return 1\n return((odd_factorial(n // 2, primes)**2) * swing(n, primes))\n\n def eval(n):\n if n < 10:\n return product(range(2, n + 1), 0, n - 2)\n bits = n - gmpy2.popcount(n)\n primes = primesieve.generate_primes(2, n + 1)\n return odd_factorial(n, primes) * 2 ** bits\n return eval(n)\n","sub_path":"PythonFactorial/primeswing.py","file_name":"primeswing.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"527209170","text":"\"\"\"\nBecause of the complicated and highly integrated relationship between views,\nresources, and requests when resolving an action, the Stackcite API relies on\nspecial test cases to create standard, predictable test conditions.\n\"\"\"\n\nimport unittest\n\nfrom pyramid import testing\n\nfrom stackcite.api import resources\n\n\nclass BaseViewTestCase(unittest.TestCase):\n \"\"\"\n A base test case designed to coordinate the instantiation of an explicitly\n defined ``VIEW_CLASS`` with a default :class:`~IndexResource` and\n :class:`~DummyRequest`.\n \"\"\"\n\n #: The view class under test (should be defined in unit test case).\n VIEW_CLASS = NotImplemented\n\n #: A resource class associated with the view class under test.\n RESOURCE_CLASS = resources.IndexResource\n\n #: A dummy request class.\n REQUEST_CLASS = testing.DummyRequest\n\n def make_view(self, name=None):\n \"\"\"\n Creates an instance of the view class under test along with associated\n context and request objects.\n\n :return: An instance of ``VIEW_CLASS``\n \"\"\"\n name = name or str(self.RESOURCE_CLASS)\n context = self.RESOURCE_CLASS(None, name)\n request = self.REQUEST_CLASS()\n view = self.VIEW_CLASS(context, request)\n return view\n\n\nclass APIViewTestCase(BaseViewTestCase):\n \"\"\"\n An alternate version of :class:`~BaseViewTestCase` for testing API view\n classes.\n \"\"\"\n\n RESOURCE_CLASS = resources.APIIndexResource\n\n\nclass ExceptionViewTestCase(unittest.TestCase):\n \"\"\"\n An alias of :class:`~BaseViewTestCase` used specifically to test exception\n contexts (e.g. :class:`APIValidationError`).\n \"\"\"\n EXCEPTION_CLASS = NotImplemented\n VIEW_CLASS = NotImplemented\n REQUEST_CLASS = testing.DummyRequest\n\n def make_view(self):\n context = self.EXCEPTION_CLASS()\n request = self.REQUEST_CLASS()\n view = self.VIEW_CLASS(context, request)\n return view\n\n\nclass CollectionViewTestCase(BaseViewTestCase):\n \"\"\"\n An alias for :class:`.BaseViewTestCase` used specifically to test\n collection endpoint view classes.\n \"\"\"\n\n\nclass DocumentViewTestCase(BaseViewTestCase):\n \"\"\"\n A modified version of :class:`~CollectionViewTestCase` used specifically\n to test view classes associated with specific documents in a collection.\n \"\"\"\n\n def make_view(self, object_id=None, parent_name=None):\n \"\"\"\n Creates an instance of the view class under test along with associated\n context and request objects. Specifically, this method will use the\n resource defined by ``RESOURCE_CLASS`` as a parent, and mock a\n traversal resolution for a :class:`bson.ObjectId`.\n\n Note: This method will randomly generate a :class:`bson.ObjectId`\n to fill in ``object_id`` if nothing is provided.\n\n :param object_id: A target :class:`bson.ObjectId` string\n :param parent_name: The parent resource name\n :return: An instance of ``VIEW_CLASS``\n \"\"\"\n parent_name = parent_name or str(self.RESOURCE_CLASS)\n # Generate a new ObjectId if one was not provided:\n if not object_id:\n from bson import ObjectId\n object_id = str(ObjectId())\n # Assemble and return the view:\n parent = self.RESOURCE_CLASS(None, parent_name)\n context = parent[object_id]\n request = testing.DummyRequest()\n view = self.VIEW_CLASS(context, request)\n return view\n","sub_path":"stackcite/api/testing/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"141179377","text":"import xgboost as xgb\r\nimport numpy as np\r\n\r\nclass XGBOOST_STACKER():\r\n def __init__(self, _subsample, _colsample_bytree, _max_depth, _min_child_weight,\r\n _eta, _lambda, _num_round,_nthread, _objective, _booster):\r\n self.subsample = _subsample\r\n self.objective = _objective\r\n self.booster = _booster\r\n self.colsample_bytree = _colsample_bytree\r\n self.max_depth = _max_depth\r\n self.min_child_weight = _min_child_weight\r\n self.eta = _eta\r\n self.reg_lambda = _lambda\r\n self.num_round = _num_round\r\n self.nthread = _nthread\r\n\r\n\r\n def fit(self,X,y):\r\n dtrain = xgb.DMatrix(X,y)\r\n params_xgb = {\r\n \"eta\": self.eta,\r\n \"objective\": self.objective,\r\n \"booster\": self.booster,\r\n \"max_depth\": int(self.max_depth),\r\n \"min_child_weight\": self.min_child_weight,\r\n \"subsample\": self.subsample,\r\n \"colsample_bytree\": self.colsample_bytree,\r\n \"lambda\": self.reg_lambda,\r\n \"eval_metric\": \"mae\",\r\n \"nthread\": self.nthread,\r\n \"silent\": 0,\r\n }\r\n\r\n def logregobj(preds, dtrain):\r\n labels = dtrain.get_label()\r\n con = 2\r\n x = preds - labels\r\n grad = con * x / (np.abs(x) + con)\r\n hess = con ** 2 / (np.abs(x) + con) ** 2\r\n return grad, hess\r\n\r\n def evalerror(preds, dtrain):\r\n labels = dtrain.get_label()\r\n return 'mae', mean_absolute_error(np.exp(preds), np.exp(labels))\r\n\r\n self.model = xgb.train(params_xgb,\r\n dtrain, num_boost_round=self.num_round,\r\n obj=logregobj,\r\n feval=evalerror)\r\n\r\n def predict(self,X):\r\n dtest = xgb.DMatrix(X)\r\n if self.booster == 'gblinear':\r\n return self.model.predict(dtest)\r\n return self.model.predict(dtest, ntree_limit = self.num_round)","sub_path":"Stacker/xgboost_stacker.py","file_name":"xgboost_stacker.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"216679272","text":"from django.conf import settings\nfrom django.core.exceptions import ViewDoesNotExist\nfrom django.template import TemplateDoesNotExist\nfrom django.views.generic import View\n\nfrom .router_class import ClassBasedRouter\nfrom .router_exception import RegistryExceptionRouter\nfrom .router_function import ViewFunctionRouter\nfrom .router_template import TemplateViewRouter\n\nfrom .decorators import view_function\n\nimport inspect\nimport threading\nfrom importlib import import_module\nfrom importlib.util import find_spec\n\n\n\n\n########################################################\n### Cached routers\n\nCACHED_ROUTERS = {}\nrlock = threading.RLock()\n\ndef get_router(module_name, function_name, fallback_app=None, fallback_template=None, verify_decorator=True):\n '''\n Gets or creates a mini-router for module_name.function_name.\n If the module or function cannot be found, ViewDoesNotExist is raised.\n '''\n # first check the cache\n key = ( module_name, function_name )\n try:\n return CACHED_ROUTERS[key]\n except KeyError:\n with rlock:\n # try again now that we're locked\n try:\n return CACHED_ROUTERS[key]\n except KeyError:\n func = router_factory(module_name, function_name, fallback_app, fallback_template, verify_decorator)\n if not settings.DEBUG: # only cache in production mode\n CACHED_ROUTERS[key] = func\n return func\n\n # the code should never be able to get here\n raise Exception(\"Django-Mako-Plus error: registry.get_router() should not have been able to get to this point. Please notify the owner of the DMP project. Thanks.\")\n\n\n\n############################################################\n### Creates the appropriate router for a\n### view function, class-based view function,\n### template, or error.\n\ndef router_factory(module_name, function_name, fallback_app=None, fallback_template=None, verify_decorator=True):\n '''\n Factory method to create a view-specific router in the system.\n See the four mini-routers at the end of this file.\n '''\n try:\n # I'm first calling find_spec first here beacuse I don't want import_module in\n # a try/except -- there are lots of reasons that importing can fail, and I just want to\n # know whether the file actually exists. find_spec raises AttributeError if not found.\n try:\n spec = find_spec(module_name)\n except ValueError:\n spec = None\n if spec is None:\n # no view module, can we call the template directly?\n try:\n return TemplateViewRouter(fallback_app, fallback_template)\n except TemplateDoesNotExist as e:\n raise ViewDoesNotExist('View module {} not found, and fallback template {} could not be loaded ({})'.format(module_name, fallback_template, e))\n\n # load the module and function\n try:\n module = import_module(module_name)\n func = getattr(module, function_name)\n except ImportError as e:\n raise ViewDoesNotExist('Module \"{}\" could not be imported: {}'.format(module_name, e))\n except AttributeError as e:\n raise ViewDoesNotExist('Module \"{}\" found successfully, but \"{}\" was not found: {}'.format(module_name, function_name, e))\n\n # class-based view?\n if inspect.isclass(func) and issubclass(func, View):\n # must do func() to instantiate because func is class (not a function)\n return ClassBasedRouter(module, func())\n\n # a view function?\n if verify_decorator and not view_function._is_decorated(func):\n raise ViewDoesNotExist(\"View {}.{} was found successfully, but it must be decorated with @view_function or be a subclass of django.views.generic.View.\".format(module_name, function_name))\n return ViewFunctionRouter(module, func)\n\n except ViewDoesNotExist as vdne:\n return RegistryExceptionRouter(vdne)\n","sub_path":"django_mako_plus/router/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":4005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"139409087","text":"# Прикажите вашим войскам двигаться на восток и атаковать любых огров которых они увидят.\n# Используйте for циклы и findFriends.\n# Вы можете использовать метод findNearestEnemy() на Ваших солдатах, для того, чтобы находить ближайшего к ним, а не к себе, противника.\nindex = 0\nwhile True:\n friends = self.findFriends()\n enemy = self.findNearest(self.findEnemies())\n if enemy and self.distanceTo(enemy) < 20:\n if (self.isReady(\"jump\") and self.distanceTo(enemy) > 10):\n self.jumpTo(enemy.pos)\n elif (self.isReady(\"cleave\")):\n self.cleave(enemy)\n elif (self.isReady(\"bash\")):\n self.bash(enemy)\n elif (self.isReady(\"power-up\")):\n self.powerUp()\n self.attack(enemy)\n else:\n self.attack(enemy)\n else:\n if (self.now() < 7):\n pos = {'x': 87, 'y': 49}\n else:\n pos = {'x': 12, 'y': 47}\n if (self.isReady(\"jump\")):\n self.jumpTo(pos)\n else:\n self.move(pos)\n for j in range(len(friends)):\n friend = friends[j]\n if (friend.pos.y > 46 and self.now() < 5):\n pos = {'x': 12, 'y': 64}\n elif (friend.pos.y > 46):\n if (friend.type != 'archer'):\n pos = {'x': 61, 'y': 67}\n else:\n pos = {'x': 42, 'y': 67}\n else:\n if (friend.type != 'archer'):\n pos = {'x': 45, 'y': 32}\n else:\n pos = {'x': 51, 'y': 32}\n enemy = friend.findNearestEnemy()\n if (friend.health < 29 or (enemy and friend.type == 'archer' and friend.distanceTo(enemy) < 22)):\n self.command(friend, 'move', {'x': 11, 'y': 47})\n elif enemy and friend.distanceTo(enemy) < 20:\n self.command(friend, 'attack', enemy)\n else:\n self.command(friend, 'move', pos)\n","sub_path":"Mountain/HuntingParty.py","file_name":"HuntingParty.py","file_ext":"py","file_size_in_byte":2068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"230585926","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n__author__ = 'Kabir Abdulhamid / Upwork'\n\n# REQUIRED PACKAGES & INPUTS\n\n# selenium : pip3 install -U selenium (to get pip: sudo apt-get install python3-pip)\n\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.common import exceptions as EX\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.common.keys import Keys\n\nimport argparse\nimport re\nimport os\nimport time\n\nfrom lxml import html\n\nimport CommonFunctions\n\n# ------------------------------------------------- Globals -----------------------------------------------------\ng_url = 'http://www.pagesjaunes.fr/'\ng_PagesJaunesDir = './PagesJaunes/'\n\n# ------------------------------------------------- Function ----------------------------------------------------\ndef killPopup(p_driver):\n # \n # \n # Fermer\n # \n try:\n p_driver.find_element_by_xpath('//a[@class=\"pjpopin-closer\"]').click()\n return True\n except EX.NoSuchElementException:\n print('No popup (A) ...')\n\n # \n try:\n p_driver.find_element_by_xpath('//button[@class=\"kclose kbutton button primary large-button\"]').click()\n return True\n except EX.NoSuchElementException:\n print('No popup (B) ...')\n\n return False\n\ndef doSearch(p_search, p_location, p_pathA, p_pathB, p_minDelay, p_maxDelay):\n\n # open output csv file (main)\n l_fOutMain = open(p_pathA, 'w')\n l_fOutMain.write('ID;NAME;ADDRESS;CP;CITY;CREATION;SIRET;TYPE;COUNT;OWNER;' +\n 'TEL1;TEL2;TEL3;TEL4;MAIL;WEB1;WEB2;WEB3;WEB4;HOURS;BUSINESS;ADDITIONAL\\n')\n\n # open output csv file (secondary)\n l_fOutSecondary = open(p_pathB, 'w')\n l_fOutSecondary.write('ID;TYPE;RAW;CLEAN;FLAG\\n')\n\n # Create a new instance of the Firefox driver\n l_driver = CommonFunctions.getDriver()\n\n # go to the base Url\n l_driver.get(g_url)\n\n try:\n # locate the keyword search input text box and enter the search string\n l_quoiQui = WebDriverWait(l_driver, 10).until(EC.presence_of_element_located(\n (By.XPATH, '//input[@id=\"pj_search_quoiqui\"]')))\n print('l_quoiQui placeholder:', l_quoiQui.get_attribute('placeholder'))\n l_quoiQui.send_keys(p_search)\n\n # locate the location input text box and enter the location string\n l_ou = l_driver.find_element_by_id('pj_search_ou')\n print('l_ou placeholder:', l_ou.get_attribute('placeholder'))\n l_ou.send_keys(p_location)\n\n # submit the form\n l_driver.find_element_by_xpath('//button[@class=\"button primary icon large-button\"]').click()\n except EX.NoSuchElementException:\n print('[01] Something is badly wrong (Element not found) ...')\n return 0\n except EX.TimeoutException:\n print('[02] Something is badly wrong (Timeout) ...')\n return 0\n\n l_finished = False\n l_count = 0\n while not l_finished:\n try:\n # WebDriverWait(driver,5).until(\n # lambda driver: driver.find_elements(By.ID,\"a\") or driver.find_elements(By.ID,\"b\"))\n\n WebDriverWait(l_driver, 10).until(\n lambda p_driver: \\\n p_driver.find_elements(By.XPATH, '//h2[@class=\"company-name\"]') \\\n or p_driver.find_elements(By.XPATH, '//div[@class=\"no-response\"]'))\n\n #WebDriverWait(l_driver, 10).until(EC.presence_of_element_located(\n # (By.XPATH, '//h2[@class=\"company-name\"]')))\n except EX.TimeoutException:\n print('[03] Something is badly wrong (Timeout) ...')\n return 0\n\n if killPopup(l_driver):\n continue\n\n try:\n l_driver.find_element_by_xpath('//div[@class=\"no-response\"]')\n print('No results')\n\n l_finished = True\n continue\n except EX.NoSuchElementException:\n print('There should be results')\n\n try:\n # reformulation\n l_reformulation = l_driver.find_element_by_xpath(\n '//span[@class=\"denombrement\"]/strong[@id=\"SEL-nbresultat\"]')\n\n l_resultCount = l_reformulation.text\n print('l_resultCount:', l_resultCount)\n\n except EX.NoSuchElementException:\n print('No reformulation ?! ...')\n\n l_articleList = []\n try:\n for l_company in l_driver.find_elements_by_xpath('//h2[@class=\"company-name\"]/../../../..'):\n l_articleId = l_company.get_attribute('id')\n print('l_articleId:', l_articleId)\n l_articleList += [l_articleId]\n\n except EX.NoSuchElementException:\n print('[04] Something is badly wrong (Element not found) ...')\n return 0\n\n try:\n l_article = 0\n for l_articleId in l_articleList:\n if killPopup(l_driver):\n print('Popup Killed, waiting for 10 s.')\n time.sleep(10)\n\n print('+ l_articleId:', l_articleId)\n l_company = l_driver.find_element_by_xpath(\n '//article[@id=\"{0}\"]//h2[@class=\"company-name\"]/a[2]'.format(l_articleId))\n\n #l_driver.execute_script(\"return arguments[0].scrollIntoView();\", l_company)\n\n l_name = l_company.text\n print('Fetching:', l_name)\n\n l_driver.execute_script(\"return arguments[0].scrollIntoView();\", l_company)\n l_driver.execute_script(\"window.scrollBy(0, -300);\")\n\n # Save the window opener (current window, do not mistaken with tab... not the same)\n l_mainWindow = l_driver.current_window_handle\n\n # l_company.send_keys(Keys.CONTROL + Keys.RETURN)\n # scroll to it, to make it visible, and then click it\n l_actions = ActionChains(l_driver)\n l_actions.move_to_element(l_company)\n l_actions.context_click()\n l_actions.send_keys(Keys.ARROW_DOWN)\n l_actions.send_keys(Keys.ENTER)\n l_actions.perform()\n\n # Switch tab to the new tab, which we will assume is the next one on the right\n l_driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)\n\n # Put focus on current window which will, in fact, put focus on the current visible tab\n l_driver.switch_to_window(l_mainWindow)\n\n if doOneCompany(l_driver, l_fOutMain, l_fOutSecondary, l_count):\n l_count += 1\n\n CommonFunctions.randomWait(p_minDelay, p_maxDelay)\n\n # Close current tab\n l_driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')\n\n # Put focus on current window which will be the window opener\n l_driver.switch_to_window(l_mainWindow)\n\n except EX.NoSuchElementException:\n print('[05] Something is badly wrong (Element not found) ...')\n return 0\n\n # locate the next button and click it\n try:\n l_next = l_driver.find_element_by_id('pagination-next')\n\n # scroll to it, to make it visible, and then click it\n l_actions = ActionChains(l_driver)\n l_actions.move_to_element(l_next)\n l_actions.click()\n l_actions.perform()\n except EX.NoSuchElementException:\n print('No more results')\n l_finished = True\n\n print('Number of items retrieved:', l_count)\n\n l_fOutMain.close()\n l_fOutSecondary.close()\n\n l_driver.quit()\n return l_count\n\ndef doOneCompany(p_driver, p_fOutMain, p_fOutSecondary, p_id):\n print('---[{0}]---'.format(p_id))\n\n l_finished = False\n l_name = ''\n while not l_finished:\n try:\n l_nameItem = WebDriverWait(p_driver, 10).until(EC.presence_of_element_located(\n (By.XPATH, '//h1[@itemprop=\"name\"]')))\n\n l_name = l_nameItem.text\n l_name = re.sub('\\s+Afficher le numéro$', '', l_name).strip()\n print(' l_name :', l_name)\n except EX.TimeoutException:\n print('[06] Something is badly wrong (Timeout) ...')\n return False\n\n if killPopup(p_driver):\n continue\n\n l_finished = True\n\n try:\n l_html = p_driver.find_element_by_xpath('//body').get_attribute('innerHTML')\n l_tree = html.fromstring(l_html)\n\n l_address = CommonFunctions.getUnique(l_tree, '//span[@itemprop=\"streetAddress\"]')\n print(' l_address :', l_address)\n l_zip = CommonFunctions.getUnique(l_tree, '//span[@itemprop=\"postalCode\"]')\n l_zip = re.sub('^[,;:\\.]\\s+', '', l_zip).strip()\n print(' l_zip :', l_zip)\n l_city = CommonFunctions.getUnique(l_tree, '//span[@itemprop=\"addressLocality\"]')\n print(' l_city :', l_city)\n\n # extract a full xml/html tree from the fragment\n l_telList = []\n for l_telRow in l_tree.xpath('//div[@id=\"coord-list-container-1\"]//ul/li'):\n l_telType = CommonFunctions.getUnique(l_telRow, './span[@class=\"num-tel-label\"]')\n l_telType = re.sub('\\s+:$', '', l_telType).strip()\n\n if l_telType == 'tél':\n l_telType = 'FixedPhone'\n elif l_telType == 'Mobile':\n l_telType = 'MobilePhone'\n elif l_telType == 'Fax':\n l_telType = 'Fax'\n else:\n l_telType = 'UnspecifiedPhone'\n\n print(' l_telType :', l_telType)\n\n l_tel = CommonFunctions.getUnique(l_telRow, './span[@class=\"coord-numero\"]')\n l_tel = re.sub('^\\.', '', l_tel).strip()\n l_tel = re.sub('\\s+$', '', l_tel).strip()\n l_tel = re.sub('^\\s+', '', l_tel).strip()\n print(' l_tel :', l_tel)\n l_tel = CommonFunctions.cleanField(l_tel)\n l_telList += [l_tel]\n\n p_fOutSecondary.write('{0};\"{1}\";\"{2}\";\"{3}\";\"{4}\"\\n'.format(\n p_id, l_telType, l_tel, l_tel, ''))\n\n\n l_webList = []\n # l_root = l_tree.getroottree()\n for l_webRow in l_tree.xpath(\n '//article/div/div/h3[text()=\"Sites et réseaux sociaux\"]/..//ul/li/a/span[@class=\"value\"]'):\n l_webSite = l_webRow.text_content().strip()\n # print(' l_webSite path :', l_root.getpath(l_webRow))\n print(' l_webSite :', l_webSite)\n l_webSite = CommonFunctions.cleanField(l_webSite)\n l_webList += [l_webSite]\n\n p_fOutSecondary.write('{0};\"{1}\";\"{2}\";\"{3}\";\"{4}\"\\n'.format(\n p_id, 'WebSite', l_webSite, l_webSite, ''))\n\n # bloc-info-horaires\n l_hoursList = []\n for l_hoursRow in l_tree.xpath(\n '//ul[@class=\"liste-horaires-principaux\"]//ul/li[@itemprop=\"openingHours\"]'):\n l_hours = l_hoursRow.get('content').strip()\n print(' l_hours :', l_hours)\n l_hours = CommonFunctions.cleanField(l_hours)\n l_hoursList += [l_hours]\n\n p_fOutSecondary.write('{0};\"{1}\";\"{2}\";\"{3}\";\"{4}\"\\n'.format(\n p_id, 'OpeningHours', l_hours, l_hours, ''))\n\n l_businessList = []\n for l_businessRow in l_tree.xpath('//span[@class=\"activite-premiere-visibilite activite\"]'):\n\n l_businessCategory = l_businessRow.text_content().strip()\n l_businessCategory = re.sub('\\s+[\\.;,:]$', '', l_businessCategory).strip()\n l_businessCategory = re.sub('^[\\.;,:]\\s+', '', l_businessCategory).strip()\n l_businessCategory = CommonFunctions.cleanField(l_businessCategory)\n print(' l_businessCat. :', l_businessCategory)\n l_businessList += [l_businessCategory]\n\n p_fOutSecondary.write('{0};\"{1}\";\"{2}\";\"{3}\";\"{4}\"\\n'.format(\n p_id, 'BusinessCategory', l_businessCategory, l_businessCategory, ''))\n\n # description\n l_additional = ''\n for l_description in l_tree.xpath('//div[@itemprop=\"description\"]'):\n l_additional = l_description.text_content().strip()\n\n l_additional = re.sub('\\s+', ' ', l_additional).strip()\n print(' l_additional :', l_additional)\n\n l_telList = (l_telList + ['', '', '', ''])[0:4]\n l_webList = (l_webList + ['', '', '', ''])[0:4]\n\n # output to CSV file (main)\n p_fOutMain.write(\n ('{0};\"{1}\";\"{2}\";\"{3}\";\"{4}\";\"{5}\";\"{6}\";\"{7}\";\"{8}\";\"{9}\";' +\n '\"{10}\";\"{11}\";\"{12}\";\"{13}\";\"{14}\";\"{15}\"\\n').format(\n # ID\n p_id,\n # NAME\n re.sub('\"', '\"\"', CommonFunctions.cleanField(l_name)),\n # ADDRESS\n re.sub('\"', '\"\"', CommonFunctions.cleanField(l_address)),\n # CP\n re.sub('\"', '\"\"', CommonFunctions.cleanField(l_zip)),\n # CITY\n re.sub('\"', '\"\"', CommonFunctions.cleanField(l_city)),\n # CREATION\n '',\n # SIRET\n '',\n # TYPE\n '',\n # COUNT\n '',\n # OWNER\n '',\n # TEL1 - TEL4\n '\";\"'.join([re.sub('\"', '\"\"', CommonFunctions.cleanField(t)) for t in l_telList]),\n # MAIL\n '',\n # WEB1 - WEB4\n '\";\"'.join([re.sub('\"', '\"\"', CommonFunctions.cleanField(w)) for w in l_webList]),\n # HOURS\n re.sub('\"', '\"\"', CommonFunctions.cleanField('|'.join(l_hoursList))),\n # BUSINESS\n re.sub('\"', '\"\"', CommonFunctions.cleanField('|'.join(l_businessList))),\n # ADDITIONAL\n re.sub('\"', '\"\"', CommonFunctions.cleanField(l_additional))\n ))\n p_fOutMain.flush()\n p_fOutSecondary.flush()\n\n except EX.NoSuchElementException:\n print('[07] Something is badly wrong (Element not found) ...')\n return False\n\n return True\n\n# ---------------------------------------------------- Main section ---------------------------------------------\n\nif __name__ == \"__main__\":\n print('+------------------------------------------------------------+')\n print('|' + '{:<60}'.format(' Web Scraping of {0}'.format(g_url)) + '|')\n print('| |')\n print('| Contractor: Kabir Abdulhamid / Upwork |')\n print('| |')\n print('| Client: Teddy Nestor |')\n print('| |')\n print('| v. 2.3 - 04/04/2016 |')\n print('| + réupération des horaires |')\n print('+------------------------------------------------------------+')\n\n # list of départements, all formated as a string of 3 digits\n l_départements = [str(i+1).zfill(3) for i in range(95)] + ['971', '972', '973', '974', '976']\n\n # list of arguments\n l_parser = argparse.ArgumentParser(description='Crawl {0}.'.format(g_url))\n l_parser.add_argument('search', help='Search keyword(s)')\n l_parser.add_argument('location', help='Location criterion')\n l_parser.add_argument('--min', type=int, help='Minimum delay between requests (in seconds)', default=0)\n l_parser.add_argument('--max', type=int, help='Minimum delay between requests (in seconds)', default=0)\n\n # create 118218 dir and email if not exist\n if not os.path.isdir(g_PagesJaunesDir):\n os.makedirs(g_PagesJaunesDir)\n\n # dummy class to receive the parsed args\n class C:\n def __init__(self):\n self.search = ''\n self.location = ''\n self.min = 0\n self.max = 0\n\n # do the argument parse\n c = C()\n l_parser.parse_args()\n parser = l_parser.parse_args(namespace=c)\n\n l_minDelay = 0\n l_maxDelay = 0\n\n # local variables (why did I do this ?)\n l_search = c.search\n l_location = c.location\n if c.min is not None:\n l_minDelay = c.min\n if c.max is not None:\n l_maxDelay = c.max\n\n # A file type path and name\n l_pathA = os.path.join(g_PagesJaunesDir, 'PagesJaunesA_{0}-{1}.csv'.format(\n re.sub('\\s+', '_', l_search),\n re.sub('\\s+', '_', l_location)))\n\n # B file type path and name\n l_pathB = os.path.join(g_PagesJaunesDir, 'PagesJaunesB_{0}-{1}.csv'.format(\n re.sub('\\s+', '_', l_search),\n re.sub('\\s+', '_', l_location)))\n\n # displays parameters\n print('Search keyword(s) :', c.search)\n print('Location :', c.location)\n if l_minDelay > 0:\n print('Minimum delay (s.) :', c.min)\n if l_maxDelay > 0:\n print('Maximum delay (s.) :', c.max)\n\n # do the per-département search if the location parameter is 'France'\n if l_location.lower() == 'france':\n print('Location = France --> search all départements')\n\n # one tmp file per département\n for l_dépNum in l_départements:\n l_tmpA = os.path.join(g_PagesJaunesDir, '__tmpA_{0}.csv'.format(l_dépNum))\n l_tmpB = os.path.join(g_PagesJaunesDir, '__tmpB_{0}.csv'.format(l_dépNum))\n\n if not os.path.isfile(l_tmpA) and not os.path.isfile(l_tmpA):\n doSearch(l_search, l_dépNum, l_tmpA, l_tmpB, l_minDelay, l_maxDelay)\n\n # merge the tmp files\n CommonFunctions.concatTmp(g_PagesJaunesDir, l_départements, l_pathA, l_pathB)\n\n # sort the result\n CommonFunctions.csvSort(l_pathA, p_départements=True)\n else:\n # otherwise, do an ordinary search\n doSearch(l_search, l_location, l_pathA, l_pathB, l_minDelay, l_maxDelay)\n # and sort the results as well\n CommonFunctions.csvSort(l_pathA)\n\n # displays parameters again\n print('------------------------------------------------------')\n print('Search keyword(s) :', c.search)\n print('Location :', c.location)\n if l_minDelay > 0:\n print('Minimum delay (s.) :', c.min)\n if l_maxDelay > 0:\n print('Maximum delay (s.) :', c.max)\n print(' ---> Main File :', l_pathA)\n print(' ---> Tel File :', l_pathB)","sub_path":"PagesJaunes.py","file_name":"PagesJaunes.py","file_ext":"py","file_size_in_byte":18762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"314480401","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass DefaultErrorResponseError(Model):\n \"\"\"Error model.\n\n Variables are only populated by the server, and will be ignored when\n sending a request.\n\n :ivar code: Standardized string to programmatically identify the error.\n :vartype code: str\n :ivar message: Detailed error description and debugging information.\n :vartype message: str\n :ivar target: Detailed error description and debugging information.\n :vartype target: str\n :param details:\n :type details:\n list[~azure.mgmt.web.models.DefaultErrorResponseErrorDetailsItem]\n :ivar innererror: More information to debug error.\n :vartype innererror: str\n \"\"\"\n\n _validation = {\n 'code': {'readonly': True},\n 'message': {'readonly': True},\n 'target': {'readonly': True},\n 'innererror': {'readonly': True},\n }\n\n _attribute_map = {\n 'code': {'key': 'code', 'type': 'str'},\n 'message': {'key': 'message', 'type': 'str'},\n 'target': {'key': 'target', 'type': 'str'},\n 'details': {'key': 'details', 'type': '[DefaultErrorResponseErrorDetailsItem]'},\n 'innererror': {'key': 'innererror', 'type': 'str'},\n }\n\n def __init__(self, **kwargs):\n super(DefaultErrorResponseError, self).__init__(**kwargs)\n self.code = None\n self.message = None\n self.target = None\n self.details = kwargs.get('details', None)\n self.innererror = None\n","sub_path":"azure-mgmt-web/azure/mgmt/web/models/default_error_response_error.py","file_name":"default_error_response_error.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"497547175","text":"#!/usr/bin/env python3\n# Copyright 2017 Karl Sundequist Blomdahl \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# pylint: disable=C0103, C0301\n\n\"\"\"\nGTP (Go Text Protocol) referee program for running engines against each other\nsome number of times to determine a winner.\n\nUsage: ./referee.py [num games] \n\"\"\"\n\nimport sys\nimport subprocess\nfrom math import sqrt\nfrom random import random\n\nimport numpy as np\n\ndef gtp_to_sgf(vertex):\n \"\"\" Convert an GTP vertex (e.g. D4) to SGF format (dd) \"\"\"\n GTP_LETTERS = [\n 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm',\n 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'\n ]\n SGF_LETTERS = [\n 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',\n 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'\n ]\n x = GTP_LETTERS.index(vertex[0])\n y = int(vertex[1:]) - 1\n\n return '{}{}'.format(SGF_LETTERS[x], SGF_LETTERS[y])\n\ndef play_game(engine_1, engine_2):\n \"\"\"\n Play a game of the two given engines and returns `0` if the first\n engine won, otherwise `1`.\n \"\"\"\n proc_1 = subprocess.Popen(engine_1, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)\n proc_2 = subprocess.Popen(engine_2, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)\n\n def write_both(s):\n \"\"\" Write the given bytes to both of the engines. \"\"\"\n proc_1.stdin.write(s)\n proc_2.stdin.write(s)\n\n def write_command(to, line_nr, s):\n \"\"\" Write a command to the given process and returns the response \"\"\"\n to.stdin.write(\"{} {}\".format(line_nr, s).encode('utf-8'))\n to.stdin.flush()\n\n for line in to.stdout:\n line = line.decode('utf-8').strip().lower()\n\n if line.startswith('=' + str(line_nr)):\n return line\n elif line.startswith('?' + str(line_nr)):\n print(line, file=sys.stderr)\n break\n\n try:\n write_both(b'komi 7.5\\n')\n write_both(b'boardsize 19\\n')\n write_both(b'clear_board\\n')\n\n if random() < 0.5:\n black = (engine_1, proc_1, 'B', 0)\n white = (engine_2, proc_2, 'W', 1)\n else:\n black = (engine_2, proc_2, 'B', 1)\n white = (engine_1, proc_1, 'W', 0)\n\n turns = [black, white]\n all_moves = []\n pass_count = 0\n move_count = 0\n sgf = ''\n re = '?'\n\n while move_count < 722 and pass_count < 2:\n current, other = turns[0], turns[1]\n line_nr = move_count + 1000\n\n response = write_command(current[1], line_nr, 'genmove {}\\n'.format(current[2]))\n if response:\n move = response.split(' ')[1]\n\n if move == 'pass':\n pass_count += 1\n sgf += ';{}[]'.format(current[2])\n elif move == 'resign':\n re = '{}+Resign'.format(other[2])\n return other[3]\n else:\n pass_count = 0\n all_moves.append((current[2], move))\n\n # play this move to the other engine and then continue\n # to its turn.\n write_command(other[1], line_nr, 'play {} {}\\n'.format(current[2], move))\n sgf += ';{}[{}]'.format(current[2], gtp_to_sgf(move))\n else:\n # if an engine encounter an error, then it loses\n print('Received erroneous response from {}'.format(current[0]), file=sys.stderr)\n re = '{}+Resign'.format(other[2])\n return other[3]\n\n # flip the current player\n turns = [turns[1], turns[0]]\n move_count += 1\n\n proc_1.stdin.write(b'quit\\n')\n proc_2.stdin.write(b'quit\\n')\n\n # we finished without a winner, we use GNU Go to determine the winner so that\n # no complicated scoring algorihm, including figuring out if a group is alive\n # or not, has to be implemented in the referee.\n #\n # We use the `final_score` variant here to avoid any incorrect scores due to\n # complicated situations that `estimate_score` fail to take into account.\n gnugo = subprocess.Popen('gnugo --chinese-rules --mode gtp', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)\n gnugo.stdin.write(b'komi 7.5\\n')\n gnugo.stdin.write(b'boardsize 19\\n')\n gnugo.stdin.write(b'clear_board\\n')\n\n for (i, (color, move)) in enumerate(all_moves):\n write_command(gnugo, 1000 + i, 'play {} {}\\n'.format(color, move))\n\n re = write_command(gnugo, 2000, 'final_score\\n')\n if not re:\n return # cannot determine winner\n\n re = re.split(' ')[1].upper() # trim away the id prefix\n\n gnugo.stdin.write(b'quit\\n')\n gnugo.kill()\n gnugo.communicate()\n\n if re.startswith('b') or re.startswith('B'):\n return black[3]\n else:\n return white[3]\n finally:\n print('(;GM[1]FF[4]SZ[19]RU[Chinese]KM[7.5]PW[{}]PB[{}]RE[{}]{})'.format(\n white[0],\n black[0],\n re,\n sgf\n ), flush=True)\n\n # terminate the engines the hard way if they have not died already\n if not proc_1.poll():\n proc_1.kill()\n proc_1.communicate()\n if not proc_2.poll():\n proc_2.kill()\n proc_2.communicate()\n\ndef join_pretty(headers, elements):\n \"\"\"\n Join the given elements with padding such that they align to the\n given headers.\n \"\"\"\n\n max_header = max([len(header) for header in headers])\n num_padding = max_header + 2\n out = ''\n\n for element in elements:\n out += element\n out += ' ' * (num_padding - len(element))\n\n return out\n\ndef main(num_games, engines):\n \"\"\" Main function \"\"\"\n\n # generate all unique pairings of engines\n num_engines = len(engines)\n pairings = []\n\n for i in range(num_engines):\n for j in range(i + 1, num_engines):\n pairings.append((i, j))\n\n # keep track of the number of times, for each `(engine_1, engine_2)`\n # pair, how many times `engine_1` has won.\n wins = np.zeros((num_engines, num_engines), np.int32)\n\n try:\n def total_played(engine_1, engine_2):\n \"\"\"\n Returns the total number of games that the two given engines\n has played against each other.\n \"\"\"\n return wins[engine_1, engine_2] + wins[engine_2, engine_1]\n\n while min([total_played(p[0], p[1]) for p in pairings]) < num_games:\n next_pair = min(pairings, key=lambda p: total_played(p[0], p[1]))\n winner = play_game(engines[next_pair[0]], engines[next_pair[1]])\n\n if winner == 0:\n wins[next_pair[0], next_pair[1]] += 1\n elif winner == 1:\n wins[next_pair[1], next_pair[0]] += 1\n else:\n pass # error? retry again later\n finally:\n # pretty-print the engines scores, sorted according to their total number\n # of wins.\n print('# Played {} games between all engines, outputting the confidence'.format(np.sum(wins)), file=sys.stderr)\n print('# interval for each engine winning against every other engine.', file=sys.stderr)\n print(file=sys.stderr)\n\n names = ['{}. {}'.format(i + 1, engines[i]) for i in range(num_engines)]\n titles = ['vs {}'.format(name) for name in names]\n max_name = max([len(name) for name in names])\n name_padding = max_name + 4\n\n def get_score(engine_1, engine_2):\n \"\"\" Returns the score of `engine_1` vs `engine_2` \"\"\"\n if engine_1 == engine_2:\n return '-'\n else:\n n_s = float(wins[engine_1, engine_2])\n n_f = float(wins[engine_2, engine_1])\n\n return '{} - {}'.format(int(n_s), int(n_f))\n\n print(' ' * name_padding + '{}'.format(join_pretty(titles, titles)), file=sys.stderr)\n for i in sorted(range(num_engines), key=lambda e: -np.sum(wins[e, :])):\n scores = [get_score(i, other) for other in range(num_engines)]\n\n print('{}{}{}'.format(\n names[i],\n ' ' * (name_padding - len(names[i])),\n join_pretty(titles, scores)\n ), file=sys.stderr)\n\nif __name__ == '__main__':\n if len(sys.argv) <= 3:\n print('Usage: referee.py [num games] ')\n quit()\n\n main(int(sys.argv[1]), sys.argv[2:])\n","sub_path":"tools/referee.py","file_name":"referee.py","file_ext":"py","file_size_in_byte":9231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"181473052","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Export the Bioregistry as a JSON-LD context.\"\"\"\n\nimport json\nimport logging\nfrom pathlib import Path\nfrom typing import Mapping, Optional, Sequence\n\nimport click\n\nimport bioregistry\nfrom bioregistry.constants import DOCS_DATA\nfrom bioregistry.schema import Collection\n\nlogger = logging.getLogger(__name__)\n\n\n@click.command()\ndef generate_context_json_ld():\n \"\"\"Generate various JSON-LD context files.\"\"\"\n contexts_directory = Path(DOCS_DATA) / \"contexts\"\n contexts_directory.mkdir(parents=True, exist_ok=True)\n\n with contexts_directory.joinpath(\"obo.context.jsonld\").open(\"w\") as file:\n json.dump(\n fp=file,\n indent=4,\n sort_keys=True,\n obj={\n \"@context\": get_obofoundry_prefix_map(),\n },\n )\n\n with contexts_directory.joinpath(\"obo_synonyms.context.jsonld\").open(\"w\") as file:\n json.dump(\n fp=file,\n indent=4,\n sort_keys=True,\n obj={\n \"@context\": get_obofoundry_prefix_map(include_synonyms=True),\n },\n )\n\n for key, collection in bioregistry.read_collections().items():\n name = collection.context\n if name is None:\n continue\n with contexts_directory.joinpath(name).with_suffix(\".context.jsonld\").open(\"w\") as file:\n json.dump(fp=file, indent=4, sort_keys=True, obj=get_collection_jsonld(key))\n\n\ndef get_collection_jsonld(identifier: str) -> Mapping[str, Mapping[str, str]]:\n \"\"\"Get the JSON-LD context based on a given collection.\"\"\"\n collection = bioregistry.get_collection(identifier)\n if collection is None:\n raise KeyError\n return collection.as_context_jsonld()\n\n\ndef collection_to_context_jsonlds(collection: Collection) -> str:\n \"\"\"Get the JSON-LD context as a string from a given collection.\"\"\"\n return json.dumps(collection.as_context_jsonld())\n\n\nOBO_PRIORITY = (\n \"obofoundry\",\n \"bioregistry\",\n \"prefixcommons\",\n \"miriam\",\n \"ols\",\n)\nOBO_REMAPPING = {\n \"umls\": \"UMLS\",\n \"snomedct\": \"SCTID\",\n \"ensembl\": \"ENSEMBL\",\n}\n\n\ndef get_obofoundry_prefix_map(include_synonyms: bool = False) -> Mapping[str, str]:\n \"\"\"Get the OBO Foundry prefix map.\n\n :param include_synonyms: Should synonyms of each prefix also be included as additional prefixes, but with\n the same URL prefix?\n :return: A mapping from prefixes to prefix URLs.\n \"\"\"\n remapping = bioregistry.get_registry_map(\"obofoundry\")\n remapping.update(OBO_REMAPPING)\n return get_general_prefix_map(\n remapping=remapping, priority=OBO_PRIORITY, include_synonyms=include_synonyms\n )\n\n\ndef get_general_prefix_map(\n *,\n remapping: Optional[Mapping[str, str]] = None,\n priority: Optional[Sequence[str]] = None,\n include_synonyms: bool = False,\n) -> Mapping[str, str]:\n \"\"\"Get the full prefix map.\n\n :param remapping: A mapping from bioregistry prefixes to preferred prefixes.\n :param priority: A priority list for how to generate prefix URLs.\n :param include_synonyms: Should synonyms of each prefix also be included as additional prefixes, but with\n the same URL prefix?\n :return: A mapping from prefixes to prefix URLs.\n \"\"\"\n urls = bioregistry.get_format_urls(priority=priority, include_synonyms=include_synonyms)\n if remapping is None:\n return urls\n return {remapping.get(prefix, prefix): prefix_url for prefix, prefix_url in urls.items()}\n\n\nif __name__ == \"__main__\":\n generate_context_json_ld()\n","sub_path":"src/bioregistry/export/prefix_maps.py","file_name":"prefix_maps.py","file_ext":"py","file_size_in_byte":3548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"463995023","text":"def login (un_pw):\n if not un_pw:\n return False\n else:\n username = input(\"Enter your username (or r to register):\").lower()\n while username not in un_pw and username.lower() != 'r':\n username = input(\"Enter a valid username (or r to register)\")\n if username.lower() == 'r':\n return False\n else:\n password = input(\"Enter your password: \")\n while password != un_pw[username]:\n password = input(\"Enter your password please:\")\n print(\"You are now logged in\")\n return True\ndef register (un_pw):\n un = input(\"Please register a new username: \").lower()\n pw = input(\"Enter a password of 6 characters or more: \")\n while len(pw) < 5:\n print(\"You did not enter a password of 6 characters of more.\")\n pw = input(\"Enter a password of 6 characters or more:\")\n un_pw[un] = pw\n print(\"Your login info has been created!\")\n return un_pw\ndef menu_text():\n print(\"Main Menu\")\n print(\"Press A to Add books\")\n print(\"Press D to Delete books\")\n print(\"Press F to Find a book\")\n print(\"Press S to Sell a book\")\n print(\"Press X to Log out\")\ndef get_menu_option():\n menu_text()\n menu_select = input(\"Enter a command:\").lower()\n while menu_select not in ('f', 'x', 'a', 'd', 's'):\n print(\"Error: Invalid command\")\n menu_text()\n menu_select = input(\"Enter a command:\").lower()\n return menu_select\ndef find(books_prices):\n options = list(books_prices.items())\n for i, (k,v) in enumerate(options):\n print(\"Type\", i + 1, \"for\", k)\n num = input(\"Which book would you like to access\")\n while not num.isnumeric() or 1 > int(num) or int(num) > len(options):\n print(\"Please select a number that is within the range: \")\n for i, (k,v) in enumerate(options):\n print(\"Select\", i + 1, \"for\", k)\n num = input(\"Which book would you like to access\")\n i = int(num) - 1\n title = options[i][0]\n price = str(options[i][1])\n print(title + \": $\" + price)\n question = input(\"Anymore books you are looking for? Y or N\").lower()\n while question not in ('n', 'y'):\n question = input(\"Press Y or N if you want to continue looking for books\").lower()\n if question == 'y':\n return True, books_prices\n else:\n return False, books_prices\n\n\ndef add(books_prices):\n print(str(books_prices))\n newbook = input(\"What book would you like to add?\").title()\n newcost = input(\"What is the cost of \" + str(newbook) + \"?\")\n try:\n while float(newcost) < 0 or not float(newcost):\n print(\"Please enter a number:\")\n newcost = input(\"What is the cost of \" + str(newbook) + \"?\")\n except ValueError:\n newcost = input(\"What is the cost of \" + str(newbook) + \"?\")\n books_prices[newbook] = newcost\n question = input(\"Anymore books you would like to add? Y or N\").lower()\n while question not in ('y', 'n'):\n print(\"Please enter a valid command.\")\n question = input(\"Anymore books you would like to add? Y or N\").lower()\n if question == 'y':\n return True, books_prices\n else:\n return False, books_prices\n\n\ndef delete(books_prices):\n options = list(books_prices.items())\n for i, (k,v) in enumerate(options):\n print(\"Select\", i + 1, \"to delete\", k)\n num = input(\"Which book would you like to delete\")\n while not num.isnumeric() or 1 > int(num) or int(num) > len(options):\n print(\"Please select a number that is within the range: \")\n for i, (k,v) in enumerate(options):\n print(\"Select\", i + 1, \"for\", k)\n num = input(\"Which book would you like to delete\")\n i = int(num) - 1\n title = options[i][0]\n price = str(options[i][1])\n print(title + \": $\" + price + \" is now being deleted\")\n options.remove(options[i])\n print(options)\n books_prices = dict(options)\n question = input(\"Press Y or N if you want to continue deleting books\").lower()\n while question not in ('n', 'y'):\n question = input(\"Press Y or N if you want to continue deleting books\").lower()\n if question == 'y':\n return True, books_prices\n else:\n print(books_prices)\n return False, books_prices\n\ndef sell(books_prices):\n options = list(books_prices.items())\n for i, (k,v) in enumerate(options):\n print(\"Select\", i + 1, \"to sell\", k)\n num = input(\"Which book would you like to sell\")\n while not num.isnumeric() or 1 > int(num) or int(num) > len(options):\n print(\"Please select a number that is within the range: \")\n for i, (k,v) in enumerate(options):\n print(\"Select\", i + 1, \"for\", k)\n num = input(\"Which book would you like to sell\")\n i = int(num) - 1\n subtotal = float(options[i][1])\n taxes = subtotal * 0.07\n tax = round(taxes, 2)\n book = options[i][0]\n shipping = 3.00\n order = [subtotal, tax, shipping]\n total = sum(order)\n print(book + \" is now being sold\")\n print(\"The subtotal is: $\" + str(subtotal))\n print(\"The tax is: $\" + str(tax))\n print(\"The shipping & handling cost is: $\" + str(shipping))\n print(\"The total is: $\" + str(total))\n options.remove(options[i])\n print(options)\n books_prices = dict(options)\n question = input(\"Press Y or N if you want to continue selling books\").lower()\n while question not in ('n', 'y'):\n question = input(\"Press Y or N if you want to continue selling books\").lower()\n if question == 'y':\n return True, books_prices\n else:\n print(books_prices)\n return False, books_prices\ndef main():\n has_started = True\n user_quit = False\n while not user_quit:\n if has_started:\n books = {'Games of Thrones': 50.00, 'Lord of the Rings': 25.00, 'Fantastic Beasts and Where to Find Them': 10.00}\n users = {'fred': 'luffy1'}\n valid_login = False\n has_started = False\n\n while not valid_login:\n valid_login = login(users)\n if not valid_login:\n users = register(users)\n\n menu_select = get_menu_option()\n if menu_select == 'a':\n while True:\n add_another, books = add(books)\n if add_another:\n continue\n else:\n break\n elif menu_select == 'f':\n while True:\n find_another, books = find(books)\n if find_another:\n continue\n else:\n break\n elif menu_select == 'd':\n while True:\n delete_another, books = delete(books)\n if delete_another:\n continue\n else:\n break\n elif menu_select == 's':\n while True:\n sell_another, books = sell(books)\n if sell_another:\n continue\n else:\n break\n else:\n print(\"Logging out\")\n valid_login = False\nmain()","sub_path":"bookstore.py","file_name":"bookstore.py","file_ext":"py","file_size_in_byte":7093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"249742953","text":"# -*- coding: utf-8 -*-\nimport itertools\n\nfrom odoo import models, fields, api, _\nfrom odoo.addons.grid.models import END_OF\nfrom odoo.exceptions import UserError\n\n\nclass AnalyticLine(models.Model):\n _inherit = 'account.analytic.line'\n\n name = fields.Char(required=False)\n # reset amount on copy\n amount = fields.Monetary(copy=False)\n validated = fields.Boolean(\"Validated line\", compute='_timesheet_line_validated', store=True)\n is_timesheet = fields.Boolean(\n string=\"Timesheet Line\",\n compute='_compute_is_timesheet', search='_search_is_timesheet',\n help=\"Set if this analytic line represents a line of timesheet.\")\n\n @api.multi\n @api.depends('project_id')\n def _compute_is_timesheet(self):\n for line in self:\n line.is_timesheet = bool(line.project_id)\n\n def _search_is_timesheet(self, operator, value):\n if (operator, value) in [('=', True), ('!=', False)]:\n return [('project_id', '!=', False)]\n\n return [('project_id', '=', False)]\n\n @api.multi\n def validate(self):\n anchor = fields.Date.from_string(self.env.context['grid_anchor'])\n span = self.env.context['grid_range']['span']\n validate_to = fields.Date.to_string(anchor + END_OF[span])\n\n if not self:\n raise UserError(_(\"There aren't any timesheet to validate\"))\n\n employees = self.mapped('user_id.employee_ids')\n validable_employees = employees.filtered(lambda e: not e.timesheet_validated or e.timesheet_validated < validate_to)\n if not validable_employees:\n raise UserError(_('All selected timesheets are already validated'))\n\n validation = self.env['timesheet_grid.validation'].create({\n 'validate_to': validate_to,\n 'validable_ids': [\n (0, None, {'employee_id': employee.id})\n for employee in validable_employees\n ]\n })\n\n return {\n 'type': 'ir.actions.act_window',\n 'target': 'new',\n 'res_model': 'timesheet_grid.validation',\n 'res_id': validation.id,\n 'views': [(False, 'form')],\n }\n\n @api.multi\n def adjust_grid(self, row_domain, column_field, column_value, cell_field, change):\n if column_field != 'date' or cell_field != 'unit_amount':\n raise ValueError(\n \"{} can only adjust unit_amount (got {}) by date (got {})\".format(\n self._name,\n cell_field,\n column_field,\n ))\n\n # span is always daily and value is an iso range\n day = column_value.split('/')[0]\n\n self.search(row_domain, limit=1).copy({\n 'name': False,\n column_field: day,\n cell_field: change\n })\n return False\n @api.multi\n @api.depends('date', 'user_id.employee_ids.timesheet_validated')\n def _timesheet_line_validated(self):\n for line in self:\n # get most recent validation date on any of the line user's\n # employees\n validated_to = max(itertools.chain((\n e.timesheet_validated\n for e in line.user_id.employee_ids\n ), [None]))\n if validated_to:\n line.validated = line.date <= validated_to\n else:\n line.validated = False\n\nclass Employee(models.Model):\n _inherit = 'hr.employee'\n\n timesheet_validated = fields.Date(\n \"Timesheets validation limit\",\n help=\"Date until which the employee's timesheets have been validated\")\n\nclass Validation(models.TransientModel):\n _name = 'timesheet_grid.validation'\n\n validate_to = fields.Date()\n validable_ids = fields.One2many('timesheet_grid.validable', 'validation_id')\n\n # Recompute SO Lines delivered at validation\n @api.multi\n def validate(self):\n self.validable_ids \\\n .filtered('validate').mapped('employee_id') \\\n .write({'timesheet_validated': self.validate_to})\n return ()\n\nclass Validable(models.TransientModel):\n _name = 'timesheet_grid.validable'\n\n validation_id = fields.Many2one('timesheet_grid.validation', required=True)\n employee_id = fields.Many2one('hr.employee', string=\"Employee\", required=True)\n validate = fields.Boolean(\n default=True, help=\"Validate this employee's timesheet up to the chosen date\")\n","sub_path":"addons/enterprise/timesheet_grid/models/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"195912448","text":"from chx_xpcs.io.eiger.compress_file import compress_file\nimport time\nfrom chx_xpcs.io.eiger.compress_file2 import compress_file as compress_file2\n\nfilename = \"/home/lhermitte/research/projects/xpcs-aps-chx-project/sample_data/bnl_data_yugang/647a2a04-bc5c-4dc9-8550_2511_master.h5\".encode(\"utf-8\")\ndataset_prefix = \"/entry/data/data_\".encode(\"utf-8\")\ndataset_root = \"/entry/data\".encode(\"utf-8\")\nout_filename = \"out_version1_large.bin\".encode(\"utf-8\")\n\nprint(\"begin compression\")\nt1 = time.time()\ncompress_file(filename, dataset_root, dataset_prefix, out_filename)\nt2 = time.time()\nprint(\"end. took {} seconds\".format(t2-t1))\n\nprint(\"begin compression version 2 (python API)\")\nt1 = time.time()\ncompress_file2(filename, dset_min=1, dset_max=50, dset_pref=\"data_\",\n outfile=\"out_version2_large.bin\")\nt2 = time.time()\nprint(\"end. took {} seconds\".format(t2-t1))\n\n#filename = \"../../sample_data/flow10crlT0_EGhtd_011_66/flow10crlT0_EGhtd_011_66_master.h5\".encode(\"utf-8\")\n#dataset_prefix = \"entry/data_\".encode(\"utf-8\")\n#dataset_root = \"/entry\".encode(\"utf-8\")\n#out_filename = \"out2.bin\".encode(\"utf-8\")\n","sub_path":"tests/test_compress.py","file_name":"test_compress.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"521358855","text":"from Core.GetPlayerPosition import GetPlayerPosition\n\nSQMs = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\nPlayer = [0, 0]\ngameWindow = [0, 0, 0, 0]\nSQMsSizes = [0, 0]\n\n\ndef SetSQMs(HOOK_OPTION):\n if gameWindow[0] and gameWindow[1] != 0:\n SQMsSizes[0] = int((gameWindow[2] - gameWindow[0]) / 15)\n SQMsSizes[1] = int((gameWindow[3] - gameWindow[1]) / 11)\n print(f\"Size of Your SQM [Width: {SQMsSizes[0]}px, Height: {SQMsSizes[1]}px]\")\n print('')\n else:\n print(\"Setting Window Size...\")\n print('')\n Player[0], Player[1], gameWindow[0], gameWindow[1], gameWindow[2], gameWindow[\n 3] = GetPlayerPosition(HOOK_OPTION)\n SetSQMs(HOOK_OPTION)\n\n if Player[0] and Player[1] != 0 and SQMsSizes[0] and SQMsSizes[1] != 0:\n SQMs[0] = Player[0] - SQMsSizes[0]\n SQMs[1] = Player[1] + SQMsSizes[1]\n SQMs[2] = Player[0]\n SQMs[3] = Player[1] + SQMsSizes[1]\n SQMs[4] = Player[0] + SQMsSizes[0]\n SQMs[5] = Player[1] + SQMsSizes[1]\n SQMs[6] = Player[0] - SQMsSizes[0]\n SQMs[7] = Player[1]\n SQMs[8] = Player[0]\n SQMs[9] = Player[1]\n SQMs[10] = Player[0] + SQMsSizes[0]\n SQMs[11] = Player[1]\n SQMs[12] = Player[0] - SQMsSizes[0]\n SQMs[13] = Player[1] - SQMsSizes[1]\n SQMs[14] = Player[0]\n SQMs[15] = Player[1] - SQMsSizes[1]\n SQMs[16] = Player[0] + SQMsSizes[0]\n SQMs[17] = Player[1] - SQMsSizes[1]\n return SQMs[0], SQMs[1], SQMs[2], SQMs[3], SQMs[4], SQMs[5], SQMs[6], \\\n SQMs[7], SQMs[8], SQMs[9], SQMs[10], SQMs[11], SQMs[12], SQMs[13], \\\n SQMs[14], SQMs[15], SQMs[16], SQMs[17]\n else:\n print(\"Setting Player Position...\")\n Player[0], Player[1], gameWindow[0], gameWindow[1], gameWindow[2], gameWindow[\n 3] = GetPlayerPosition(HOOK_OPTION)\n SetSQMs(HOOK_OPTION)\n\n","sub_path":"Conf/SetSQMsPositions.py","file_name":"SetSQMsPositions.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"318155964","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom flask import Flask, render_template\nfrom flask import request, jsonify\nimport json\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/postText', methods=['POST'])\ndef lower_conversion():\n text = request.json['text']\n if \"ping\" in text:\n return_data = {\"result\":\"pong\"}\n return jsonify(ResultSet=json.dumps(return_data))\n lower_text = text.lower()\n return_data = {\"result\":lower_text}\n return jsonify(ResultSet=json.dumps(return_data))\n\n\nif __name__ == '__main__':\n app.run(host=\"127.0.0.1\", port=8080)\n","sub_path":"jQuery/ch05/03_ajax/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"365417211","text":"# Importimi i librarise socket per krijimin e socketave per lidhje\r\nfrom socket import *\r\nfrom _thread import * \r\nimport datetime\r\nimport random\r\nimport math\r\n\r\n# Porti i serverit, ne te cilin do te pritet per komunikim\r\n\r\nserverPort=12000 \r\nserverSocket=socket(AF_INET,SOCK_STREAM) \r\nserverSocket.bind(('', serverPort)) \r\nprint('Serveri u startua ne localhost: '+str(serverPort))\r\nprint('-----------------------------------')\r\n# Maksimumi i klientave qe mund te lidhen me server\r\nserverSocket.listen(5) \r\nprint('Serveri eshte i gatshem te pranoje kerkese ') \r\nprint('------------------------------------------')\r\n\r\n\r\n\r\n#Metoda Bashketingllore\r\ndef bashketingellore(fjalia):\r\n bashketingellore = ['B', 'C','Ç' 'D','DH','F','G','GJ','H', 'J','K','L','LL','M','N',\r\n 'NJ','P','Q', 'R','RR','S','SH','T','TH','V','X','XH','Z','ZH',\r\n 'b','c','ç','d','dh','f','g','gj','h','j','k','l','ll','m','n',\r\n 'nj','p','q','r','rr','s','sh','t','th','v','x','xh','z','zh']\r\n count=0\r\n for shkronja in fjalia:\r\n if(shkronja in bashketingellore):\r\n count=count+1\r\n return count\r\n\r\n #Metoda EMRIIKOMPJUTERIT\r\ndef Host():\r\n try:\r\n host=gethostname()\r\n return host\r\n except socket.error:\r\n return \"Emri i hostit nuk mund te gjendet!\"\r\n\r\n\r\n #Metoda Koha\r\ndef timenow():\r\n time=datetime.datetime.now() \r\n return time.strftime(\"%d-%m-%Y %I:%M:%S %p\")\r\n\r\n #Metoda Loja \r\ndef loja():\r\n listaNumrave=\"\"\r\n for number in range(0,7): \r\n numriRandom=random.randint(1,49)\r\n listaNumrave+=str(numriRandom)\r\n if number!=6:\r\n listaNumrave+=\", \"\r\n return listaNumrave\r\n\r\n #Metoda Fibonacci\r\ndef fibonacci(num):\r\n if num==0:\r\n return 0;\r\n elif num == 1:\r\n return 1;\r\n elif num < 0:\r\n return \"Numri eshte me i vogel se zero!\"\r\n else:\r\n return fibonacci(num-1)+fibonacci(num-2);\r\n\r\n\r\n #Metoda Konvertimi\r\ndef konvertimi(opsioni, vlera):\r\n if opsioni==\"KilowattToHorsepower\":\r\n rezultati=vlera*1.34\r\n\r\n elif opsioni==\"HorsepowerToKilowatt\":\r\n rezultati=vlera/1.34 \r\n\r\n elif opsioni==\"DegreesToRadians\":\r\n rezultati = (vlera * (math.pi/ 180))\r\n\r\n\r\n elif opsioni==\"RadiansToDegrees\":\r\n rezultati = (vlera * (180/math.pi))\r\n\r\n elif opsioni==\"GallonsToLiters\":\r\n rezultati = vlera * 3.785\r\n\r\n elif opsioni==\"LitersToGallons\":\r\n rezultati = vlera/3.785\r\n else:\r\n rezultati=\"Gabim\"\r\n return '%.2f' %(rezultati)\r\n\r\n#Metoda Faktorieli\r\ndef factorial(nr):\r\n if nr<=1:\r\n return 1\r\n else:\r\n return nr*factorial(nr-1)\r\n\r\n#Metoda Madhesia\r\ndef madhesia(fjalia):\r\n shkronja = 'A'\r\n fjalia=fjalia.upper()\r\n for S in fjalia:\r\n if ord(S) > ord(shkronja):\r\n shkronja = S\r\n return shkronja\r\n\r\n\r\n\r\n'''\r\n Funksioni client_handler ka 2 parametra, i pari eshte socketi i lidhjes me nje client i dyti esht adresa e klientit,\r\n'''\r\ndef client_handler(connectionSocket, addr):\r\n while 1:\r\n\r\n fjalia = connectionSocket.recv(128)\r\n\r\n if fjalia.decode('UTF-8').upper() == 'KOMANDAT':\r\n komandat = ''\r\n komandat += '---------------------------->FUNKSIONET<----------------------------\\n'\r\n komandat += '->Shtypni IPADRESA per te gjetur ip addressen tuaj\\n'\r\n komandat += '->Shtypni NUMRIIPORTIT per te gjetur portin tuaj\\n'\r\n komandat += '->Shtypni BASHKETINGLLORE per te numruar numrin e bashketinglloreve ne nje fjale ose fjali\\n'\r\n komandat += '->Shtypni PRINTIMI per te printuar ate qe keni shenuar\\n'\r\n komandat += '->Shtypni EMRIIKOMPJUTERIT per te ditur emrin e klientit\\n'\r\n komandat += '->Shtypni TIME nese doni te dini oren dhe daten aktuale\\n'\r\n komandat += '->Shtypni LOJA nese doni te shihni numra te rendomte\\n'\r\n komandat += '->Shtypni FIBONACCI pastaj numrin per te cilin gjendet vargu i Fibonaccit\\n'\r\n komandat += '->Shtypni KONVERTIMI per te bere konvertimin e numrave\\n'\r\n komandat += '->Shtypni ZARI per te hedhur zarin\\n'\r\n komandat += '->Shtypni FACTORIAL per te gjetur faktorielin e nje numri \\n'\r\n komandat += '->Shtypni MADHESIA per te gjetur karakterin me te madh sipas ASCII kodit\\n'\r\n\r\n connectionSocket.send(komandat.encode('UTF-8'))\r\n fjalia = connectionSocket.recv(1024)\r\n\r\n # Ruan ne nje variabel kerkesen me shkronja te medha\r\n FjaliaMeShkronjaTeMedha=fjalia.upper()\r\n \r\n rcvCMD = FjaliaMeShkronjaTeMedha.decode('UTF-8')\r\n\r\n if rcvCMD == 'PRINTIMI':\r\n # Pas pranimit te fjales PRINTO, pret per nje fjale tjeter nga klienti\r\n mesazhi = connectionSocket.recv(128).decode('UTF-8')\r\n mesazhi = 'Fjalia e dhene eshte: ' + mesazhi\r\n connectionSocket.send(mesazhi.encode('UTF-8'))\r\n elif rcvCMD == 'EMRIIKOMPJUTERIT':\r\n response = 'Emri i klientit eshte: ' + Host()\r\n connectionSocket.send(response.encode('UTF-8'))\r\n elif rcvCMD == 'IPADRESA':\r\n connectionSocket.send(str.encode(addr[0]))\r\n elif rcvCMD == 'NUMRIIPORTIT':\r\n response = 'Porti i serverit eshte ' + str(addr[1])\r\n connectionSocket.send(str.encode(response))\r\n elif rcvCMD == 'BASHKETINGLLORE':\r\n fjalia = connectionSocket.recv(128).decode('UTF-8')\r\n pergjigja = 'Numri i bashketingllore eshte: ' + str(bashketingellore(fjalia))\r\n connectionSocket.send(pergjigja.encode('UTF-8'))\r\n elif rcvCMD == 'TIME':\r\n koha = 'Koha eshte: ' + str(timenow())\r\n connectionSocket.send(koha.encode('UTF-8'))\r\n elif rcvCMD == 'LOJA':\r\n response = 'Numrat e shtypur nga intervali [1,49] jane: ( ' + loja() + ' )'\r\n connectionSocket.send(response.encode('UTF-8'))\r\n elif rcvCMD == 'ZARI':\r\n response = 'Zari i hedhur ka vleren: ' + str(random.randint(1, 6))\r\n connectionSocket.send(response.encode('UTF-8'))\r\n elif rcvCMD == 'FIBONACCI':\r\n nr = connectionSocket.recv(128).decode('UTF-8')\r\n print('FIBONACCI')\r\n print('Numri i dhene eshte: ' + nr)\r\n num=int(nr)\r\n connectionSocket.send(str(fibonacci(num)).encode('UTF-8'))\r\n elif rcvCMD == 'FACTORIAL':\r\n nr = connectionSocket.recv(128).decode('UTF-8')\r\n print('FACTORIAL')\r\n print('Numri i dhene eshte: ' + nr)\r\n nr=int(nr)\r\n connectionSocket.send(str(factorial(nr)).encode('UTF-8'))\r\n elif rcvCMD == 'MADHESIA':\r\n mesazhi = connectionSocket.recv(128).decode('UTF-8')\r\n mesazhi = 'Shkronja me e madhe e fjalise eshte: ' + madhesia(mesazhi)\r\n connectionSocket.send(mesazhi.encode('UTF-8'))\r\n elif rcvCMD == 'KONVERTIMI':\r\n opsioni = connectionSocket.recv(128).decode('UTF-8')\r\n print('Zgjedhja e bere eshte: ' +opsioni)\r\n num = connectionSocket.recv(128).decode('UTF-8')\r\n numri=int(num)\r\n connectionSocket.send(str(konvertimi(opsioni,numri)).encode('UTF-8'))\r\n elif rcvCMD == '0':\r\n break\r\n else:\r\n connectionSocket.send('Funksioni nuk ekziston'.encode('UTF-8'))\r\n print('Klienti ' + str(addr) + ' mbylli lidhjen.')\r\n connectionSocket.close()\r\n\r\nwhile True:\r\n connectionSocket,addr=serverSocket.accept() \r\n print('Klienti me ip ' + str(addr[0]) + ' dhe port ' + str(addr[1]) + ' krijoi nje lidhje')\r\n start_new_thread(client_handler, (connectionSocket, addr))\r\n\r\n\r\n\r\nconnectionSocket.close()\r\n\r\n\r\n","sub_path":"TCPServer/PythonApplication1/TCPServer.py","file_name":"TCPServer.py","file_ext":"py","file_size_in_byte":7776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"281405930","text":"# create a webserver using flask\nfrom flask import Flask, request, render_template\nimport joblib\nimport pandas as pd\nimport json\nimport numpy as np\n\n#create an app using Flask\napp = Flask(__name__)\n\n#load the pickle files\nmodel = joblib.load(\"churn_prediction.pkl\")\n\n# use generator to trigger a function whenever a request is received on server\n@app.route('/',methods=[\"POST\",\"GET\"])\ndef main():\n return render_template(\"index.html\")\n\n@app.route('/prediction',methods=[\"POST\",\"GET\"])\ndef main2():\n data = dict(request.form)\n df = preprocess(data)\n prediction = model.predict(df)\n prediction = [int(i) for i in prediction] # converting the boolean to integer\n data[\"Prediction\"] = prediction[0]\n data[\"Probability\"] = model.predict_proba(df)[0][1]\n return render_template(\"output.html\",output=data)\n\n\ndef preprocess(data_dict):\n # internation plan = no = 0 and yes = 1\n # vmail_messages = normal_user = 001, no vm plan = 010, HFu - 100\n df = pd.DataFrame(data_dict,index=[0])\n intcols = ['Number vmail messages', 'Total day minutes','Total eve minutes', 'Total night minutes',\n 'Total intl minutes','Customer service calls']\n for k in intcols:df[k] = df[k].apply(int)\n df['International plan'] = np.where(df['International plan']==\"Yes\",1,0)\n df['vmail_messages'] = pd.cut(df['Number vmail messages'],bins=[0,1,30,200],\n labels=['No VM plan','Normal Users','High Frequency users'],\n include_lowest=True)\n df.drop(['Number vmail messages'],axis=1,inplace=True)\n df['HFU'] = np.where(df['vmail_messages']==\"High Frequency users\",1,0)\n df['NU'] = np.where(df['vmail_messages']==\"Normal Users\",1,0)\n df['NVP'] = np.where(df['vmail_messages']==\"No VM plan\",1,0)\n df = df[['HFU','NVP','NU','International plan', 'Total day minutes',\n 'Total eve minutes', 'Total night minutes', 'Total intl minutes',\n 'Customer service calls']]\n return df\n \nif __name__==\"__main__\":\n app.run(debug=False,host=\"0.0.0.0\",port=5000)","sub_path":"Module 6/flask-docker/webapp.py","file_name":"webapp.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"630135736","text":"from app import db\nfrom app.models.mixins import SearchableMixin, BaseModelMixin\n\n\nclass User(SearchableMixin, BaseModelMixin, db.Model):\n __tablename__ = 'user'\n __searchable__ = ['name']\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n gh_username = db.Column(db.String(250), unique=True)\n gh_id = db.Column(db.Integer, unique=True)\n email = db.Column(db.String(250)) # Not github email(s), personal email where notifications go\n name = db.Column(db.String(250), nullable=False)\n bio = db.Column(db.Text, nullable=False, default=\"\")\n school_id = db.Column(db.ForeignKey('school.id'))\n\n # App Logic - \"User went though Account Creation Flow\"\n profile_created = db.Column(db.Boolean, nullable=False, default=False)\n\n school = db.relationship('School')\n contributions = db.relationship('Contribution', back_populates='user', cascade=\"all, delete-orphan\")\n watching = db.relationship('Project', secondary='watching', back_populates='watchers')\n interests = db.relationship('Tag', secondary='interest')\n notifications = db.relationship('Notification', foreign_keys=\"Notification.notifier_id\", back_populates='notifier')\n\n @classmethod\n def get_many(cls, **kwargs):\n def query_body(query):\n return query.filter_by(profile_created=True)\n return super().get_many(query_body=query_body, **kwargs)\n","sub_path":"app/models/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"3980055","text":"import os\nimport tensorflow as tf\nimport numpy as np\nimport cv2\n\n\ndef test_model(img_dir, model_path):\n # 获取图片总数\n input_count = 0\n for i in range(0, 10):\n dir = img_dir + '%s' % i # 这里可以改成你自己的图片目录,i为分类标签\n for rt, dirs, files in os.walk(dir):\n for filename in files:\n input_count += 1\n print(input_count)\n # 定义对应维数和各维长度的数组\n input_images = np.array([[[0, 0, 0]] * 48 * 32 for i in range(input_count)])\n input_labels = np.array([[0] * 10 for i in range(input_count)])\n\n # 读取图片和标签\n index = 0\n for i in range(10):\n dir = os.path.join(img_dir, str(i)) # i为分类标签\n for rt, dirs, files in os.walk(dir):\n for filename in files:\n filename = os.path.join(rt, filename)\n # print(filename)\n img = cv2.imread(filename)\n height, width = 48, 32\n img = cv2.resize(img, (height, width))\n for h in range(0, height):\n for w in range(0, width):\n input_images[index][w + h * width] = img[w, h]\n print(index)\n input_labels[index][i] = 1\n index += 1\n\n with tf.Session() as sess:\n # 加载模型\n saver = tf.train.import_meta_graph('./models/models.meta')\n saver.restore(sess, tf.train.latest_checkpoint(model_path))\n graph = tf.get_default_graph()\n # 从模型中加载变量\n x_ = graph.get_tensor_by_name(\"input_x:0\")\n keep_prob = graph.get_tensor_by_name(\"Placeholder:0\")\n y_ = graph.get_tensor_by_name(\"add_3:0\")\n labels = graph.get_tensor_by_name(\"test_y:0\")\n result = tf.argmax(tf.nn.softmax(y_), 1) # 预测卡号\n accuracy = graph.get_tensor_by_name(\"Mean_1:0\") # 正确率计算\n result = sess.run(result, feed_dict={x_: input_images, labels: input_labels, keep_prob: 1.0})\n grid = accuracy.eval(feed_dict={x_: input_images, labels: input_labels, keep_prob: 1.0})\n print(result) # 预测结果\n print(grid) # 输出正确率\n return (result, grid)\n\n\ndef main():\n img_dir = './test_img/'\n '''\n 此处为测试图片目录\n 格式为\n --test_img\n --0/\n --1/\n --2/\n ...\n ...\n --9/\n '''\n model_path = './models/' # 此处为模型加载路径\n test_model(img_dir, model_path)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"CNN_test01.py","file_name":"CNN_test01.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"203900822","text":"#!/usr/bin/python\nfrom __future__ import print_function\n\nimport pylab as pl\nimport xml.etree.ElementTree as ET\n\ndef main():\n\tgrag = Champ('grag')\n\tannie = Champ('annie')\n\tscp = Scope()\n\tscp.ap = 0\n\tscp.lvl = 18\n\tscp.ohp = 800\n\tgrag.spellDamage( scp, 'q', 'w', 'e', 'r')\n\told = 0\n\toldA = 0\n\tdiffs = []\n\tdiffsA = []\n\tdams = []\n\tdamsA = []\n\tlvls = []\n\tfor i in range(1,19):\n\t\tprint(\"Lvl: \" + str(i))\n\t\tscp.lvl = i\n\t\tlvls.append(i)\n\t\tdam = grag.spellDamage( scp, 'q', 'w', 'e', 'r')\n\t\tdamA = annie.spellDamage( scp, 'q', 'w', 'e', 'r')\n\t\tdiffs.append(dam - old)\n\t\tdiffsA.append(damA - oldA)\n\t\tdams.append(dam)\n\t\tdamsA.append(damA)\n\t\told = dam\n\t\toldA = damA\n\tprint(diffs)\n\tpl.plot(lvls, dams)\n\tpl.plot(lvls, damsA, color=\"red\")\n\tpl.show()\n\n\nclass Scope:\n\tdef __init__(self):\n\t\tself.ap = 100\n\t\tself.ad = 0\n\t\tself.ohp = 1500\n\t\tself.lvl = 11\n\nclass Champ:\n\tdef __init__(self, name):\n\t\tself.getChampDetails(name)\n\t\n\n\tdef setSplLvels( self, splLvls):\n\t\tif ( len( splLvls ) != 18 ):\n\t\t\twarn(\"Incorrect spell leveling.\")\n\t\t\tsys.exit()\n\t\tself.skillOrder = splLvls\n\n\tdef getChampDetails(self, name):\n\t\ttree = ET.parse(name+'.xml')\n\t\troot = tree.getroot()\n\t\tfor child in root:\n\t\t\ttag = child.tag\n\t\t\tval = child.text\n\t\t\tif ( child.tag == 'name' ):\n\t\t\t\tself.champName = val\n\t\t\telif ( tag == 'defSplLvls' ):\n\t\t\t\tself.skillOrder = commaToArray( val )\n\t\t\telif ( tag == 'stats' ):\n\t\t\t\tself.getChampStats( child )\n\t\t\telif ( tag == 'q' or tag == 'w' or tag == 'e' or tag == 'r' ):\n\t\t\t\tself.getSpellStats( tag, child )\n\t\n\tdef getChampStats( self, xml ):\n\t\tself.stats = dict()\n\t\tfor child in xml:\n\t\t\ttag = child.tag\n\t\t\tval = child.text\n\t\t\tif ',' in val:\n\t\t\t\tself.stats[tag] = commaToArray(val)\n\t\t\telse:\n\t\t\t\tself.stats[tag] = float(val)\n\n\tdef getSpellStats( self, spl, xml ):\n\t\tspell = dict()\n\t\tfor child in xml:\n\t\t\ttag = child.tag\n\t\t\tval = child.text\n\t\t\tif ',' in val:\n\t\t\t\tspell[tag] = commaToArray(val)\n\t\t\telse:\n\t\t\t\tspell[tag] = float(val)\n\t\tif ( spl == 'q' ):\n\t\t\tself.q = spell\n\t\telif ( spl == 'w'):\n\t\t\tself.w = spell\n\t\telif ( spl == 'e'):\n\t\t\tself.e = spell\n\t\telif ( spl == 'r'):\n\t\t\tself.r = spell\n\n\tdef spellDamage( self, scope, *spls ):\n\t\tdam = 0\n\t\tif ( len( spls ) > 4 ):\n\t\t\twarn(\"TOO MANY SPELLS\")\n\t\t\tsys.exit()\n\t\tfor spl in spls:\n\t\t\tif ( spl == 'q' ):\n\t\t\t\tdam += self.splDamage( spl, self.q, scope )\n\t\t\telif ( spl == 'w' ):\n\t\t\t\tdam += self.splDamage( spl, self.w, scope )\n\t\t\telif ( spl == 'e' ):\n\t\t\t\tdam += self.splDamage( spl, self.e, scope )\n\t\t\telif ( spl == 'r' ):\n\t\t\t\tdam += self.splDamage( spl, self.r, scope )\n\t\tprint(\"TOTAL DAMAGE: \" + str(dam));\n\t\treturn dam\n\n\tdef getLevel( self, c, lvl, arr ):\n\t\tval = 0.0\n\t\tj = 0\n\t\tfor i in range(0,int(lvl),1):\n\t\t\tif self.skillOrder[i] == c:\n\t\t\t\tval = float(arr[j])\n\t\t\t\tj += 1\n\t\treturn val\n\t\n\tdef splDamage( self, spl, splDet, scope ):\n\t\tlvl = scope.lvl\n\t\tdam = self.getLevel( spl, lvl, splDet['base'])\n\t\tif 'apRatio' in splDet:\n\t\t\tdam += scope.ap * float(splDet['apRatio'])\n\t\tif 'adRatio' in splDet:\n\t\t\tdam += (self.stats['adBase'] + ( lvl * self.stats['adGrow'] ) ) * float(splDet['adRatio'])\n\t\tif 'opHPRatio' in splDet:\n\t\t\tif type(splDet['opHPRatio']) is list:\n\t\t\t\tdam += scope.ohp * self.getLevel( spl, lvl, splDet['opHPRatio'] )\n\t\t\telse:\n\t\t\t\tdam += scope.ohp * splDet['opHPRatio']\n\t\t#print(\"Spell: \" + spl + \" dam: \" + str(dam))\n\t\t# TODO REDUCE DAMAGE BASED ON SCOPE.\n\t\treturn dam\n\n\tdef qDamage( self, scope ):\n\t\tlvl = scope.lvl\n\t\tdam = self.getLevel( 'q', lvl, self.q['base'])\n\t\tif 'apRatio' in self.q:\n\t\t\tdam += scope.ap * float(self.q['apRatio'])\n\t\tprint(dam)\n\t\treturn dam\n\tdef wDamage( self, scope ):\n\t\tsplDet = self.w\n\t\tlvl = scope.lvl\n\t\tdam = self.getLevel( 'w', lvl, splDet['base'])\n\t\tif 'apRatio' in splDet:\n\t\t\tdam += scope.ap * float(splDet['apRatio'])\n\t\tif 'adRatio' in splDet:\n\t\t\tdam += (self.stats['adBase'] + ( lvl * self.stats['adGrow'] ) ) * float(splDet['adRatio'])\n\t\tprint(dam)\n\t\t# TODO REDUCE DAMAGE BASED ON SCOPE.\n\t\treturn dam\n\tdef eDamage( self, scope ):\n\t\tlvl = scope.lvl\n\t\tdam = self.getLevel( 'e', lvl, self.e['base'])\n\t\tif 'apRatio' in self.e:\n\t\t\tdam += scope.ap * float(self.e['apRatio'])\n\t\tprint(dam)\n\t\treturn dam\n\tdef rDamage( self, scope ):\n\t\tlvl = scope.lvl\n\t\tdam = self.getLevel( 'r', lvl, self.r['base'])\n\t\tif 'apRatio' in self.r:\n\t\t\tdam += scope.ap * float(self.r['apRatio'])\n\t\tprint(dam)\n\t\treturn dam\n\n\t\t\n\nclass Spell:\n\tdef __init__(self):\n\t\tprint(\"dur\")\n\t\t#base = []\n\t\t#adRatio = 0.0\n\t\t#adRatio = 0.0\n\t\t#opHPRatio = 0.0\n\t\t#hPRatio = 0.0\n\t\t#manaRatio = 0.0\n\t\t#armRatio = 0.0\n\t\t#mrRatio = 0.0\n\ndef commaToArray( commaStr ):\n\tret = commaStr.split(',')\n\tfor thing in ret:\n\t\tthing = thing.strip()\n\treturn ret\n\ndef warn(*objs):\n\tprint(\"WARNING: \", *objs, file=sys.stderr)\n\n\nmain()\n","sub_path":"character.py","file_name":"character.py","file_ext":"py","file_size_in_byte":4642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"461063467","text":"import os\r\nimport fnmatch\r\nimport glob\r\nfrom os.path import relpath\r\n\r\n\r\ndef file_names_in_tree_root(treeroot, create_file_dir, file_name):\r\n file_path = os.path.join(create_file_dir, file_name)\r\n if os.path.isfile(file_path):\r\n os.remove(file_path)\r\n\r\n paths = []\r\n last_path = None\r\n for filename in glob.iglob(treeroot + '**/**', recursive=True):\r\n if os.path.isfile(os.path.join(treeroot, filename)):\r\n if not (filename.endswith(\".jpg\") or filename.endswith(\".mat\") or filename.endswith(\".png\")):\r\n continue\r\n new_path = relpath(filename.split('.')[0], treeroot)\r\n # print(f\"new: {new_path} \\t\\t olf: {last_path} \\n\")\r\n if last_path == new_path:\r\n continue\r\n # print(\"ssss\")\r\n paths.append(new_path)\r\n last_path = new_path\r\n\r\n paths = sorted(paths)\r\n print(f\"number of files found: {len(paths)}\")\r\n\r\n with open(file_path, 'w') as f:\r\n for path in paths:\r\n f.write(f\"{path}\\n\")\r\n\r\n return file_path, paths\r\n\r\n\r\nif __name__ == \"__main__\":\r\n def main():\r\n test_path_windows = r\"C:\\Noam\\Code\\vision_course\\downloads\\datasets\\300W-LP\\big_set\\300W_LP\"\r\n test_path_linux = r\"/home/noams/hopenet/deep-head-pose/code/Data/Training/300W_LP\"\r\n create_at = test_path_linux\r\n file_name = \"rel_paths.txt\"\r\n paths = file_names_in_tree_root(test_path_linux, create_at, file_name)\r\n print(paths)\r\n\r\n main()\r\n","sub_path":"code/Utils/create_filename_list.py","file_name":"create_filename_list.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"130364937","text":"#%% imports\nimport uuid\nimport json\nimport requests\n\n#%% set mandatory parameters\nclientAccessToken = '433d3c40b242412db2c879f56014e84e'\nheader = {'Authorization': 'Bearer ' + clientAccessToken}\nv = '20150910'\nsessionId = str(uuid.uuid4())\nlang = 'EN'\nurl_base = 'https://api.api.ai/api/query'\n\n#%% interactive loop\n\ni = 1\nwhile i == 1:\n # construct the query\n query = input(\">\")\n url = url_base+'?v='+v+'&query='+query+'&lang='+lang+'&sessionId='+sessionId\n \n # get the response\n response = requests.get(url, headers=header)\n \n # parse & print the speech response\n response_json = json.loads(response.text)\n speech = response_json['result']['fulfillment']['speech']\n print(speech)\n","sub_path":"alberto.py","file_name":"alberto.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"447517622","text":"# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport time\nimport math\nimport subprocess\nimport linecache\n\nimport click\n\n# Number of problems present in problems.txt\nTOTAL_PROBLEMS = 256\n\n\ndef format_time(timespan, precision=3):\n \"\"\"Formats the timespan in a human readable form\"\"\"\n\n if timespan >= 60.0:\n # Format time greater than one minute in a human readable format\n # Idea from http://snipplr.com/view/5713/\n parts = [('d', 60*60*24), ('h', 60*60), ('min', 60), ('s', 1)]\n time_parts = []\n leftover = timespan\n for suffix, length in parts:\n value = int(leftover / length)\n if value > 0:\n leftover = leftover % length\n time_parts.append('%s%s' % (str(value), suffix))\n if leftover < 1:\n break\n return ' '.join(time_parts)\n\n\n # Unfortunately, the Unicode 'micro' symbol can cause problems in\n # certain terminals (see https://bugs.launchpad.net/ipython/+bug/348466)\n # Try to prevent crashes by being more secure than it needs to be\n # eg. Eclipse is able to print a µ, but has no sys.stdout.encoding set.\n units = ['s', 'ms', 'us', 'ns'] # the save value\n if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:\n try:\n micro = b'\\xc2\\xb5s'.decode('utf-8')\n units = ['s', 'ms', micro, 'ns']\n except:\n pass\n scaling = [1, 1e3, 1e6, 1e9]\n\n if timespan > 0.0:\n order = min(-int(math.floor(math.log10(timespan)) // 3), 3)\n else:\n order = 3\n\n return '%.*g %s' % (precision, timespan * scaling[order], units[order])\n\n\ndef get_filename(problem):\n \"\"\"Returns filename in the form `001.py`\"\"\"\n return '{0:03d}.py'.format(problem)\n\n\ndef get_solution(problem):\n \"\"\"Returns the answer to a given problem\"\"\"\n solutionsFile = os.path.join(os.path.dirname(__file__), 'solutions.txt')\n line = linecache.getline(solutionsFile, problem)\n\n # Isolate answer from the question number and trailing newline\n answer = line.split(\". \")[1].strip()\n\n if answer == '':\n click.echo('No known answer for problem #{0}.'.format(problem))\n click.echo('If you have an answer, consider submitting a pull ' +\n 'request at https://github.com/iKevinY/EulerPy.')\n return None\n else:\n return answer\n\n\ndef verify_answer(problem):\n filename = get_filename(problem)\n\n if not os.path.isfile(filename):\n click.secho('Error: \"{0}\" not found.'.format(filename), fg='red')\n sys.exit(1)\n\n solution = get_solution(problem)\n\n if solution:\n click.echo('Checking \"{0}\" against solution: '.format(filename), nl=False)\n\n cmd = 'python {0}'.format(filename)\n wall_start = time.time()\n proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)\n output, _ = proc.communicate()\n wall_end = time.time()\n\n # Calculate the wall time and format the output\n wall_time = wall_end - wall_start\n time_info = 'Time elapsed: {0}'.format(format_time(wall_time))\n\n # Python 3 returns bytes; use a valid encoding like ASCII as the output\n # will fall in that range\n if isinstance(output, bytes):\n output = output.decode('ascii')\n\n return_val = proc.poll()\n\n if return_val:\n click.secho('Error calling \"{0}\".'.format(filename), fg='red')\n sys.exit(1)\n\n # Strip newline from end of output if output is not a lone newline.\n # This behaviour is favourable to stripping all whitespace with strip()\n # as stripping all newlines from the output may inhib debugging done by\n # the user (if they were to use multiple print statements in their code\n # while in the process of atempting to solve the problem).\n try:\n if output[-1] == '\\n':\n output = output[:-1]\n except IndexError:\n output = \"[no output]\"\n\n # If there is still a newline, the output is multi-lined. Print the\n # first line of the output on a separate line from the \"checking\n # against solution\" message. Additionally, a multi-line output is\n # not going to be correct, so skip the solution check.\n if '\\n' in output:\n is_correct = False\n click.secho('\\n' + output, bold=True, fg='red')\n else:\n is_correct = output.strip() == solution\n fg_colour = 'green' if is_correct else 'red'\n click.secho(output, bold=True, fg=fg_colour)\n\n click.secho(time_info, fg='cyan')\n return is_correct\n\n\ndef get_problem(problem):\n problemsFile = os.path.join(os.path.dirname(__file__), 'problems.txt')\n problemLines = []\n\n with open(problemsFile, 'r') as file:\n isProblemText = False\n sequentialBreaks = 0\n\n for line in file:\n if line.strip() == 'Problem {0}'.format(problem):\n isProblemText = True\n\n if isProblemText:\n if line == '\\n':\n sequentialBreaks += 1\n else:\n sequentialBreaks = 0\n\n # Two subsequent empty lines indicates that the current\n # problem text has ended, so stop iterating over file\n if sequentialBreaks >= 2:\n break\n else:\n problemLines.append(line[:-1])\n\n return '\\n'.join(problemLines[3:])\n\n\ndef generate_file(problem, default=True):\n click.confirm(\"Generate file for problem #{0}?\".format(problem),\n default=default, abort=True)\n problemText = get_problem(problem)\n\n filename = get_filename(problem)\n\n if os.path.isfile(filename):\n click.secho('\"{0}\" already exists. Overwrite?'.format(filename),\n fg='red', nl=False)\n click.confirm('', abort=True)\n\n problemHeader = 'Project Euler Problem #{0}\\n'.format(problem)\n problemHeader += '=' * len(problemHeader) + '\\n\\n'\n\n with open(filename, 'w') as file:\n file.write('\"\"\"\\n')\n file.write(problemHeader)\n file.write(problemText)\n file.write('\"\"\"\\n\\n\\n')\n\n click.echo('Successfully created \"{0}\".'.format(filename))\n\n\ndef generate_first_problem():\n click.echo(\"No Project Euler files found in the current directory.\")\n generate_file(1)\n sys.exit()\n\n\ndef view_solution(problem):\n solution = get_solution(problem)\n\n if solution:\n click.confirm(\"View answer to problem #{0}?\".format(problem), abort=True)\n click.echo(\"The answer to problem #{0} is \".format(problem), nl=False)\n click.secho(solution, bold=True, nl=False)\n click.echo(\".\")\n\n\ndef preview_problem(problem):\n click.secho(\"Project Euler Problem #{0}\".format(problem), bold=True)\n click.echo(get_problem(problem)[:-1]) # strip trailing newline\n\n\ndef determine_largest_problem():\n for problem in reversed(range(1, TOTAL_PROBLEMS + 1)):\n if os.path.isfile(get_filename(problem)):\n return problem\n else:\n return False\n\n\nhelp = {\n 'cheat': 'View the answer to a problem.',\n 'generate': 'Generates Python file for a problem.',\n 'skip': 'Generates Python file for the next problem.',\n 'preview': 'Prints the text of a problem.',\n 'verify': 'Verifies the solution to a problem.',\n}\n\n@click.command(name='euler', options_metavar='[OPTION]')\n@click.argument('problem', default=0, type=click.IntRange(0, TOTAL_PROBLEMS))\n@click.option('--cheat', '-c', 'option', flag_value='cheat', help=help['cheat'])\n@click.option('--generate', '-g', 'option', flag_value='generate', help=help['generate'])\n@click.option('--skip', '-s', 'option', flag_value='skip', help=help['skip'])\n@click.option('--preview', '-p', 'option', flag_value='preview', help=help['preview'])\n@click.option('--verify', '-v', 'option', flag_value='verify', help=help['verify'])\ndef main(option, problem):\n \"\"\"Python tool to streamline Project Euler.\"\"\"\n\n # No option given\n if option is None:\n if problem == 0:\n problem = determine_largest_problem()\n # No Project Euler files in current directory\n if not problem:\n generate_first_problem()\n\n # If correct answer was given, generate next problem file\n if verify_answer(problem):\n generate_file(problem + 1)\n else:\n if os.path.isfile(get_filename(problem)):\n verify_answer(problem)\n else:\n generate_file(problem)\n\n else:\n # Handle options that ignore a problem argument\n if option == 'skip':\n problem = determine_largest_problem()\n click.echo(\"Current problem is problem #{0}.\".format(problem))\n generate_file(problem + 1, default=False)\n\n # Handle other options\n else:\n if problem == 0:\n problem = determine_largest_problem()\n\n if not problem:\n if option == 'preview':\n problem = 1\n else:\n generate_first_problem()\n\n funcs = {\n 'cheat': view_solution,\n 'generate': generate_file,\n 'preview': preview_problem,\n 'verify': verify_answer,\n }\n\n # Execute function\n funcs[option](problem)\n\n sys.exit()\n","sub_path":"EulerPy/euler.py","file_name":"euler.py","file_ext":"py","file_size_in_byte":9426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"605934242","text":"# coding:utf-8\n\nimport csv\nimport os\n\ndomain_entity_dict = {}\ncurrent_path = os.getcwd()\nwith open(current_path + '/../data/domain_dict.csv', 'r', encoding=\"utf-8\") as csvfile:\n\treader = csv.reader(csvfile, delimiter=',')\n\tfor row in reader:\n\t\tdomain_entity_dict[str(row[0])] = int(row[1])","sub_path":"kgcar/nlp/create_entity_dict.py","file_name":"create_entity_dict.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"438099552","text":"'''\nCSS 430 Assignment 2 Scheduling\nAssumptions:\n1. Input file is sorted by arrival time (does this matter???)\n2. Input file is well formatted\n'''\nimport queue\n\nclass Process:\n def __init__(self, num, aT, bT, priority):\n self.num = num\n self.aT = aT\n self.bT = bT\n self.priority = priority\n\n def __lt__(self, other):\n if self.priority == other.priority:\n return self.bT < other.bT\n\n return self.priority < other.priority\n\n def __gt__(self, other):\n if self.priority == other.priority:\n return self.bT > other.bT\n return self.priority > other.priority\n \n def __str__(self):\n return 'P' + str(self.num)\n\n def _repr_html_(self):\n return 'Process [' + str(self.aT) + ', ' + str(self.bT) + ', ' + str(self.priority) + ']'\n\n def runOne(self):\n self.bT -= 1\n\n def isCompleted(self):\n return bT == 0\n\ndef main():\n filename = input('Type in input file: (must be .txt file)\\n')\n processes = readFile(filename)\n \n #quantum = input('Enter value for quantum size (ms): ')\n #print('p_arrival: ', end = '')\n #print(p_arrival)\n #print('p_cpu: ', end = '')\n #print(p_cpu)\n p_arrival = []\n for p in processes:\n p_arrival.append(p.aT)\n timeline = getTimeline(processes)\n \n tats = getAllTat(p_arrival, timeline)\n wt = getAllwt(p_arrival, timeline)\n\n printAll(timeline, tats, wt)\n\ndef readFile(filename):\n #get input from input file\n #filename = input('Type in input file: (must be .txt file) \\n')\n f = open(filename, 'r')\n f_lines = f.readlines() #convert input into list \n #size = len(f_lines) #number of processes\n ans = []\n #storing to list\n for line in f_lines:\n l_arr = line.split()\n num = int(l_arr[0][1:]) - 1 #num starts at 0 so we can reuse functions from previous parts\n aT = int(l_arr[1])\n bT = int(l_arr[2])\n priority = l_arr[3]\n ans.append(Process(num, aT, bT, priority))\n\n f.close()\n\n return ans\n\ndef printQueue(q):\n if q.qsize() is not 0:\n val = q.get()\n arr = [val]\n print('[' + str(val) + '', end = '')\n q.put(val)\n \n for _ in range(1, q.qsize()):\n val = q.get()\n arr.append(val)\n print(', ' + str(val), end = '')\n q.put(val)\n print(']')\n else:\n print('[]')\n\ndef getTimeline(processes, quantum = 3):\n currProcess = 0 #current working process (index)\n #counter = quantum\n timeline = []\n\n total_time = 0\n for p in processes:\n total_time += p.bT\n\n q = []\n \n currProcess = Process(0, 0, 0, 0)\n\n #arrived = []\n #running all processes\n \n for sec in range(total_time):\n #put arrived processes in queue\n for p in processes:\n if sec == p.aT:\n q.append(p)\n q.sort()\n \n if sec is 0:\n currProcess = q.pop(0)\n elif sec%quantum is 0:\n if currProcess.bT > 0: #if previous process bust time > 0 (note that currProess here is previous process because it hasn't been updated yet)\n q.append(currProcess)\n q.sort()\n currProcess = q.pop(0)\n\n currProcess.runOne()\n\n if currProcess.bT >= 0: #if bT == 0 means process has just completed \n timeline.append(currProcess.num)\n else:\n timeline.append(-1)\n \n \n \n\n\n\n #if currProcess.bT is not 0 and : #put back in queue and end of quantum if it has burst time left\n # q.append(currProcess)\n \n\n #timeline.append(currProcess.num)\n print('second' + str(sec) + ': ', end = ' ')\n print(timeline)\n return timeline\n\ndef rindex(arr, val):\n rarr = arr[::-1] #reverse array\n return len(arr) - 1 - rarr.index(val)\n\ndef getTat(p_arrival, timeline, pid):\n #last instance - arrival time\n return rindex(timeline, pid) - p_arrival[pid] + 1\n\ndef getAllTat(p_arrival, timeline):\n tats = []\n numP = len(p_arrival)\n for pid in range(numP):\n tats.append(getTat(p_arrival, timeline, pid))\n return tats\n\ndef getWaitTime(p_arrival, timeline, pid):\n start = p_arrival[pid]\n end = rindex(timeline, pid) + 1\n tl_subset = timeline[start:end]\n return len(tl_subset) - tl_subset.count(pid)\n\ndef getAllwt(p_arrival, timeline):\n wt = []\n numP = len(p_arrival)\n for pid in range(numP):\n wt.append(getWaitTime(p_arrival, timeline, pid))\n return wt\n\ndef printAll(timeline, tats, wt):\n printTimeline(timeline)\n printTat(tats)\n printWt(wt)\n\ndef printTimeline(timeline):\n print('TIMELINE:')\n for sec in range(len(timeline)):\n if timeline[sec] >= 0:\n p = 'P'+str(timeline[sec]) #add plus one here\n else:\n p = 'NO'\n print(p.rjust(4), end = '')\n \n print()\n\n for sec in range(len(timeline)+1):\n print(str(sec).ljust(4), end = '')\n\n print('\\n')\n\ndef printTat(tats):\n print('Turnaround Time(s):')\n for i in range(len(tats)):\n print('P' + str(i) + ': ' + str(tats[i]).ljust(3) + 's') #add plus one at str(i)\n print()\n\ndef printWt(wt):\n print('Waiting Time(s):')\n for i in range(len(wt)):\n print('P' + str(i) + ': ' + str(wt[i]).ljust(3) + 's') #add plus one at str(i)\n avg = sum(wt)/len(wt)\n print('Average wait time: ' + str(avg) + 's')\n print()\n\n\n \n\nif __name__ == '__main__':\n main()","sub_path":"ass2p3timegap.py","file_name":"ass2p3timegap.py","file_ext":"py","file_size_in_byte":5491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"283244170","text":"\n\nclass BinaryTree(object):\n\t\"\"\"docstring for BinaryTree\"\"\"\n\tdef __init__(self, arg):\n\t\tself.key = arg\n\t\tself.leftChild = None\n\t\tself.rightChild = None\n\t\t\n\tdef insertLeft(self, node):\n\t\tif not self.leftChild:\n\t\t\tself.leftChild = BinaryTree(node)\n\t\telse:\n\t\t\ttmp = BinaryTree(node)\n\t\t\ttmp.leftChild = self.leftChild\n\t\t\tself.leftChild = tmp\n\t\treturn self.leftChild\n\t\t\n\tdef insertRight(self, node):\n\t\tif not self.rightChild:\n\t\t\tself.rightChild = BinaryTree(node)\n\t\telse:\n\t\t\ttmp = BinaryTree(node)\n\t\t\ttmp.rightChild = self.rightChild\n\t\t\tself.rightChild = tmp\n\t\treturn self.rightChild\n\t\t\n\tdef getRootVal(self):\n\t\treturn self.key\n\t\t\n\tdef setRootVal(self, newval):\n\t\tself.key = newval\n\t\t\n\t\t\ndef parse_expr_to_tree(expr):\n\tstack = []\n\toperators = ['+', '-', '*', '/']\n\texpr_list = list(expr)\n\texpr_list = [x for x in expr_list if not x.isspace()]\n\ttree = BinaryTree('')\n\tcurrent_node = tree\n\tstack.append(current_node)\n\tfor char in expr_list:\n\t\tif char == '(':\n\t\t\tstack.append(current_node)\n\t\t\tcurrent_node = current_node.insertLeft('')\n\t\t\t\n\t\telif char.isdigit():\n\t\t\tcurrent_node.setRootVal(char)\n\t\t\tcurrent_node = stack.pop()\n\t\t\t\n\t\telif char in operators:\n\t\t\tcurrent_node.setRootVal(char)\n\t\t\tstack.append(current_node)\n\t\t\tcurrent_node = current_node.insertRight('')\n\t\t\t\n\t\telif char is ')':\n\t\t\tcurrent_node = stack.pop()\n\t\t\t\n\telse:\n\t\tassert tree\n\t\treturn tree\n\t\t\n\t\t\ndef eval_tree(tree):\n\toperator_map = {\n\t'+': int.__add__,\n\t'-': int.__sub__,\n\t'/': int.__div__,\n\t'*': int.__mul__\n\t}\n\t\n\toperator = tree.getRootVal()\n\tleft_op = tree.leftChild.getRootVal()\n\tright_op = tree.rightChild.getRootVal()\n\t\n\tif type(left_op) is int or left_op.isdigit():\n\t\tleft_int = int(left_op)\n\telif left_op in operator_map.keys():\n\t\tleft_int = eval_tree(tree.leftChild)\n\t\t\n\tif type(right_op) is int or right_op.isdigit():\n\t\tright_int = int(right_op)\n\telif right_op in operator_map.keys():\n\t\tright_int = eval_tree(tree.rightChild)\n\t\t\n\tfunc = operator_map[operator]\n\ttotal = func(left_int, right_int)\n\treturn total\n\n","sub_path":"sort/node_tree_3.py","file_name":"node_tree_3.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"447457025","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.6 (62161)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/herbert/dev/python/sctdev/simpleproject/simpleproject/../../communitytools/sphenecoll/sphene/sphwiki/wikilink_utils.py\n# Compiled at: 2012-03-17 12:42:14\nimport re\nfrom sphene.sphwiki.models import WikiSnip\nfrom sphene.community.sphutils import get_sph_setting\nfrom sphene.community.middleware import get_current_group\nimport logging\nlog = logging.getLogger('wikilink_utils')\nWIKILINK_RE = '((?P.*?\\\\\\\\|\\\\b)?(?P(((?P([A-Z]+[a-z-_0-9]+){2,})\\\\b)|\\\\[(?P[A-Za-z-_/0-9]+)(\\\\|(?P.+?))?\\\\])))'\nWIKILINK_RE = get_sph_setting('wikilink_regexp', WIKILINK_RE)\nWIKILINK_RE_COMPILED = re.compile(WIKILINK_RE)\n\ndef get_wikilink_regex_pattern():\n return WIKILINK_RE\n\n\ndef get_wikilink_regex():\n return WIKILINK_RE_COMPILED\n\n\ndef handle_wikilinks_match(matchgroups):\n if matchgroups.get('urls'):\n return {'label': matchgroups.get('urls')}\n if matchgroups.get('escape'):\n return {'label': matchgroups.get('wholeexpression')}\n snipname = matchgroups.get('camelcase') or matchgroups.get('snipname')\n label = matchgroups.get('sniplabel') or snipname.replace('_', ' ')\n cssclass = 'sph_wikilink'\n try:\n snip = WikiSnip.objects.get(group=get_current_group(), name=snipname)\n href = snip.get_absolute_url()\n except WikiSnip.DoesNotExist:\n try:\n snip = WikiSnip(group=get_current_group(), name=snipname)\n except TypeError:\n log.error('No group found when getting wikilinks. Ignoring.')\n return {'label': label}\n else:\n if not snip.has_edit_permission() and get_sph_setting('wiki_links_nonexistent_show_only_privileged'):\n return {'label': label}\n href = snip.get_absolute_editurl()\n cssclass += ' sph_nonexistent'\n if get_sph_setting('wiki_links_nonexistent_prefix'):\n label = 'create:' + label\n\n return {'href': href, 'label': label, \n 'class': cssclass}\n\n\ndef render_wikilinks_match(match):\n wikilink = handle_wikilinks_match(match.groupdict())\n if 'href' not in wikilink:\n return wikilink['label']\n return '%s' % (wikilink['href'], wikilink['class'], wikilink['label'])\n\n\ndef render_wikilinks(source):\n done = WIKILINK_RE_COMPILED.sub(render_wikilinks_match, source)\n return done","sub_path":"pycfiles/django-sct-0.7.tar/wikilink_utils.py","file_name":"wikilink_utils.py","file_ext":"py","file_size_in_byte":2545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"427403963","text":"# -*- coding: utf-8 -*-\r\n\r\nimport datetime\r\n\r\nfrom sqlalchemy.engine.url import URL\r\nfrom sqlalchemy.ext.declarative import declarative_base\r\nfrom sqlalchemy import create_engine, Column, Integer, String, Text, DateTime\r\nfrom data_qq_report_spider.settings import DATABASE\r\n\r\n\r\ndef db_connect():\r\n return create_engine(URL(**DATABASE))\r\n\r\n\r\ndef create_news_table(engine):\r\n Base.metadata.create_all(engine)\r\n\r\n\r\nBase = declarative_base()\r\n\r\n\r\nclass Article(Base):\r\n __tablename__ = 'article'\r\n\r\n id = Column(Integer, primary_key=True)\r\n article_title = Column(String(255))\r\n article_ctn = Column(Text)\r\n\r\n\r\nclass Increment(Base):\r\n __tablename__ = 'increment_verify'\r\n\r\n id = Column(Integer, primary_key=True)\r\n crawl_link = Column(String(255))\r\n crawl_md = Column(String(32))\r\n","sub_path":"practices/data_qq_report_spider/data_qq_report_spider/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"477556609","text":"class RandomizedSet:\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.container = []\n self.position_mem = {}\n\n def insert(self, val):\n \"\"\"\n Inserts a value to the set. Returns true if the set did not already contain the specified element.\n :type val: int\n :rtype: bool\n \"\"\"\n if val not in self.position_mem:\n self.container.append(val)\n self.position_mem[val] = len(self.container) - 1\n return True\n return False\n \n\n def remove(self, val):\n \"\"\"\n Removes a value from the set. Returns true if the set contained the specified element.\n :type val: int\n :rtype: bool\n \"\"\"\n if val in self.position_mem:\n position = self.position_mem[val]\n # move last number to this location\n self.position_mem[self.container[-1]] = position\n self.container[position], self.container[-1] = self.container[-1], self.container[position]\n self.container.pop()\n del(self.position_mem[val])\n return True\n return False\n\n def getRandom(self):\n \"\"\"\n Get a random element from the set.\n :rtype: int\n \"\"\"\n import random\n random.seed()\n return self.container[random.randint(0, len(self.container) - 1)]","sub_path":"380_Insert_Delete_GetRandom/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"607367807","text":"import os\n\nimport tensorflow as tf\nfrom transformers_keras.modeling_albert import Albert\nfrom transformers_keras.modeling_bert import Bert\n\nBASE_DIR = os.environ.get('BASE_DIR')\nif not BASE_DIR:\n BASE_DIR = '/home/zhouyang.lzy/pretrain-models'\nos.environ.update({'CUDA_VISIBLE_DEVICES': '-1'})\n\n\nclass LoadPretrainedModelTest(tf.test.TestCase):\n\n def _do_predict(self, model):\n input_ids = tf.constant([1, 2, 3, 4, 5, 6, 7, 8], shape=(2, 4))\n # output_1 should be all close to output_2\n _, outputs_1, _, _ = model.predict((input_ids,))\n print(outputs_1)\n _, outputs_2, _, _ = model(inputs=(input_ids,))\n print(outputs_2)\n\n def test_load_pretrained_bert(self):\n model_paths = [\n 'chinese_wwm_ext_L-12_H-768_A-12',\n 'chinese_L-12_H-768_A-12',\n 'chinese_roberta_wwm_ext_L-12_H-768_A-12',\n 'chinese_roberta_wwm_large_ext_L-24_H-1024_A-16'\n ]\n for p in model_paths:\n model = Bert.from_pretrained(os.path.join(BASE_DIR, p))\n model.summary()\n self._do_predict(model)\n\n def test_load_pretrained_albert(self):\n model_paths = [\n 'albert_base_zh', 'albert_large_zh', 'albert_xlarge_zh'\n ]\n for p in model_paths:\n model = Albert.from_pretrained(os.path.join(BASE_DIR, p))\n model.summary()\n self._do_predict(model)\n\n def test_bert_classify(self):\n\n def _build_bert_model(trainable=True):\n input_ids = tf.keras.layers.Input(shape=(None,), dtype=tf.int32, name='input_ids')\n segment_ids = tf.keras.layers.Input(shape=(None,), dtype=tf.int32, name='segment_ids')\n\n bert = Bert.from_pretrained(os.path.join(BASE_DIR, 'chinese_wwm_ext_L-12_H-768_A-12'))\n bert.trainable = trainable\n\n sequence_output, pooled_output, _, _ = bert(inputs=(input_ids, segment_ids))\n outputs = tf.keras.layers.Dense(2, name='output')(pooled_output)\n model = tf.keras.Model(inputs=[input_ids, segment_ids], outputs=outputs)\n model.compile(loss='binary_cross_entropy', optimizer='adam')\n return model\n\n for trainable in [True, False]:\n model = _build_bert_model(trainable)\n model.summary()\n\n def test_albert_classify(self):\n\n def _build_albert_model(trainable=True):\n input_ids = tf.keras.layers.Input(shape=(None,), dtype=tf.int32, name='input_ids')\n segment_ids = tf.keras.layers.Input(shape=(None,), dtype=tf.int32, name='segment_ids')\n\n albert = Albert.from_pretrained(os.path.join(BASE_DIR, 'albert_large_zh'))\n albert.trainable = trainable\n\n sequence_output, pooled_output, _, _ = albert(inputs=(input_ids, segment_ids))\n outputs = tf.keras.layers.Dense(2, name='output')(pooled_output)\n model = tf.keras.Model(inputs=[input_ids, segment_ids], outputs=outputs)\n model.compile(loss='binary_cross_entropy', optimizer='adam')\n return model\n\n for trainable in [True, False]:\n model = _build_albert_model(trainable)\n model.summary()\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n","sub_path":"tests/load_pretrained_test.py","file_name":"load_pretrained_test.py","file_ext":"py","file_size_in_byte":3233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"42672867","text":"from django.core.paginator import Paginator\nfrom django.db.models import F\nfrom django.shortcuts import render\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom .models import Imdb, MyRatings\n\n\n@csrf_exempt\ndef imdb_index(request):\n # Parameters.\n title = '' if request.GET.get('title') is None else request.GET.get('title')\n selected_genres = [x.lower() for x in request.GET.getlist('genres')]\n sort_by = 'prediction_desc' if request.GET.get('sort_by') is None else request.GET.get('sort_by')\n page_number = 1 if request.GET.get('page') is None else request.GET.get('page')\n\n # Get databases.\n imdb_list = Imdb.objects.all()\n my_ratings_list = MyRatings.objects.all().values()\n\n # Filter genres.\n if len(selected_genres) > 0:\n for genre in selected_genres:\n argument = {f'genre_{genre}__contains': '1'}\n imdb_list = imdb_list.filter(**argument)\n\n # Filter titles.\n imdb_list = imdb_list \\\n .filter(name__icontains=title)\n\n # Sort titles by prediction value.\n if sort_by.split(\"_\")[0] == 'prediction':\n if 'asc' in sort_by:\n imdb_list = imdb_list \\\n .order_by(F('prediction').asc(nulls_last=True), 'id') \\\n .values()\n else:\n imdb_list = imdb_list \\\n .order_by(F('prediction').desc(nulls_last=True), 'id') \\\n .values()\n # Sort titles by rating value.\n else:\n # Get all the shows already watched.\n imdb_list = imdb_list.filter(prediction__exact=None).values()\n for i, item in enumerate(imdb_list):\n imdb_list[i]['my_rating'] = next((x['my_rating'] for x in my_ratings_list if item[\"id\"] == x['imdb_id']), None)\n imdb_list = list(filter(lambda x: x['my_rating'] is not None, imdb_list))\n imdb_list = sorted(imdb_list, key=lambda x: x['my_rating'], reverse='asc' not in sort_by)\n\n paginator = Paginator(imdb_list, 20)\n page_obj = paginator.get_page(page_number)\n\n context = {\n 'imdb': page_obj,\n 'my_ratings': my_ratings_list,\n 'selected_genres': selected_genres,\n 'sort_by': sort_by,\n 'last_page': paginator.num_pages\n }\n\n return render(request, 'imdb_index.html', context)\n\n\ndef imdb_detail(request, imdb_id):\n imdb = Imdb.objects.get(id=imdb_id)\n\n context = {\n 'imdb': imdb\n }\n return render(request, 'imdb_detail.html', context)\n","sub_path":"web/src/tv/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"539274434","text":"# (C) Copyright 2013 Hewlett-Packard Development Company, L.P.\n'''\n\nThis file contains all element ID on Fusion base UI page\n\n'''\n\n\nclass FusionBasePage(object):\n ID_PAGE_LABEL = \"xpath=//div[@class='hp-page-label']/h1\"\n ID_MASTER_PANE = \"xpath=//div[contains(@class, 'hp-master-pane')]\"\n ID_ACTIVITY_CONTROL = \"hp-activity-control\"\n ID_ACTIVITY_NOTIFICATION = \"//div[@id='hp-activity-notification']\"\n ID_ACTIVE_ACTIVITY_NOTIFICATION = \"//div[@id='hp-activity-notification'][contains(@class, 'hp-active')]\"\n ID_ACTIVITY_MESSAGE = ID_ACTIVITY_NOTIFICATION + \"//div[@class='hp-message']\"\n ID_DASHBOARD = \"hp-dashboard-primary\"\n ID_EMPTYMESSAGE = \"div.hp-empty-message\"\n ID_HELP = \"css=div.hp-icon.hp-help\"\n ID_HELP_ON_THIS_PAGE = \"link=Help on this page\"\n ID_HP_LOGO = \"hp-logo\"\n ID_MAIN_BANNER = \"hp-main-banner\"\n ID_MAIN_MENU = \"hp-main-menu\"\n ID_MAIN_MENU_CONTROL = \"hp-main-menu-control\"\n ID_SEARCH_CONTROL = \"hp-search-control\"\n ID_SESSION_CONTROL = \"hp-session-control\"\n ID_SESSION_LOGOUT = \"hp-session-logout\"\n ID_MENU_LINK_ACTIVITY = \"link=Activity\"\n ID_MENU_ACTIVITY = \"xpath=.//*[@id='hp-main-menu']//li/a[text()='Activity']\"\n ID_MENU_LINK_DASHBOARD = \"link=Dashboard\"\n ID_MENU_LINK_FIRMWARE_BUNDLES = \"link=Firmware Bundles\"\n ID_MENU_LINK_SERVER_PROFILE = \"link=Server Profiles\"\n ID_MENU_LINK_LOGICAL_ENCLOSURES = \"link=Logical Enclosures\"\n ID_MENU_LINK_ENCLOSURE_GROUPS = \"link=Enclosure Groups\"\n ID_MENU_LINK_ENCLOSURES = \"link=Enclosures\"\n ID_MENU_LINK_SERVER_HARDWARE = \"link=Server Hardware\"\n ID_MENU_LINK_SERVER_HARDWARE_TYPES = \"link=Server Hardware Types\"\n ID_MENU_LINK_LOGICAL_INTERCONNECT_GROUPS = \"link=Logical Interconnect Groups\"\n ID_MENU_LINK_LOGICAL_INTERCONNECTS = \"link=Logical Interconnects\"\n ID_MENU_LINK_NETWORKS = \"link=Networks\"\n ID_MENU_LINK_NETWORK_SETS = \"link=Network Sets\"\n ID_MENU_LINK_INTERCONNECTS = \"link=Interconnects\"\n ID_MENU_LINK_DATA_CENTERS = \"link=Data Centers\"\n ID_MENU_LINK_RACKS = \"link=Racks\"\n ID_MENU_LINK_POWER_DELIVERY_DEVICES = \"link=Power Delivery Devices\"\n ID_MENU_LINK_UNMANAGED_DEVICES = \"link=Unmanaged Devices\"\n ID_MENU_LINK_SETTINGS = \"link=Settings\"\n ID_MENU_LINK_STORAGE_SYSTEMS = \"link=Storage Systems\"\n ID_MENU_LINK_STORAGE_POOLS = \"link=Storage Pools\"\n ID_MENU_LINK_STORAGE_TEMPLATES = \"link=Volume Templates\"\n ID_MENU_LINK_STORAGE_VOLUMES = \"link=Volumes\"\n ID_MENU_LINK_USERS_AND_GROUPS = \"link=Users and Groups\"\n ID_MENU_LINK_SAN_MANAGERS = \"link=SAN Managers\"\n ID_MENU_LINK_SAN = \"link=SANs\"\n ID_MENU_LINK_PROFILE_TEMPLATE = \"link=Server Profile Templates\"\n ID_SIDEBAR_CONTROL = 'hp-sidebar-control'\n ID_MENU_ONE_VIEW = \"id=hp-main-menu-labels\"\n ID_LINK_NETWORK_SET = \"link=Network Sets\"\n ID_SIDEBAR_CONTROL = 'hp-sidebar-control'\n HELP_PAGE_TITLE = \"HP OneView 1.05 help\"\n HELP_PAGE_FRAME_NAME = \"xpath=//frame[contains(@name, 'mainhelp_pane')]\"\n\n # Search Generic-----------\n ID_MENU_LINK_BASE = \"link=%s\"\n ID_PAGE_LABEL_BASE = \"xpath=//div[@class='hp-page-label']/h1[text()='%s']\"\n ID_TABLE_MASTER_BASE = \"xpath=.//div[@class='dataTables_scrollBody']/table[@class='hp-master-table hp-selectable dataTable']\"\n ID_INPUT_SEARCH = \"xpath=//div[@id='hp-search-input']/input\"\n ID_SEARCH_BAR = \"xpath=//h2[@id='hp-search-control']\"\n ID_SEARCH_CLEAR = \"xpath=//div[@id='hp-search-clear']\"\n ID_LABEL_FIRMWARE_BUNDLE_BASE = \"xpath=//div[@id='cic-fwdriver-page']//div[text()='%s']\"\n ID_LABEL_ENCLOSURE_GROUPS_BASE = \"xpath=//li[starts-with(@class,'hp-master-grid-item')]/header/div[text()='%s']\"\n ID_LABEL_SERVER_HARDWARE_TYPE_BASE = \"xpath=//div[@id='cic-servertypes-page']//div[text()='%s']\"\n ID_MENU_LINK_REPORTS = \"link=Reports\"\n\n # Help page\n ID_HELP_CONTROL = \"hp-help-control\"\n HELP_PAGE_CONTENT_LIST = \"xpath=//div[@class='toc']/dl/dd[%s]/table/tbody/tr/td[2]\"\n HELP_PAGE_SUB_CONTENT = \"xpath=//div[@class='toc']/dl/dd[%s]/dl/dd[%s]\"\n HELP_PAGE_SUB_CONTENT_LIST = \"xpath=//div[@class='toc']/dl/dd[%s]/dl/dd[%s]/table/tbody/tr/td[2]\"\n ID_LINK_BROWSE_HELP = \"href=/doc#/cic\"\n","sub_path":"robo4.2/fusion/FusionLibrary/ui/business_logic/general/base_elements.py","file_name":"base_elements.py","file_ext":"py","file_size_in_byte":4147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"469221966","text":"# author:Hurricane\n# date: 2020/11/5\n# E-mail:hurri_cane@qq.com\n\nimport cv2 as cv\nimport numpy as np\nimport os\norig_path = r\"F:\\PyCharm\\Practice\\hand_wrtten\\real_img\"\nimg_list = os.listdir(orig_path)\nkernel = np.ones((3,3),np.uint8)\nfor img_name in img_list:\n img_path = os.path.join(orig_path, img_name)\n img = cv.imread(img_path)\n img_resize = cv.resize(img,(600,600))\n img_gray = cv.cvtColor(img_resize, cv.COLOR_RGB2GRAY)\n ret, img_bw = cv.threshold(img_gray, 200, 255,cv.THRESH_BINARY)\n\n # img_open = cv.morphologyEx(img_bw,cv.MORPH_CLOSE,kernel)\n img_open = cv.dilate(img_bw,kernel,iterations=3)\n # cv.imshow(\"open\", img_open)\n num_labels, labels, stats, centroids = \\\n cv.connectedComponentsWithStats(img_open, connectivity=8, ltype=None)\n for sta in stats:\n if sta[4] < 1000:\n cv.rectangle(img_open, tuple(sta[0:2]), tuple(sta[0:2] + sta[2:4]), (0, 0, 255), thickness=-1)\n # cv.imshow(\"img\", img)\n # cv.imshow(\"gray\", img_gray)\n # cv.imshow(\"bw\", img_bw)\n # cv.imshow(\"dele\", img_open)\n cv.imshow(\"img_resize\",img_resize)\n cv.waitKey(0)\n print(\"*\"*50)\n\ncv.destroyAllWindows()\n\n\n\n","sub_path":"get_number_batch.py","file_name":"get_number_batch.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"593751980","text":"# (C) Copyright IBM Corp. 2020.\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, re, os\n\nfrom ibm_watson_machine_learning.libs.repo.mlrepository import MetaNames\nfrom ibm_watson_machine_learning.libs.repo.mlrepositoryartifact.runtimes_artifact import RuntimesArtifact\nfrom ibm_watson_machine_learning.libs.repo.swagger_client.api_client import ApiException\nimport json\nfrom .runtimes_adapter import WmlRuntimesAdapter\nfrom ibm_watson_machine_learning.libs.repo.swagger_client.models import RuntimeSpecDefinitionInput, RuntimeSpecDefinitionInputCustomLibraries,\\\n PatchOperationRuntimeSpec, RuntimeSpecDefinitionInputPlatform\n\n\n\nlogger = logging.getLogger('RuntimesCollection')\n\n\nclass RuntimesCollection:\n \"\"\"\n Client operating on runtimes in repository service.\n\n :param str base_path: base url to Watson Machine Learning instance\n :param MLRepositoryApi repository_api: client connecting to repository rest api\n :param MLRepositoryClient client: high level client used for simplification and argument for constructors\n \"\"\"\n def __init__(self, base_path, repository_api, client):\n\n from ibm_watson_machine_learning.libs.repo.mlrepositoryclient import MLRepositoryClient\n from ibm_watson_machine_learning.libs.repo.mlrepositoryclient import MLRepositoryApi\n\n if not isinstance(base_path, str) and not isinstance(base_path, unicode):\n raise ValueError('Invalid type for base_path: {}'.format(base_path.__class__.__name__))\n\n if not isinstance(repository_api, MLRepositoryApi):\n raise ValueError('Invalid type for repository_api: {}'.format(repository_api.__class__.__name__))\n\n if not isinstance(client, MLRepositoryClient):\n raise ValueError('Invalid type for client: {}'.format(client.__class__.__name__))\n\n self.base_path = base_path\n self.repository_api = repository_api\n self.client = client\n\n def all(self, library_name=None, library_id=None):\n \"\"\"\n Gets info about all runtimes which belong to this user.\n\n Not complete information is provided by all(). To get detailed information about experiment use get().\n\n :return: info about runtimes\n :rtype: list[ExperimentsArtifact]\n \"\"\"\n\n all_runtimes = self.repository_api.v3_runtime_spec_list(library_name, library_id)\n list_runtimes_artifact = []\n if all_runtimes is not None:\n resr = all_runtimes.resources\n for iter1 in resr:\n list_runtimes_artifact.append(WmlRuntimesAdapter(iter1, self.client).artifact())\n return list_runtimes_artifact\n else:\n return []\n\n def get(self, runtimes_id):\n\n \"\"\"\n Gets detailed information about runtimes.\n\n :param str runtimes_id: uid used to identify experiment\n :return: returned object has all attributes of SparkPipelineArtifact but its class name is PipelineArtifact\n :rtype: PipelineArtifact(SparkPipelineLoader)\n \"\"\"\n\n if not isinstance(runtimes_id, str) and not isinstance(runtimes_id, unicode):\n raise ValueError('Invalid type for experiment_id: {}'.format(runtimes_id.__class__.__name__))\n if(runtimes_id.__contains__(\"/v4/runtimes\")):\n matched = re.search('.*/v4/runtimes/([A-Za-z0-9\\-]+)', runtimes_id)\n if matched is not None:\n runtimes_id = matched.group(1)\n return self.get(runtimes_id)\n else:\n raise ValueError('Unexpected artifact href: {} format'.format(runtimes_id))\n else:\n runtimes_output = self.repository_api.v3_runtime_spec_get(runtimes_id)\n if runtimes_output is not None:\n return WmlRuntimesAdapter(runtimes_output, self.client).artifact()\n else:\n raise Exception('Library not found'.format(runtimes))\n\n def remove(self, runtimes_id):\n \"\"\"\n Removes runtimes with given runtimes_id.\n\n :param str runtimes_id: uid used to identify experiment\n \"\"\"\n\n if not isinstance(runtimes_id, str) and not isinstance(runtimes_id, unicode):\n raise ValueError('Invalid type for runtimes_id: {}'.format(runtimes_id.__class__.__name__))\n\n if(runtimes_id.__contains__(\"/v4/runtimes\")):\n matched = re.search('.*/v4/runtimes/([A-Za-z0-9\\-]+)', runtimes_id)\n if matched is not None:\n runtimes_id_value = matched.group(1)\n self.remove(runtimes_id_value)\n else:\n raise ValueError('Unexpected experiment artifact href: {} format'.format(runtimes_id))\n else:\n return self.repository_api.v3_runtime_spec_delete(runtimes_id)\n\n def patch(self, runtimes_id, artifact):\n runtimes_patch_input = self.prepare_runtimes_patch_input(artifact)\n runtimes_patch_output = self.repository_api.v3_runtime_spec_patch_with_http_info(runtimes_patch_input, runtimes_id)\n statuscode = runtimes_patch_output[1]\n\n if statuscode is not 200:\n logger.info('Error while patching runtimes: no location header')\n raise ApiException(statuscode, \"Error while patching runtimes\")\n\n if runtimes_patch_output is not None:\n new_artifact = WmlRuntimesAdapter(runtimes_patch_output[0], self.client).artifact()\n return new_artifact\n\n def save(self, artifact, runtimespec_path = None):\n \"\"\"\n Saves runtimes in repository service.\n\n :param artifact : RuntimesArtifact to be saved in the repository service\n :param runtimes : runtimes file path to be saved in the repository service\n :return: saved artifact with changed MetaProps\n :rtype: RuntimesArtifact\n \"\"\"\n logger.debug('Creating a new WML Runtimes : {}'.format(artifact.name))\n\n if not issubclass(type(artifact), RuntimesArtifact):\n raise ValueError('Invalid type for artifact: {}'.format(artifact.__class__.__name__))\n\n runtimes_input = self._prepare_wml_runtimes_input(artifact)\n runtimes_output = self.repository_api.v3_runtime_spec_create_with_http_info(runtimes_input)\n\n runtimes_id = runtimes_output[0].metadata.guid\n\n if runtimespec_path is not None:\n if not os.path.exists(runtimespec_path):\n raise IOError('The runtimes specified ( {} ) does not exist.'.format(runtimespec_path))\n artifact.runtimespec_path = runtimespec_path\n\n if runtimespec_path is None and artifact.runtimespec_path is not None:\n if not os.path.exists(artifact.runtimespec_path):\n raise IOError('The artifact specified ( {} ) does not exist.'.format(artifact.runtimespec_path))\n\n statuscode = runtimes_output[1]\n if statuscode is not 201:\n logger.info('Error while creating runtimes: no location header')\n raise ApiException(statuscode, 'No artifact location')\n\n if runtimes_output is not None:\n new_artifact = WmlRuntimesAdapter(runtimes_output[0], self.client).artifact()\n new_artifact.runtimespec_path = artifact.runtimespec_path\n if artifact.runtimespec_path is not None:\n self._upload_runtimes_content(new_artifact, artifact.runtimespec_path)\n return new_artifact\n\n\n @staticmethod\n def _prepare_wml_runtimes_input(artifact):\n name = None\n version = None\n platform =None\n platform_version = None\n description = None\n\n name = artifact.meta.prop(MetaNames.RUNTIMES.NAME)\n description = artifact.meta.prop(MetaNames.RUNTIMES.DESCRIPTION)\n platform = json.loads(artifact.meta.prop(MetaNames.RUNTIMES.PLATFORM))\n platform_input = RuntimeSpecDefinitionInputPlatform(platform.get('name'), platform.get('version'))\n custom_libs = json.loads(artifact.meta.prop(MetaNames.RUNTIMES.CUSTOM_LIBRARIES_URLS))\n custom_library_param_list = []\n if custom_libs is not None:\n custom_library_param_list = RuntimeSpecDefinitionInputCustomLibraries(custom_libs.get('urls', None))\n if description is not None and not isinstance(description, str):\n raise ValueError('Invalid data format for description.')\n runtimes_input = RuntimeSpecDefinitionInput(\n name, description, platform_input, custom_library_param_list)\n return runtimes_input\n\n @staticmethod\n def prepare_runtimes_patch_input(artifact):\n patch_list = []\n patch_input = artifact.meta.prop(MetaNames.RUNTIMES.PATCH_INPUT)\n if isinstance(patch_input, str):\n patch_input_list = json.loads(artifact.meta.prop(MetaNames.RUNTIMES.PATCH_INPUT))\n if isinstance(patch_input_list, list):\n for iter1 in patch_input_list:\n runtimes_patch = PatchOperationRuntimeSpec(\n op = iter1.get('op'),\n path= iter1.get('path'),\n value = iter1.get('value', None),\n _from =iter1.get('from', None),\n )\n patch_list.append(runtimes_patch)\n\n return patch_list\n\n def _upload_runtimes_content(self, runtimes_artifact, artifact_path, query_param=None):\n runtimes_id = runtimes_artifact.uid\n content_stream = runtimes_artifact.reader().read()\n self.repository_api.upload_runtimes(runtimes_id, content_stream)\n content_stream.close()\n runtimes_artifact.reader().close()\n logger.debug('Content uploaded for runtimes created at: {}'.format(runtimes_id))\n\n","sub_path":"venv/Lib/site-packages/ibm_watson_machine_learning/libs/repo/mlrepositoryclient/runtimes_collection.py","file_name":"runtimes_collection.py","file_ext":"py","file_size_in_byte":10138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"7013367","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 16 15:42:36 2020\n\n@author: jacquelinedowling\n\"\"\"\n\n#Fixed capacities unmet demand\n\n\n##===========================================\n#Import stuff\n##===========================================\nfrom __future__ import division\nimport os\nimport sys\nimport copy\nimport numpy as np\n\nimport pickle\nimport numpy as np\nfrom numpy import genfromtxt\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport matplotlib.ticker as ticker\n\nimport datetime\nfrom matplotlib.dates import DayLocator, MonthLocator, HourLocator, AutoDateLocator, DateFormatter, drange\nfrom matplotlib.dates import MO, TU, WE, TH, FR, SA, SU, WeekdayLocator\nfrom numpy import arange\nfrom matplotlib.ticker import ScalarFormatter\nfrom matplotlib.ticker import FormatStrFormatter\n\nimport matplotlib.cm as cm\nimport matplotlib.mlab as mlab\nimport os\nimport re\nimport matplotlib.patches as mpatches\n\nimport matplotlib.ticker as mtick\n\n\n\n#UPDATE TO 2018!!!!\n\npgp_q = 'pink' \nbatt_q = 'purple'\n\n#pgp_q = '#ffb3ff' \n#batt_q = '#8c1aff'\n#dem_c = 'black'\n\n#pgp_q = '#ffb3ff' \n#batt_q = '#8c1aff'\n#pgp_q = 'pink'\n#batt_q = 'xkcd:violet'\n\n\n##===========================================\n#Read in Base Case: PGP Batteries, Wind Solar\n##===========================================\n\npickle_in = open('/Users/jacquelinedowling/MEM_Nov2019/SEM-1.2/Output_Data/fixedcaps_yrs/fixedcaps_yrs_1yrs_2018_2018_tst1980.pickle', 'rb')\n#pickle_in = open('/Users/jacquelinedowling/Documents/SEM-1.1_20190114/Output_Data/PGPtest5/PGPtest5_WindSolarPGPBatt_2015.pickle','rb')\nbase = pickle.load(pickle_in)\ninfo = base[0]\ninputs = base[1]\nresults = base[2]\n\n\n\n#def get_pickles():\n#\n# unsorted_pickles = [] #collection of all pickle files for triple year runs for ex\n# startyrs_list =[]\n# \n# path = \"/Users/jacquelinedowling/MEM_Nov2019/SEM-1.2/Output_Data/fixedcaps_2018/\"\n# for filename in os.listdir(path):\n# if re.match(\"fixedcaps_2018_SolarWindPGPbatt2018_\\d+.pickle\",filename):\n# pickle_in = open(str(path)+ filename,\"rb\")\n# base = pickle.load(pickle_in)\n# inputs = base[1]\n# start_year = int(inputs['START_YEAR'])\n# \n# unsorted_pickles.append(base)\n# startyrs_list.append(start_year)\n# sorted_pickles = [i for _,i in sorted(zip(startyrs_list, unsorted_pickles))]\n#\n# return sorted_pickles\n\n\ndef get_group(grouping):\n\n unsorted_pickles = [] #collection of all pickle files for triple year runs for ex\n startyrs_list =[]\n \n path = \"/Users/jacquelinedowling/MEM_Nov2019/SEM-1.2/Output_Data/fixedcaps_yrs/\"\n for filename in os.listdir(path):\n if re.match(\"fixedcaps_yrs_\"+str(grouping)+\"yrs_\\d+_\\d+_tst\\d+.pickle\",filename):\n pickle_in = open(str(path)+ filename,\"rb\")\n base = pickle.load(pickle_in)\n inputs = base[1]\n start_year = int(inputs['START_YEAR'])\n \n unsorted_pickles.append(base)\n startyrs_list.append(start_year)\n sorted_pickles = [i for _,i in sorted(zip(startyrs_list, unsorted_pickles))]\n\n \n \n return sorted_pickles\n\n#Example here\ndouble_years = get_group(2)\n\n\n\ndef get_met_demand(group):\n print(group)\n pickles = get_group(group)\n x_years = [] \n y_values = []\n \n for i in range(0, len(pickles)):\n info = pickles[i][0] \n inputs = pickles[i][1]\n results = pickles[i][2]\n \n# #demand - unmet)/demand will give you the % demand met\n# diff = sum(inputs[\"DEMAND_SERIES\"]) - sum(results['DISPATCH_UNMET_DEMAND'])\n# pcent_met = (diff / sum(inputs[\"DEMAND_SERIES\"]))*100\n# \n# #There will be two x values (start and end year). We'll duplicate the y value such that each x value matches a y value.\n# x_years.append(inputs['START_YEAR'])\n# y_values.append(pcent_met)\n# x_years.append(inputs['END_YEAR']+1) #the plus one is because the run ends at the end of this year\n# y_values.append(pcent_met)\n \n #demand - unmet)/demand will give you the % demand met\n# diff = sum(inputs[\"DEMAND_SERIES\"]- results['DISPATCH_UNMET_DEMAND'])\n# pcent_met = (diff / sum(inputs[\"DEMAND_SERIES\"]))*100\n \n h_unmet = sum(results['DISPATCH_UNMET_DEMAND'])#8765.82- diff #/8765.82\n \n #There will be two x values (start and end year). We'll duplicate the y value such that each x value matches a y value.\n x_years.append(inputs['START_YEAR'])\n y_values.append(h_unmet)\n x_years.append(inputs['END_YEAR']+1) #the plus one is because the run ends at the end of this year\n y_values.append(h_unmet)\n \n return x_years, y_values\n\n\n\n\n\n\n\n\n\n\n#======================================================================================================\n# Fixed capacity plotting \n#======================================================================================================\n#=======================================================\n# Figure size settings\n#=======================================================\n\nplt.rcParams.update({'axes.titlesize': 'large'})\nplt.rcParams.update({'axes.labelsize': 'large'})\n\nimport matplotlib.pylab as pylab\nparams = {'legend.fontsize': 'large',\n 'figure.figsize': (8, 8),\n 'axes.labelsize': 'large',\n 'axes.titlesize':'x-large',\n 'xtick.labelsize':'large',\n 'ytick.labelsize':'large'}\npylab.rcParams.update(params)\n#\n\ncolorlist = ('red', 'gold', 'lime', 'aqua', 'blue', 'darkviolet')\n##take in the data\n#x,y = get_met_demand(1)\n#\nfig = plt.figure()\nax1 = plt.subplot2grid((2, 1), (0, 0), colspan=1, rowspan=1)\n\nlinelist = []\navglist = []\nfor i in range(1,7):\n x, y = get_met_demand(i)\n line = ax1.plot(x, y, '-', color=colorlist[i-1], linewidth=1.6)\n print(i, np.average(y), np.std(y))\n avglist.append(np.average(y))\n linelist.append(line)\n break\n#\n\n#ax1 = df['myvar'].plot(kind='bar')\n\n#THIS ONE\n#ax1.yaxis.set_major_formatter(mtick.PercentFormatter(decimals=2))\n\n\nax1.set_xlim(1980, 2020)\n#ax1.set_ylim(99.98,100)\nax1.set_ylabel(\"Unmet demand in each year (hours)\")\n#ax1.set_title(\"Fixed capacities.\\nUnmet demand = $10/kWh\")\n\n#periods = ['2018-2018', '2017-2018', '2016-2018','2015-2018','2014-2018','2013-2018']\n#\n#handlelist=[]\n#for i in range(1,7):\n# patch = mpatches.Patch(color=colorlist[i-1], label=str(i)+'-yr: '+str(periods[i-1]))\n# handlelist.append(patch)\n#\n#plt.legend(loc='right',bbox_to_anchor=(1.45, .5),handles=[handlelist[5],handlelist[4],handlelist[3],handlelist[2],handlelist[1],handlelist[0]])\n\n\npos1 = ax1.get_position() # get the original position \nleft, width = 0.1 , .9\nbottom, height = 0.1, .9\nright = left + width\ntop = bottom + height\n# axes coordinates are 0,0 is bottom left and 1,1 is upper right\np = mpatches.Rectangle(\n (left, bottom), width, height,\n fill=False, transform=ax1.transAxes, clip_on=False, color='white')\nax1.add_patch(p)\nax1.text(left, top-.2, 'a) Fixed capacities based\\non the 2018 base case.', size = 'large',\n horizontalalignment='left',\n verticalalignment='bottom',\n transform=ax1.transAxes)\n\np = mpatches.Rectangle(\n (left, bottom), width, height,\n fill=False, transform=ax1.transAxes, clip_on=False, color='white')\nax1.add_patch(p)\n#ax1.text(1.2*(left+right), 0.5*(bottom+1.5*top), 'Fixed capacities based\\non results from these \\nsimulation periods:', size = 'large',\n# horizontalalignment='center',\n# verticalalignment='bottom',\n# transform=ax1.transAxes)\n\n#ax2 = plt.subplot2grid((2, 1), (1, 0), colspan=1, rowspan=1)\n#xlist = [1,2,3,4,5,6]\n#ax2.plot(xlist, avglist)\n#ax2.set_title('Average demand met for each simulation period')\n#\n\nplt.tight_layout()\n#fig.text(.155, 0.94, 'a)', size='large')\n#fig.text(.155, 0.46, 'b)', size='large')\nplt.savefig('si/SI_fixedcaps_2018.pdf', bbox_inches='tight')\nplt.show()\n\n##ax2 = plt.subplot2grid((1, 2), (0, 0), colspan=1, rowspan=1)\n##ax2 = plt.subplot2grid((1, 2), (0, 0), colspan=1, rowspan=1)\n##=========================================\n##PGP energy\n#pgp_energy_days = pgp_energy/24\n##fig, ax1 = plt.subplots()\n#ax2 = ax1.twinx()\n#ax1.plot_date(dates, pgp_energy, '-', color=pgp_q, linewidth=2)\n#ax2.plot_date(dates, pgp_energy_days, '-',color=pgp_q, linewidth=2)\n#\n#ax1.fill_between(dates, pgp_energy, interpolate=True, color=pgp_q)\n#ax2.fill_between(dates, pgp_energy_days, interpolate=True, color=pgp_q)\n#\n##ax1.set_title('Energy Stored in PGP, 2006 View')\n#ax1.set_xlim(dates[0], dates[-1])\n#ax1.set_ylim(bottom=0)\n#ax2.set_ylim(bottom=0)\n#ax1.xaxis.set_major_locator(AutoDateLocator())\n#ax1.xaxis.set_major_formatter(DateFormatter('%b-%Y'))\n#\n##ax1.set_xlabel('Time')\n#ax1.set_ylabel('Energy in PGP storage \\n (hours of mean CONUS demand)')\n#ax2.set_ylabel('(days of mean CONUS demand)')\n#ax1.set_xticklabels([])\n#ax2.set_xticklabels([])\n#\n##ax1.yaxis.set_ticks_position('both') # Adding ticks to both top and bottom\n#ax1.yaxis.set_tick_params(direction='out', which='both')\n#ax2.yaxis.set_tick_params(direction='out', which='both')\n#ax1.xaxis.set_tick_params(direction='out', which='both')\n#\n#ax1.yaxis.set_major_locator(ticker.MultipleLocator(200))\n#ax1.yaxis.set_minor_locator(ticker.MultipleLocator(100))\n#\n#ax2.yaxis.set_major_locator(ticker.MultipleLocator(5))\n#ax2.yaxis.set_minor_locator(ticker.MultipleLocator(5))\n#\n##fig.autofmt_xdate()\n##plt.savefig('pgp_energy.eps', bbox_inches='tight')\n##plt.show()\n#\n#print(max(pgp_energy))\n#print(max(pgp_energy_days))\n##=========================================\n##Battery energy, year\n#ax3 = plt.subplot2grid((2, 1), (1, 0), colspan=1, rowspan=1)\n##fig, ax = plt.subplots()\n#ax3.plot_date(dates, batt_energy, '-',color=batt_q, linewidth=0.5)\n#ax3.fill_between(dates, batt_energy, interpolate=True, color=batt_q)\n#\n#ax3.set_ylim(top=2, bottom= 0) # adjust the top leaving bottom unchanged\n#ax3.set_xlim(dates[0], dates[-1])\n##ax.set_title('Energy Stored in Batteries, 2015 View')\n#\n#ax3.set_ylabel('Energy in battery storage \\n (hours of mean CONUS demand)')\n#ax3.yaxis.set_major_locator(ticker.MultipleLocator(.5))\n#ax3.yaxis.set_minor_locator(ticker.MultipleLocator(0.25))\n#\n##ax3.set_xlabel('Time')\n#ax3.xaxis.set_major_locator(AutoDateLocator())\n#ax3.xaxis.set_major_formatter(DateFormatter('%b'))\n#\n#print(max(batt_energy))\n#\n#ax3.yaxis.set_tick_params(direction='out', which='both')\n#ax3.xaxis.set_tick_params(direction='out', which='both')\n#\n##ax.xaxis.set_minor_locator(HourLocator())\n##ax.fmt_xdata = DateFormatter('%Y-%m-%d %H:%M:%S')\n##fig.autofmt_xdate()\n##ax3.xaxis.set_ticks_position('both')\n##ax3.tick_params(axis='x', direction='in', which='bottom')\n##plt.savefig('battery_energy.eps', bbox_inches='tight')\n##plt.show()\n##=========================================\n#plt.tight_layout()\n#fig.text(.155, 0.94, 'a)', size='large')\n#fig.text(.155, 0.46, 'b)', size='large')\n#plt.savefig('figure2.pdf', bbox_inches='tight')\n#plt.savefig('figure2.eps', bbox_inches='tight')\n#plt.show()\n#\n##=========================================\n \n\n#=======================================================\n#date1 = datetime.datetime(int(inputs['START_YEAR']), int(inputs['START_MONTH']),\n# int(inputs['START_DAY']), int(inputs['START_HOUR']))\n#date2 = datetime.datetime(int(inputs['END_YEAR']), int(inputs['END_MONTH']),\n# int(inputs['END_DAY']), int(inputs['END_HOUR']))\n\n#date1 = datetime.datetime(2017, 12, 31 ,23)\n#date2 = datetime.datetime(2018, 12, 31 ,23)\n##date1 = datetime.datetime(int(inputs['START_YEAR']), 1, 1 ,1)\n##date2 = datetime.datetime(int(inputs['END_YEAR']+1), 1, 1, 1)\n#delta = datetime.timedelta(hours=1)\n#dates = drange(date1, date2, delta)\n#print(len(dates))\n\n","sub_path":"SEM-1.2/Making_Figures/SIFigures_May2020/si4a_fixedcaps_2018.py","file_name":"si4a_fixedcaps_2018.py","file_ext":"py","file_size_in_byte":11763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"247004455","text":"# pylint: disable=too-few-public-methods\n\nfrom .telenium_process import TeleniumTestProcess\nfrom .common import skip_screen_checks\n\n\nclass SettingScreen(TeleniumTestProcess):\n \"\"\"Setting Screen Functionality Testing\"\"\"\n\n @skip_screen_checks\n def test_setting_screen(self):\n \"\"\"Show Setting Screen\"\"\"\n print(\"=====================Test -Show Setting Screen=====================\")\n self.cli.sleep(3)\n # this is for checking current screen\n self.assertExists(\"//Inbox[@name~=\\\"inbox\\\"]\", timeout=2)\n # this is for opening Nav drawer\n self.cli.wait_click('//MDActionTopAppBarButton[@icon=\\\"menu\\\"]', timeout=2)\n # checking state of Nav drawer\n self.assertExists(\"//MDNavigationDrawer[@state~=\\\"open\\\"]\", timeout=2)\n # this is for scrolling Nav drawer\n self.drag(\"//NavigationItem[@text=\\\"Sent\\\"]\", \"//NavigationItem[@text=\\\"Inbox\\\"]\")\n # assert for checking scroll funcation\n self.assertCheckScrollDown('//ContentNavigationDrawer//ScrollView[0]', timeout=3)\n # this is for opening setting screen\n self.cli.wait_click('//NavigationItem[@text=\\\"Settings\\\"]', timeout=1)\n # Checking current screen\n self.assertExists(\"//Setting[@name~=\\\"set\\\"]\", timeout=2)\n","sub_path":"src/bitmessagekivy/tests/test_setting_screen.py","file_name":"test_setting_screen.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"533977431","text":"#!/usr/bin/env python3\n\nimport sys\n\n\nclass SuperMeta(type):\n __attr_file__ = None\n __attrs__ = {}\n\n def __call__(cls, attr_file_path, *args, **kwargs):\n cls.__attr_file__ = attr_file_path\n\n obj = type.__call__(cls, *args, **kwargs)\n\n if attr_file_path is not None:\n with open(attr_file_path, \"r\") as attr_file:\n all_attrs = attr_file.read()\n\n attr_lines = all_attrs.split(\"\\n\")\n splited_attrs = [i.split(\"=\") for i in attr_lines]\n\n for attr in splited_attrs[:-1]:\n cls.__attrs__[attr[0]] = attr[1]\n\n for attr in cls.__attrs__.items():\n setattr(obj, attr[0], attr[1])\n\n return obj\n\n\nclass Example(object, metaclass=SuperMeta):\n def __init__(self, name):\n self.aa = name\n\n\ndef main():\n b = Example(\"attributes.attr\", \"gggaa\")\n c = Example(None, \"gggaa\")\n\n print(b.bugaga, b.ultra, b.kek, b.aa)\n print(c.bugaga)\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"Python/University tasks/02/superlab/meta.py","file_name":"meta.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"596247687","text":"\"\"\"\nA primitive back-end HTTP server implementation suitable for testing purposes.\n\"\"\"\n\nfrom http.server import *\nfrom threading import *\n\n__author__ = 'NatSys Lab'\n__copyright__ = 'Copyright (C) 2014 NatSys Lab. (info@natsys-lab.com).'\n__license__ = 'GPL2'\n\ndef start(*args, **kwargs):\n \"\"\"A shortcut for BackendHTTPServer() constructor.\"\"\"\n return BackendHTTPServer(*args, **kwargs)\n\ndef _dummy_callback(method, uri, headers, body):\n \"\"\"An example of a backend_callback passed to BackendHTTPServer().\"\"\"\n ret_code = 200\n ret_headers = { 'Content-Type': 'text/html; charset=utf-8' }\n ret_body = 'Hello from dummy back-end callback'\n return (ret_code, ret_headers, ret_body)\n\nclass BackendHTTPServer(Thread, HTTPServer):\n \"\"\"\n Basically, this implementation does two things:\n 1. It runs in a HTTP server in a separate thread.\n 2. It handles all HTTP requests with a single backend_callback function\n passed to the constructor.\n \n Also, right after initialization it blocks until a first TCP connection is\n accepted. That is done to wait until Tempesta FW is connected.\n So you have to start Tempesta first, and only then spawn the HTTP server.\n \"\"\"\n def __init__(self, backend_callback=_dummy_callback, port=8080,\n wait_tfw_timeout_sec=20):\n # Initialize HTTP server, bind/listen/etc.\n self.accept_event = Event()\n self.backend_callback = backend_callback\n HTTPServer.__init__(self, ('127.0.0.1', port), BackendHTTPRequestHandler)\n \n # Start a background thread that accept()s connections.\n kwargs = dict(poll_interval = 0.05)\n Thread.__init__(self, target=self.serve_forever, kwargs=kwargs)\n self.start()\n \n # Synchronize with Tempesta FW.\n if (wait_tfw_timeout_sec):\n self.wait_for_tfw(wait_tfw_timeout_sec)\n \n def wait_for_tfw(self, timeout):\n \"\"\"\n Sleep until a first accepted connection (presumably from Tempesta FW).\n \n FIXME: race conditions possible: after the connection is established,\n the Tempesta FW must add the server to a load-balancing scheduler and\n so on, so there is a time span, when the Tempesta is not yet ready to\n forward incoming requests to the connected back-end server. At this\n point we just hope that this time span is negligible.\n BTW, that may be fixed by exporting state of Temepsta FW via debugfs.\n \"\"\"\n got_connection = self.accept_event.wait(timeout)\n if (not got_connection):\n self.shutdown()\n msg = (\"No connection from Tempesta FW (backend: {0}, timeout: {1})\"\n .format(self.server_address, timeout))\n raise Exception(msg)\n \n # get_request() calls accept() that blocks until the first connection.\n # We just inject a synchronization with wait_for_tfw() there.\n def get_request(self):\n ret = super().get_request()\n self.accept_event.set()\n return ret\n\nclass BackendHTTPRequestHandler(BaseHTTPRequestHandler):\n \"\"\"\n A wrapper for BackendHTTPServer.backend_callback.\n The class simply pushes HTTP requests to the callback, and then builds\n responses from data returned by the callback. \n \n That is done for simplicity. It is easier to code a single callback function\n than a whole handler class. We have to code one in every test, and we don't\n need much power in tests code, so we prefer a function over a class.\n \"\"\"\n def _handle_req_with_cb(self):\n \"\"\"\n Pass HTTP request to backend_callback, send a response containing data\n returned by the callback.\n \"\"\"\n # Read body and push it to the callback\n headers = self.headers\n body_len = int(headers['Content-Length'] or 0)\n body = self.rfile.read(body_len)\n cb = self.server.backend_callback\n resp_tuple = cb(self.command, self.path, headers, body)\n \n # The callback must return a tuple of exactly 3 elements: \n # (http_code, headers_dict, body_str)\n assert len(resp_tuple) == 3\n \n # Send response fields provided by the callback.\n code, headers, body = resp_tuple\n body = bytes(body, 'UTF-8')\n self.send_response(code)\n for name, val in headers.items():\n self.send_header(name, val)\n self.end_headers()\n self.wfile.write(body)\n print(body)\n \n # At this point Tempesta FW parser blocks HTTP/1.0 requests\n protocol_version = 'HTTP/1.1'\n \n # Actual handler methods. We dispatch all them into our single function.\n do_GET = _handle_req_with_cb\n do_POST = _handle_req_with_cb\n # Add do_METHOD here if you need anything beyond GET and POST methods.\n \n # By default, the base class prints a message for every incoming request.\n # We don't want to see this flood in test results, so here is the stub.\n def log_message(self, format, *args):\n return\n","sub_path":"tempesta_fw/t/functional/helpers/be.py","file_name":"be.py","file_ext":"py","file_size_in_byte":5049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"401785765","text":"import requests\n\n\ndef test_get_tocken():\n corpid = 'wwb183614ea47a13fc'\n corpsecret = 'cyd6sQ5dXTgKy3-RNg6iShhKgUp9TM-prkXOxJt4Rbs'\n\n res = requests.get(\"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s\" %(corpid, corpsecret))\n return res.json()['access_token']\n\n\n\ndef test_post():\n data = {\n \"name\": \"成都研发中心\",\n \"name_en\": \"RDCD\",\n \"parentid\": 1,\n \"order\": 1,\n \"id\": 2\n}\n res = requests.post(f\"https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token={test_get_tocken()}\", json=data)\n print(res.json())","sub_path":"interfaceTets/test_department.py","file_name":"test_department.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"446522827","text":"import logging\nimport time\nimport blocksec2go\nfrom blocksec2go.comm.pyscard import open_pyscard\nfrom eth_account._utils.transactions import (\n encode_transaction,\n serializable_unsigned_transaction_from_dict\n)\n \nimport web3_utils\n \n \nclass Security2GoSigner:\n def __init__(self, key_id):\n self.reader = None\n self.key_id = key_id\n self.logger = logging.getLogger('security2go')\n self.pub_key = None\n self._init()\n \n def _init(self):\n while self.reader is None:\n try:\n self.reader = open_pyscard()\n except Exception as details:\n self.logger.debug(details)\n if \"No reader found\" != str(details) and \"No card on reader\" != str(details):\n self.logger.error(details)\n raise Exception(f\"Reader error: {details}\")\n self.logger.info('Reader or card not found. Retrying in 1 second...')\n time.sleep(1)\n \n blocksec2go.select_app(self.reader)\n self.pub_key = self._get_pub_key()\n self.logger.info('Initialized security2go')\n \n def get_address(self):\n return web3_utils.address_from_public_key(self.pub_key)\n \n def sign_transaction(self, raw_transaction, chain_id):\n transaction = serializable_unsigned_transaction_from_dict(raw_transaction)\n transaction_hash = transaction.hash()\n self.logger.debug(f'Signing transaction with hash {transaction_hash.hex()}')\n signature = self._generate_signature_der(transaction_hash)\n \n r, s = web3_utils.sigdecode_der(signature)\n v = web3_utils.get_v(r, s, transaction_hash, self.pub_key, chain_id)\n encoded_transaction = encode_transaction(transaction, vrs=(v, r, s))\n \n return encoded_transaction\n \n def _generate_signature_der(self, data):\n _, _, signature = blocksec2go.generate_signature(\n self.reader, self.key_id, data\n )\n self.logger.debug('generated signature')\n return signature\n \n def _get_pub_key(self):\n _, _, pub_key = blocksec2go.get_key_info(self.reader, self.key_id)\n self.logger.debug('read public key')\n return pub_key[1:] # remove the '0x04' prefix","sub_path":"security2go.py","file_name":"security2go.py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"268429913","text":"import csv\r\nfrom statistics import mean\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n#1\r\nwith open('activity.csv', 'r')as file:\r\n data = csv.reader(file)\r\n my_dict = {}\r\n for row in data:\r\n if row [0] != 'NA' and row[1] != 'date':\r\n if row[1] not in my_dict:\r\n my_dict[row[1]] = [int(row[0])]\r\n else:\r\n my_dict[row[1]].append(int(row[0]))\r\ntotal_perday = {}\r\nmean_total_perday = {}\r\nfor key, value in my_dict.items():\r\n total_perday[key] = sum(value)\r\n mean_total_perday[key] = round(mean(value),2)\r\n\r\nprint(total_perday)\r\nprint(mean_total_perday)\r\n\r\n\r\n\r\nN = len(my_dict)\r\nmeanst = tuple(total_perday.values())\r\nind = np.arange(N)\r\nwidth = 0.8\r\np1 = plt.bar(ind, meanst, width)\r\nplt.ylabel('steps')\r\nplt.title('Mean Total per day')\r\nplt.xticks(ind, tuple(total_perday.keys()))\r\nplt.yticks(np.arange(0,101,20))\r\nplt.show()\r\n\r\n\r\n","sub_path":"Codes/Python/SEM 1/CSVFileExercise/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"1873969","text":"\"\"\"\r\nCreated on Thu Mar 22 11:14:39 2018\r\n\r\n@author: Nodar.Okroshiashvili\r\n\"\"\"\r\n\r\nn = int(input())\r\n\r\na = []\r\n\r\nfor _ in range(n):\r\n a.append(list(map(int, input().rstrip().split())))\r\n\r\n\r\n\r\ndef diagonalDifference(a):\r\n main_diag = sum(a[i][i] for i in range(n))\r\n non_main_diag = sum(a[i][n-i-1] for i in range(n))\r\n x = abs(main_diag - non_main_diag)\r\n return x\r\n\r\ndiagonalDifference(a)\r\n\r\n#%%\r\n\r\n# Second Solution using Numpy\r\n\r\nn = int(input())\r\n\r\na = []\r\n\r\nfor _ in range(n):\r\n a.append(list(map(int, input().rstrip().split())))\r\n \r\n \r\ndef diagonalDifference(a):\r\n import numpy as np\r\n main_diag_sum = np.trace(a)\r\n b = np.asarray(a)\r\n b = np.fliplr(b)\r\n non_main_diag_sum = np.trace(b)\r\n return abs(main_diag_sum - non_main_diag_sum)\r\n\r\ndiagonalDifference(a)\r\n\r\n","sub_path":"Problem Solving/Diagonal Difference.py","file_name":"Diagonal Difference.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"186309809","text":"# Copyright (c) 2021 Cisco and/or its affiliates.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at:\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Module defining ProgressState class.\"\"\"\n\n\nclass ProgressState:\n \"\"\"Structure containing data to be passed around in recursion.\n\n This is basically a private class of MultipleRatioSearch,\n but keeping it in a separate file makes things more readable.\n \"\"\"\n\n def __init__(\n self, database, phases, duration, width_goal, packet_loss_ratios,\n min_rate, max_rate, stop_time):\n \"\"\"Convert and store the argument values.\n\n Also initializa the stored width for external search.\n\n :param result: Structure containing measured results.\n :param phases: How many intermediate phases to perform\n before the current one.\n :param duration: Trial duration to use in the current phase [s].\n :param width_goal: The goal relative width for the curreent phase.\n :param packet_loss_ratios: List of ratios for the current search.\n :param min_rate: Minimal target transmit rate available\n for the current search [tps].\n :param max_rate: Maximal target transmit rate available\n for the current search [tps].\n :param stop_time: Monotonic time [s] when we should fail on timeout.\n :type result: MeasurementDatabase\n :type phases: int\n :type duration: float\n :type width_goal: float\n :type packet_loss_ratios: Iterable[float]\n :type min_rate: float\n :type max_rate: float\n :type stop_time: float\n \"\"\"\n self.database = database\n self.phases = int(phases)\n self.duration = float(duration)\n self.width_goal = float(width_goal)\n self.packet_loss_ratios = [\n float(ratio) for ratio in packet_loss_ratios\n ]\n self.min_rate = float(min_rate)\n self.max_rate = float(max_rate)\n self.stop_time = float(stop_time)\n","sub_path":"resources/libraries/python/MLRsearch/ProgressState.py","file_name":"ProgressState.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"178651982","text":"from selenium import webdriver\nimport datetime\nfrom bs4 import BeautifulSoup\nimport json\nimport csv\n\n# Create dict for JSON Object\nresponse = []\n\n# Prepare for parsing APNewsBriefs with BeautifulSoup after Scraping with Selenium\nbrowser = webdriver.Chrome()\n\nurlAPNewsBriefs = 'http://hosted.ap.org/dynamic/fronts/HOME?SITE=AP&SECTION=HOME'\npageAPNewsBriefs = browser.get(urlAPNewsBriefs)\nsoupAPNewsBriefs = BeautifulSoup(browser.page_source, 'lxml')\n\nbrowser.quit()\n\n# Parse APNewsBriefs urlbrowser.page_source\ntoday = str(datetime.datetime.now().date())\nfor position in soupAPNewsBriefs.find_all('div', class_='ap-newsbriefitem'):\n headline = position.find('a').string\n brief = position.find('span', class_='topheadlinebody').string\n apOffice = brief.split(' (AP)')[0]\n fullStory = 'http://hosted.ap.org/' + position.find('a').get('href')\n ctime = fullStory.split('CTIME=')[1]\n\n # Make changes to response for APNewsBriefs\n response.append({'Headline': headline, 'Brief': brief, 'AP_Office': apOffice, 'Full_Story': fullStory,\n 'CTIME': ctime})\n\n# Write response to JSON file\npostingsFile = '/Users/glennacree/Dropbox/CSC3130/WebProject_acreeg/APNewsBriefs/' + today + '.APNewsBriefs.json'\n\nwith open(postingsFile, 'w') as outfile:\n json.dump(response, outfile, sort_keys=True, indent=2)\n\noutfile.close()\n\n# Write response to CSV file\nkeys = response[0].keys()\nwith open(today + '.APNewsBriefs.csv', 'w') as output_file:\n dict_writer = csv.DictWriter(output_file, keys)\n dict_writer.writeheader()\n dict_writer.writerows(response)\n","sub_path":"WebProject_Chandler/Testing_Unused/ScrapeWithSeleniumParseSendToJSON.py","file_name":"ScrapeWithSeleniumParseSendToJSON.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"161118547","text":"from .base import FunctionalTest\r\nfrom time import sleep\r\n\r\n\r\nclass LocationInformationTest(FunctionalTest):\r\n fixtures = ['functional_test_register.json']\r\n\r\n def test_can_add_location_information_to_existing_ipad(self):\r\n self.browser.get(self.live_server_url)\r\n self.login_test_user()\r\n\r\n # first we go to the list view to find the existing\r\n # ipad\r\n self.click_link('Lists')\r\n self.click_link('Tablets')\r\n\r\n # next we find our ipad in the list and select it\r\n self.click_link('332233')\r\n\r\n # now we are presented with an update form\r\n self.check_page_title('Tablet Detail')\r\n\r\n # we notice that there are three location fields, Campus\r\n # Building and Room\r\n self.browser.find_element_by_id('id_campus')\r\n self.browser.find_element_by_id('id_building')\r\n self.browser.find_element_by_id('id_room')\r\n","sub_path":"functional_tests/test_location_information.py","file_name":"test_location_information.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"80"} +{"seq_id":"306439646","text":"\n# coding: utf-8\n\n# In[1]:\n\n\n#Writing a simple TensorFlow code and visualize it on TensorBoard\n\n\n# In[9]:\n\n\nimport tensorflow as tf\n\na = tf.constant(10)\nb = tf.constant(30)\nx = tf.add(a, b)\nwriter = tf.summary.FileWriter('./graphs', tf.get_default_graph())\nwith tf.Session() as sess:\n print(sess.run(x))\nwriter.close()\n\n","sub_path":"Tensorflow_n_Tensorboard_Basic.py","file_name":"Tensorflow_n_Tensorboard_Basic.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"432149883","text":"\"\"\"\nDefinition for a point.\nclass Point:\n def __init__(self, a=0, b=0):\n self.x = a\n self.y = b\n\"\"\"\n\n\nclass Solution:\n \"\"\"\n @param: points: an array of point\n @return: An integer\n \"\"\"\n def maxPoints(self, points):\n # write your code here\n len_points = len(points)\n if len_points <= 1:\n return len_points\n max_count = 0\n for index1 in range(0, len_points):\n p1 = points[index1]\n gradients = {}\n infinite_count = 0\n duplicate_count = 0\n for index2 in range(index1, len_points):\n p2 = points[index2]\n dx = p2.x - p1.x\n dy = p2.y - p1.y\n if 0 == dx and 0 == dy:\n duplicate_count += 1\n if 0 == dx:\n infinite_count += 1\n else:\n g = float(dy) / dx\n gradients[g] = (gradients[g] + 1 if gradients.has_key(g) else 1)\n if infinite_count > max_count:\n max_count = infinite_count\n for k, v in gradients.items():\n v += duplicate_count\n if v > max_count:\n max_count = v\n return max_count","sub_path":"Max Points on a Line.py","file_name":"Max Points on a Line.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"375895434","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport unittest\nimport uuid\n\nfrom openstack.load_balancer.v2 import health_monitor\nfrom openstack.load_balancer.v2 import l7_policy\nfrom openstack.load_balancer.v2 import l7_rule\nfrom openstack.load_balancer.v2 import listener\nfrom openstack.load_balancer.v2 import load_balancer\nfrom openstack.load_balancer.v2 import member\nfrom openstack.load_balancer.v2 import pool\nfrom openstack.tests.functional import base\nfrom openstack.tests.functional.load_balancer import base as lb_base\n\n\n@unittest.skipUnless(base.service_exists(service_type='load-balancer'),\n 'Load-balancer service does not exist')\nclass TestLoadBalancer(lb_base.BaseLBFunctionalTest):\n\n HM_NAME = uuid.uuid4().hex\n L7POLICY_NAME = uuid.uuid4().hex\n LB_NAME = uuid.uuid4().hex\n LISTENER_NAME = uuid.uuid4().hex\n MEMBER_NAME = uuid.uuid4().hex\n POOL_NAME = uuid.uuid4().hex\n UPDATE_NAME = uuid.uuid4().hex\n HM_ID = None\n L7POLICY_ID = None\n LB_ID = None\n LISTENER_ID = None\n MEMBER_ID = None\n POOL_ID = None\n VIP_SUBNET_ID = None\n PROJECT_ID = None\n PROTOCOL = 'HTTP'\n PROTOCOL_PORT = 80\n LB_ALGORITHM = 'ROUND_ROBIN'\n MEMBER_ADDRESS = '192.0.2.16'\n WEIGHT = 10\n DELAY = 2\n TIMEOUT = 1\n MAX_RETRY = 3\n HM_TYPE = 'HTTP'\n ACTION = 'REDIRECT_TO_URL'\n REDIRECT_URL = 'http://www.example.com'\n COMPARE_TYPE = 'CONTAINS'\n L7RULE_TYPE = 'HOST_NAME'\n L7RULE_VALUE = 'example'\n\n # Note: Creating load balancers can be slow on some hosts due to nova\n # instance boot times (up to ten minutes) so we are consolidating\n # all of our functional tests here to reduce test runtime.\n @classmethod\n def setUpClass(cls):\n super(TestLoadBalancer, cls).setUpClass()\n subnets = list(cls.conn.network.subnets())\n cls.VIP_SUBNET_ID = subnets[0].id\n cls.PROJECT_ID = cls.conn.session.get_project_id()\n test_lb = cls.conn.load_balancer.create_load_balancer(\n name=cls.LB_NAME, vip_subnet_id=cls.VIP_SUBNET_ID,\n project_id=cls.PROJECT_ID)\n assert isinstance(test_lb, load_balancer.LoadBalancer)\n cls.assertIs(cls.LB_NAME, test_lb.name)\n # Wait for the LB to go ACTIVE. On non-virtualization enabled hosts\n # it can take nova up to ten minutes to boot a VM.\n cls.lb_wait_for_status(test_lb, status='ACTIVE',\n failures=['ERROR'], interval=1, wait=600)\n cls.LB_ID = test_lb.id\n\n test_listener = cls.conn.load_balancer.create_listener(\n name=cls.LISTENER_NAME, protocol=cls.PROTOCOL,\n protocol_port=cls.PROTOCOL_PORT, loadbalancer_id=cls.LB_ID)\n assert isinstance(test_listener, listener.Listener)\n cls.assertIs(cls.LISTENER_NAME, test_listener.name)\n cls.LISTENER_ID = test_listener.id\n cls.lb_wait_for_status(test_lb, status='ACTIVE',\n failures=['ERROR'])\n\n test_pool = cls.conn.load_balancer.create_pool(\n name=cls.POOL_NAME, protocol=cls.PROTOCOL,\n lb_algorithm=cls.LB_ALGORITHM, listener_id=cls.LISTENER_ID)\n assert isinstance(test_pool, pool.Pool)\n cls.assertIs(cls.POOL_NAME, test_pool.name)\n cls.POOL_ID = test_pool.id\n cls.lb_wait_for_status(test_lb, status='ACTIVE',\n failures=['ERROR'])\n\n test_member = cls.conn.load_balancer.create_member(\n pool=cls.POOL_ID, name=cls.MEMBER_NAME, address=cls.MEMBER_ADDRESS,\n protocol_port=cls.PROTOCOL_PORT, weight=cls.WEIGHT)\n assert isinstance(test_member, member.Member)\n cls.assertIs(cls.MEMBER_NAME, test_member.name)\n cls.MEMBER_ID = test_member.id\n cls.lb_wait_for_status(test_lb, status='ACTIVE',\n failures=['ERROR'])\n\n test_hm = cls.conn.load_balancer.create_health_monitor(\n pool_id=cls.POOL_ID, name=cls.HM_NAME, delay=cls.DELAY,\n timeout=cls.TIMEOUT, max_retries=cls.MAX_RETRY, type=cls.HM_TYPE)\n assert isinstance(test_hm, health_monitor.HealthMonitor)\n cls.assertIs(cls.HM_NAME, test_hm.name)\n cls.HM_ID = test_hm.id\n cls.lb_wait_for_status(test_lb, status='ACTIVE',\n failures=['ERROR'])\n\n test_l7policy = cls.conn.load_balancer.create_l7_policy(\n listener_id=cls.LISTENER_ID, name=cls.L7POLICY_NAME,\n action=cls.ACTION, redirect_url=cls.REDIRECT_URL)\n assert isinstance(test_l7policy, l7_policy.L7Policy)\n cls.assertIs(cls.L7POLICY_NAME, test_l7policy.name)\n cls.L7POLICY_ID = test_l7policy.id\n cls.lb_wait_for_status(test_lb, status='ACTIVE',\n failures=['ERROR'])\n\n test_l7rule = cls.conn.load_balancer.create_l7_rule(\n l7_policy=cls.L7POLICY_ID, compare_type=cls.COMPARE_TYPE,\n type=cls.L7RULE_TYPE, value=cls.L7RULE_VALUE)\n assert isinstance(test_l7rule, l7_rule.L7Rule)\n cls.assertIs(cls.COMPARE_TYPE, test_l7rule.compare_type)\n cls.L7RULE_ID = test_l7rule.id\n cls.lb_wait_for_status(test_lb, status='ACTIVE',\n failures=['ERROR'])\n\n @classmethod\n def tearDownClass(cls):\n test_lb = cls.conn.load_balancer.get_load_balancer(cls.LB_ID)\n cls.lb_wait_for_status(test_lb, status='ACTIVE', failures=['ERROR'])\n\n cls.conn.load_balancer.delete_l7_rule(\n cls.L7RULE_ID, l7_policy=cls.L7POLICY_ID, ignore_missing=False)\n cls.lb_wait_for_status(test_lb, status='ACTIVE', failures=['ERROR'])\n\n cls.conn.load_balancer.delete_l7_policy(\n cls.L7POLICY_ID, ignore_missing=False)\n cls.lb_wait_for_status(test_lb, status='ACTIVE', failures=['ERROR'])\n\n cls.conn.load_balancer.delete_health_monitor(\n cls.HM_ID, ignore_missing=False)\n cls.lb_wait_for_status(test_lb, status='ACTIVE', failures=['ERROR'])\n\n cls.conn.load_balancer.delete_member(\n cls.MEMBER_ID, cls.POOL_ID, ignore_missing=False)\n cls.lb_wait_for_status(test_lb, status='ACTIVE', failures=['ERROR'])\n\n cls.conn.load_balancer.delete_pool(cls.POOL_ID, ignore_missing=False)\n cls.lb_wait_for_status(test_lb, status='ACTIVE', failures=['ERROR'])\n\n cls.conn.load_balancer.delete_listener(cls.LISTENER_ID,\n ignore_missing=False)\n cls.lb_wait_for_status(test_lb, status='ACTIVE', failures=['ERROR'])\n\n cls.conn.load_balancer.delete_load_balancer(\n cls.LB_ID, ignore_missing=False)\n\n def test_lb_find(self):\n test_lb = self.conn.load_balancer.find_load_balancer(self.LB_NAME)\n self.assertEqual(self.LB_ID, test_lb.id)\n\n def test_lb_get(self):\n test_lb = self.conn.load_balancer.get_load_balancer(self.LB_ID)\n self.assertEqual(self.LB_NAME, test_lb.name)\n self.assertEqual(self.LB_ID, test_lb.id)\n self.assertEqual(self.VIP_SUBNET_ID, test_lb.vip_subnet_id)\n\n def test_lb_list(self):\n names = [lb.name for lb in self.conn.load_balancer.load_balancers()]\n self.assertIn(self.LB_NAME, names)\n\n def test_lb_update(self):\n update_lb = self.conn.load_balancer.update_load_balancer(\n self.LB_ID, name=self.UPDATE_NAME)\n self.lb_wait_for_status(update_lb, status='ACTIVE',\n failures=['ERROR'])\n test_lb = self.conn.load_balancer.get_load_balancer(self.LB_ID)\n self.assertEqual(self.UPDATE_NAME, test_lb.name)\n\n update_lb = self.conn.load_balancer.update_load_balancer(\n self.LB_ID, name=self.LB_NAME)\n self.lb_wait_for_status(update_lb, status='ACTIVE',\n failures=['ERROR'])\n test_lb = self.conn.load_balancer.get_load_balancer(self.LB_ID)\n self.assertEqual(self.LB_NAME, test_lb.name)\n\n def test_listener_find(self):\n test_listener = self.conn.load_balancer.find_listener(\n self.LISTENER_NAME)\n self.assertEqual(self.LISTENER_ID, test_listener.id)\n\n def test_listener_get(self):\n test_listener = self.conn.load_balancer.get_listener(self.LISTENER_ID)\n self.assertEqual(self.LISTENER_NAME, test_listener.name)\n self.assertEqual(self.LISTENER_ID, test_listener.id)\n self.assertEqual(self.PROTOCOL, test_listener.protocol)\n self.assertEqual(self.PROTOCOL_PORT, test_listener.protocol_port)\n\n def test_listener_list(self):\n names = [ls.name for ls in self.conn.load_balancer.listeners()]\n self.assertIn(self.LISTENER_NAME, names)\n\n def test_listener_update(self):\n test_lb = self.conn.load_balancer.get_load_balancer(self.LB_ID)\n\n self.conn.load_balancer.update_listener(\n self.LISTENER_ID, name=self.UPDATE_NAME)\n self.lb_wait_for_status(test_lb, status='ACTIVE',\n failures=['ERROR'])\n test_listener = self.conn.load_balancer.get_listener(self.LISTENER_ID)\n self.assertEqual(self.UPDATE_NAME, test_listener.name)\n\n self.conn.load_balancer.update_listener(\n self.LISTENER_ID, name=self.LISTENER_NAME)\n self.lb_wait_for_status(test_lb, status='ACTIVE',\n failures=['ERROR'])\n test_listener = self.conn.load_balancer.get_listener(self.LISTENER_ID)\n self.assertEqual(self.LISTENER_NAME, test_listener.name)\n\n def test_pool_find(self):\n test_pool = self.conn.load_balancer.find_pool(self.POOL_NAME)\n self.assertEqual(self.POOL_ID, test_pool.id)\n\n def test_pool_get(self):\n test_pool = self.conn.load_balancer.get_pool(self.POOL_ID)\n self.assertEqual(self.POOL_NAME, test_pool.name)\n self.assertEqual(self.POOL_ID, test_pool.id)\n self.assertEqual(self.PROTOCOL, test_pool.protocol)\n\n def test_pool_list(self):\n names = [pool.name for pool in self.conn.load_balancer.pools()]\n self.assertIn(self.POOL_NAME, names)\n\n def test_pool_update(self):\n test_lb = self.conn.load_balancer.get_load_balancer(self.LB_ID)\n\n self.conn.load_balancer.update_pool(self.POOL_ID,\n name=self.UPDATE_NAME)\n self.lb_wait_for_status(test_lb, status='ACTIVE', failures=['ERROR'])\n test_pool = self.conn.load_balancer.get_pool(self.POOL_ID)\n self.assertEqual(self.UPDATE_NAME, test_pool.name)\n\n self.conn.load_balancer.update_pool(self.POOL_ID,\n name=self.POOL_NAME)\n self.lb_wait_for_status(test_lb, status='ACTIVE', failures=['ERROR'])\n test_pool = self.conn.load_balancer.get_pool(self.POOL_ID)\n self.assertEqual(self.POOL_NAME, test_pool.name)\n\n def test_member_find(self):\n test_member = self.conn.load_balancer.find_member(self.MEMBER_NAME,\n self.POOL_ID)\n self.assertEqual(self.MEMBER_ID, test_member.id)\n\n def test_member_get(self):\n test_member = self.conn.load_balancer.get_member(self.MEMBER_ID,\n self.POOL_ID)\n self.assertEqual(self.MEMBER_NAME, test_member.name)\n self.assertEqual(self.MEMBER_ID, test_member.id)\n self.assertEqual(self.MEMBER_ADDRESS, test_member.address)\n self.assertEqual(self.PROTOCOL_PORT, test_member.protocol_port)\n self.assertEqual(self.WEIGHT, test_member.weight)\n\n def test_member_list(self):\n names = [mb.name for mb in self.conn.load_balancer.members(\n self.POOL_ID)]\n self.assertIn(self.MEMBER_NAME, names)\n\n def test_member_update(self):\n test_lb = self.conn.load_balancer.get_load_balancer(self.LB_ID)\n\n self.conn.load_balancer.update_member(self.MEMBER_ID, self.POOL_ID,\n name=self.UPDATE_NAME)\n self.lb_wait_for_status(test_lb, status='ACTIVE', failures=['ERROR'])\n test_member = self.conn.load_balancer.get_member(self.MEMBER_ID,\n self.POOL_ID)\n self.assertEqual(self.UPDATE_NAME, test_member.name)\n\n self.conn.load_balancer.update_member(self.MEMBER_ID, self.POOL_ID,\n name=self.MEMBER_NAME)\n self.lb_wait_for_status(test_lb, status='ACTIVE', failures=['ERROR'])\n test_member = self.conn.load_balancer.get_member(self.MEMBER_ID,\n self.POOL_ID)\n self.assertEqual(self.MEMBER_NAME, test_member.name)\n\n def test_health_monitor_find(self):\n test_hm = self.conn.load_balancer.find_health_monitor(self.HM_NAME)\n self.assertEqual(self.HM_ID, test_hm.id)\n\n def test_health_monitor_get(self):\n test_hm = self.conn.load_balancer.get_health_monitor(self.HM_ID)\n self.assertEqual(self.HM_NAME, test_hm.name)\n self.assertEqual(self.HM_ID, test_hm.id)\n self.assertEqual(self.DELAY, test_hm.delay)\n self.assertEqual(self.TIMEOUT, test_hm.timeout)\n self.assertEqual(self.MAX_RETRY, test_hm.max_retries)\n self.assertEqual(self.HM_TYPE, test_hm.type)\n\n def test_health_monitor_list(self):\n names = [hm.name for hm in self.conn.load_balancer.health_monitors()]\n self.assertIn(self.HM_NAME, names)\n\n def test_health_monitor_update(self):\n test_lb = self.conn.load_balancer.get_load_balancer(self.LB_ID)\n\n self.conn.load_balancer.update_health_monitor(self.HM_ID,\n name=self.UPDATE_NAME)\n self.lb_wait_for_status(test_lb, status='ACTIVE', failures=['ERROR'])\n test_hm = self.conn.load_balancer.get_health_monitor(self.HM_ID)\n self.assertEqual(self.UPDATE_NAME, test_hm.name)\n\n self.conn.load_balancer.update_health_monitor(self.HM_ID,\n name=self.HM_NAME)\n self.lb_wait_for_status(test_lb, status='ACTIVE', failures=['ERROR'])\n test_hm = self.conn.load_balancer.get_health_monitor(self.HM_ID)\n self.assertEqual(self.HM_NAME, test_hm.name)\n\n def test_l7_policy_find(self):\n test_l7_policy = self.conn.load_balancer.find_l7_policy(\n self.L7POLICY_NAME)\n self.assertEqual(self.L7POLICY_ID, test_l7_policy.id)\n\n def test_l7_policy_get(self):\n test_l7_policy = self.conn.load_balancer.get_l7_policy(\n self.L7POLICY_ID)\n self.assertEqual(self.L7POLICY_NAME, test_l7_policy.name)\n self.assertEqual(self.L7POLICY_ID, test_l7_policy.id)\n self.assertEqual(self.ACTION, test_l7_policy.action)\n\n def test_l7_policy_list(self):\n names = [l7.name for l7 in self.conn.load_balancer.l7_policies()]\n self.assertIn(self.L7POLICY_NAME, names)\n\n def test_l7_policy_update(self):\n test_lb = self.conn.load_balancer.get_load_balancer(self.LB_ID)\n\n self.conn.load_balancer.update_l7_policy(\n self.L7POLICY_ID, name=self.UPDATE_NAME)\n self.lb_wait_for_status(test_lb, status='ACTIVE', failures=['ERROR'])\n test_l7_policy = self.conn.load_balancer.get_l7_policy(\n self.L7POLICY_ID)\n self.assertEqual(self.UPDATE_NAME, test_l7_policy.name)\n\n self.conn.load_balancer.update_l7_policy(self.L7POLICY_ID,\n name=self.L7POLICY_NAME)\n self.lb_wait_for_status(test_lb, status='ACTIVE', failures=['ERROR'])\n test_l7_policy = self.conn.load_balancer.get_l7_policy(\n self.L7POLICY_ID)\n self.assertEqual(self.L7POLICY_NAME, test_l7_policy.name)\n\n def test_l7_rule_find(self):\n test_l7_rule = self.conn.load_balancer.find_l7_rule(\n self.L7RULE_ID, self.L7POLICY_ID)\n self.assertEqual(self.L7RULE_ID, test_l7_rule.id)\n self.assertEqual(self.L7RULE_TYPE, test_l7_rule.type)\n\n def test_l7_rule_get(self):\n test_l7_rule = self.conn.load_balancer.get_l7_rule(\n self.L7RULE_ID, l7_policy=self.L7POLICY_ID)\n self.assertEqual(self.L7RULE_ID, test_l7_rule.id)\n self.assertEqual(self.COMPARE_TYPE, test_l7_rule.compare_type)\n self.assertEqual(self.L7RULE_TYPE, test_l7_rule.type)\n self.assertEqual(self.L7RULE_VALUE, test_l7_rule.rule_value)\n\n def test_l7_rule_list(self):\n ids = [l7.id for l7 in self.conn.load_balancer.l7_rules(\n l7_policy=self.L7POLICY_ID)]\n self.assertIn(self.L7RULE_ID, ids)\n\n def test_l7_rule_update(self):\n test_lb = self.conn.load_balancer.get_load_balancer(self.LB_ID)\n\n self.conn.load_balancer.update_l7_rule(self.L7RULE_ID,\n l7_policy=self.L7POLICY_ID,\n rule_value=self.UPDATE_NAME)\n self.lb_wait_for_status(test_lb, status='ACTIVE', failures=['ERROR'])\n test_l7_rule = self.conn.load_balancer.get_l7_rule(\n self.L7RULE_ID, l7_policy=self.L7POLICY_ID)\n self.assertEqual(self.UPDATE_NAME, test_l7_rule.rule_value)\n\n self.conn.load_balancer.update_l7_rule(self.L7RULE_ID,\n l7_policy=self.L7POLICY_ID,\n rule_value=self.L7RULE_VALUE)\n self.lb_wait_for_status(test_lb, status='ACTIVE', failures=['ERROR'])\n test_l7_rule = self.conn.load_balancer.get_l7_rule(\n self.L7RULE_ID, l7_policy=self.L7POLICY_ID,)\n self.assertEqual(self.L7RULE_VALUE, test_l7_rule.rule_value)\n","sub_path":"openstack/tests/functional/load_balancer/v2/test_load_balancer.py","file_name":"test_load_balancer.py","file_ext":"py","file_size_in_byte":18212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"410590697","text":"import itertools\nimport json\nimport config\nimport requests\nimport re\nimport solve_predicates\nimport sys \n\nfrom moz_sql_parser import parse\nfrom copy import deepcopy\n\nfrom utils import *\n\nsys.setrecursionlimit(10**6)\n\nclass Query(object):\n\n def __init__(self, query):\n\n super().__init__()\n\n query = initialParsing(query)\n\n self.initial_query = query\n self.FRAGMENT_PREDICATE_CACHE = {}\n self.KEYWORDS = config.QUERY_KEYWORDS\n self.frag_parents = {}\n\n self.join_col_pairs = set()\n # Hardcoded (PK, PK) for all vertical fragments \n self.join_col_pairs.add(('vendorID', 'vendorID'))\n \n self.temp_unioned = set()\n self.updateFragParent()\n self.QUERY_ATTRIBUTES = set()\n self.joins = None\n\n self.query = self.parseQuery(query)\n self.getAttributes()\n delim = ''\n self.generateJoins()\n\n\n print(\"\\nINITIAL JOIN TREE\")\n print(self.joins)\n\n self.query_where_clause = '1=1'\n self.query_grp_by_clause = self.getQueryGroupByClause()\n self.query_having_clause = '1=1'\n\n\n if 'where' in self.query.keys():\n self.ATTRIBUTES_DATATYPE = getAttributesDatatype()\n self.query_where_clause = self.getQueryWhereClause(self.initial_query)\n self.query_where_clause = ' '.join(self.query_where_clause.split())\n self.join_col_pairs = self.parseJoinColPairs(self.query_where_clause)\n self.joins = self.horizontalPruning(deepcopy(self.joins), self.query_where_clause)\n print(\"\\nPRUNED JOIN TREE (PREDICATE PRUNING)\")\n print(self.joins)\n\n if self.query_grp_by_clause != '':\n if self.query_grp_by_clause.lower().find(\"having\")!=-1:\n self.query_grp_by_clause = self.query_grp_by_clause.replace('HAVING', 'having')\n self.query_grp_by_clause, self.query_having_clause = self.query_grp_by_clause.split('having')\n self.query_having_clause = self.replaceAllTableName(self.query_having_clause, ' ')\n self.query_grp_by_clause = self.replaceAllTableName(self.query_grp_by_clause, ' ')\n\n query_attrs = query.split('from')[0].strip(' ').split('select')[1].split(',')\n attr_num = 1\n self.aggregate_projections = []\n self.final_aggregate_projections = []\n for attr in query_attrs:\n for aggregate_keyword in (\"MAX\", \"MIN\", \"SUM\"):\n if attr.find(aggregate_keyword)!=-1:\n agg_col = attr.replace(aggregate_keyword,'').replace('(','').replace(')','').strip(' ')\n if agg_col.find('.')!=-1:\n attr = attr.replace(agg_col, agg_col.split('.')[1])\n agg_col = agg_col.split('.')[1]\n self.final_aggregate_projections.append('{}({})'.format(aggregate_keyword, agg_col) )\n self.aggregate_projections.append('{} as {}'.format(attr, agg_col) )\n attr_num+=1\n if attr.find(\"AVG\")!=-1:\n agg_col = attr.replace(\"AVG(\",'').replace(')','').strip(' ')\n if agg_col.find('.')!=-1:\n attr = attr.replace(agg_col, agg_col.split('.')[1])\n agg_col = agg_col.split('.')[1]\n self.aggregate_projections.append('SUM({}) as {}'.format(agg_col,agg_col) )\n self.aggregate_projections.append('count(*) as {}'.format(\"attr_{}\".format(attr_num)) )\n self.final_aggregate_projections.append('SUM({})/SUM({})'.format(agg_col, \"attr_{}\".format(attr_num)) )\n self.query_having_clause.replace(attr.strip(' '), 'SUM({})/SUM({})'.format(agg_col, \"attr_{}\".format(attr_num)))\n attr_num+=1\n \n print(self.join_col_pairs)\n\n print(\"\\nQUERY PLAN WITH OPTIMAL JOIN ORDER (HEURISTIC BASED)\")\n self.joins = self.rearrangeJoins(self.joins)\n print(self.joins)\n\n infix_query = self.getInfixExecutionExpression(self.joins)\n \n self.frag_site_map, self.frag_id_name_map = getFragInfo()\n self.frag_attr_names = {}\n for frag_id, frag_name in self.frag_id_name_map.items():\n self.frag_attr_names[frag_name] = list(fetchFragmentAttributeNames(frag_id))\n\n # Added whitespaces for parsing\n infix_query = \" {} \".format(infix_query)\n for frag_id, frag_name in self.frag_id_name_map.items():\n infix_query = infix_query.replace(' {} '.format(frag_id), ' {} '.format(frag_name))\n self.INFIX_QUERY_EXPRESSION = infix_query\n print(self.INFIX_QUERY_EXPRESSION)\n\n def getQueryGroupByClause(self):\n query = self.initial_query.replace(\"GROUP BY\", \"group by\")\n if query.find(\"group by\") != -1:\n return \"GROUP BY {}\".format(query.split('group by')[1])\n return ''\n\n def updateFragParent(self):\n QUERY = \"\"\" select table_name, relation_name from Fragments; \"\"\"\n response = executeQuery(QUERY)\n for row in response:\n frag, parent = row\n self.frag_parents[frag] = parent\n return\n\n def getJoinColumns(self, reln1, reln2):\n attrs1 = set(self.frag_attr_names[reln1])\n attrs2 = set(self.frag_attr_names[reln2])\n\n common_attrs = attrs1.intersection(attrs2)\n\n join_columns = set()\n\n for col1 in common_attrs:\n for col2 in common_attrs:\n if (col1,col2) in self.join_col_pairs:\n join_columns.add( '{}.{}={}.{}'.format(reln1,col1,reln2,col2) )\n\n return ' and '.join(list(join_columns))\n\n def parseJoinColPairs(self, query_where_clause):\n self.join_col_pairs = set()\n join_col_pairs = set()\n for op in ('=','!=','>','>=','<','<='):\n query_where_clause = query_where_clause.replace(' {} '.format(op), op)\n where_clause_tokens = query_where_clause.split(' ')\n for ele in where_clause_tokens:\n if re.search('\\w\\=\\w',ele) and ele.count('.')==2:\n lhs, rhs = ele.split('=')\n if lhs.split('.')[0] == rhs.split('.')[0]:\n continue\n join_col_pairs.add((lhs.split('.')[1],rhs.split('.')[1]))\n join_col_pairs.add((rhs.split('.')[1],lhs.split('.')[1]))\n if len(join_col_pairs) == 0:\n join_col_pairs.add(('vendorID','vendorID'))\n return join_col_pairs\n\n def getTempTableName(self):\n return 'temp_{}'.format(self.temp_table_num)\n\n def getFragIDfromName(self, reln_name):\n for frag_id, frag_name in self.frag_id_name_map.items():\n if frag_name == reln_name:\n return frag_id\n\n def getFragmentCardinality(self, frag_name):\n frag_site = self.frag_site_map[frag_name]\n QUERY = \"\"\" {} {} \"\"\".format(config.GET_FRAGMENT_CARDINALITY, frag_name)\n response = executeQuery(QUERY, frag_site)\n frag_cardinality = response[0][0]\n return int(frag_cardinality)\n\n def tranferCost(self, reln, storage_site, target_site):\n return (config.SITE_COST[str(target_site)] + config.NETWORK_TRANSFER_COST['{}_{}'.format(storage_site,target_site)])*self.getFragmentCardinality(reln)\n\n def getRelnUnion(self, reln1, reln2):\n print(\"DOING {} UNION {}\".format(reln1, reln2))\n attrs1 = self.frag_attr_names[reln1]\n attrs2 = self.frag_attr_names[reln2]\n attrs1 = sorted(attrs1)\n attrs2 = sorted(attrs2)\n temp_table_name = self.getTempTableName()\n # 'select attrs from '\n site_1 = self.frag_site_map[reln1]\n site_2 = self.frag_site_map[reln2]\n\n union_where_clause = self.replaceAllTableName(self.query_where_clause, ' ')\n _where1 = \"{} {}\".format(union_where_clause, self.replaceAllTableName(self.query_grp_by_clause,' '))\n _where2 = \"{} {}\".format(union_where_clause, self.replaceAllTableName(self.query_grp_by_clause,' '))\n\n if reln1 in self.temp_unioned:\n _where1 = \"1=1 {}\".format(self.replaceAllTableName(self.query_grp_by_clause,' '))\n if reln2 in self.temp_unioned:\n _where2 = \"1=1 {}\".format(self.replaceAllTableName(self.query_grp_by_clause, ' '))\n\n # print(self.temp_unioned, reln1, reln2, _where1, _where2)\n\n if site_1 == site_2:\n QUERY = \"\"\"CREATE TABLE IF NOT EXISTS {} SELECT {} FROM {} WHERE {} UNION ALL SELECT {} FROM {} WHERE {};\"\"\".format(temp_table_name, ','.join(self.getNonAggregateProjections()+self.aggregate_projections), reln1, _where1, ','.join(self.getNonAggregateProjections()+self.aggregate_projections), reln2, _where2)\n print(QUERY)\n print(executeQuery(QUERY, site_1))\n self.frag_site_map[temp_table_name] = site_1\n print(\"BOTH ON SAME SITE, {} stored at site {}\".format(temp_table_name, site_1))\n self.frag_attr_names[temp_table_name] = self.frag_attr_names[reln1]\n else:\n if self.tranferCost(reln1,site_1,site_2)>self.tranferCost(reln2,site_2,site_1):\n reln1, reln2 = reln2, reln1\n attrs1, attrs2 = attrs2, attrs1\n site_1, site_2 = site_2, site_1\n _where1, _where2 = _where2, _where1\n \n # MOVE RELN_1 TO SITE_2\n moveTable(reln1, site_1, site_2)\n print(\"MOVING {} to site {}\".format(reln1, site_2))\n QUERY = \"\"\"CREATE TABLE IF NOT EXISTS {} SELECT {} FROM {} WHERE {} UNION ALL SELECT {} FROM {} WHERE {};\"\"\".format(temp_table_name, ','.join(self.getNonAggregateProjections()+self.aggregate_projections), reln1, _where1, ','.join(self.getNonAggregateProjections()+self.aggregate_projections), reln2, _where2)\n print(QUERY)\n # QUERY = \"\"\"CREATE TABLE IF NOT EXISTS {} SELECT {} FROM {} UNION SELECT {} FROM {};\"\"\".format(temp_table_name, attrs1, reln1, attrs2, reln2)\n print(executeQuery(QUERY, site_2))\n self.frag_site_map[temp_table_name] = site_2\n print(\"{} stored at site {}\".format(temp_table_name, site_2))\n self.frag_attr_names[temp_table_name] = self.frag_attr_names[reln1]\n # DROP RELN_1 FROM SITE_2\n QUERY = \"\"\"DROP TABLE {};\"\"\".format(reln1)\n executeQuery(QUERY, site_2)\n\n self.temp_unioned.add(temp_table_name)\n \n if reln1.find(\"temp\")!=-1:\n QUERY = \"\"\"DROP TABLE {};\"\"\".format(reln1)\n executeQuery(QUERY, site_1)\n if reln2.find(\"temp\")!=-1:\n QUERY = \"\"\"DROP TABLE {};\"\"\".format(reln2)\n executeQuery(QUERY, site_2)\n\n def getRelnJoin(self, reln1, reln2, join_columns=\"1=1\"):\n print(\"DOING {} JOIN {}\".format(reln1, reln2))\n\n attrs1 = set(self.frag_attr_names[reln1])\n attrs2 = set(self.frag_attr_names[reln2])\n temp_table_name = self.getTempTableName()\n # 'select attrs from '\n site_1 = self.frag_site_map[reln1]\n site_2 = self.frag_site_map[reln2]\n\n project_attrs = []\n for attr in attrs1:\n if attr in attrs2:\n project_attrs.append('{}.{} as {}'.format(reln1, attr, attr))\n else:\n project_attrs.append(attr)\n for attr in attrs2:\n if attr in attrs1:\n continue\n project_attrs.append(attr)\n\n print(project_attrs)\n\n\n if site_1 == site_2:\n QUERY = \" CREATE TABLE IF NOT EXISTS {} SELECT {} FROM {},{} WHERE {};\".format(temp_table_name, ','.join(project_attrs), reln1, reln2, join_columns)\n print(QUERY)\n print(executeQuery(QUERY, site_2))\n self.frag_site_map[temp_table_name] = site_2\n print(\"BOTH ON SAME SITE, {} stored at site {}\".format(temp_table_name, site_2))\n self.frag_attr_names[temp_table_name] = list( attrs1.union(attrs2) )\n else:\n if self.tranferCost(reln1,site_1,site_2)>self.tranferCost(reln2,site_2,site_1):\n reln1, reln2 = reln2, reln1\n attrs1, attrs2 = attrs2, attrs1\n site_1, site_2 = site_2, site_1\n \n # MOVE RELN_1 TO SITE_2\n moveTable(reln1, site_1, site_2)\n join_attr = self.getJoinAttr(attrs1, attrs2)\n moveSemiJoinTable(reln1, reln2, site_1, site_2, join_attr)\n print(\"MOVING {} to site {}\".format(reln1, site_2))\n QUERY = \" CREATE TABLE IF NOT EXISTS {} SELECT {} FROM {},{} WHERE {};\".format(temp_table_name, ','.join(project_attrs), reln1, reln2, join_columns)\n print(QUERY)\n print(executeQuery(QUERY, site_2))\n self.frag_site_map[temp_table_name] = site_2\n print(\"{} stored at site {}\".format(temp_table_name, site_2))\n self.frag_attr_names[temp_table_name] = list( attrs1.union(attrs2) )\n # DROP RELN_1 FROM SITE_2\n QUERY = \"\"\"DROP TABLE {};\"\"\".format(reln1)\n executeQuery(QUERY, site_2)\n \n if reln1.find(\"temp\")!=-1:\n QUERY = \"\"\"DROP TABLE {};\"\"\".format(reln1)\n executeQuery(QUERY, site_1)\n if reln2.find(\"temp\")!=-1:\n QUERY = \"\"\"DROP TABLE {};\"\"\".format(reln2)\n executeQuery(QUERY, site_2)\n\n def runQuery(self):\n self.temp_table_num = 1\n tokens = self.INFIX_QUERY_EXPRESSION.split(' ')\n relns = []\n ops = []\n\n i = 0\n while i < len(tokens):\n if tokens[i] == ' ' or tokens[i] == '':\n i += 1\n continue\n elif tokens[i] == '(':\n ops.append(tokens[i])\n elif tokens[i] == ')': \n while len(ops) != 0 and ops[-1] != '(':\n reln2 = relns.pop()\n reln1 = relns.pop()\n op = ops.pop()\n\n # GENERATE CANDIDATE FOR JOIN PREDS BY REPLACING PARENT WITH CHILD FRAG\n if op == 'UNION':\n self.getRelnUnion(reln1, reln2)\n else:\n join_columns = self.getJoinColumns(reln1,reln2)\n print(join_columns)\n self.getRelnJoin(reln1, reln2, join_columns)\n\n # APPEND PREDS BY REPLACING reln1, reln2 with temp relation\n relns.append(self.getTempTableName())\n self.frag_parents[self.getTempTableName()] = self.getTempTableName()\n self.temp_table_num+=1\n ops.pop()\n elif tokens[i] in ('JOIN', 'UNION'):\n while len(ops) != 0 and solve_predicates.precedence(ops[-1]) >= solve_predicates.precedence(tokens[i]):\n reln2 = relns.pop()\n reln1 = relns.pop()\n op = ops.pop()\n\n if op == 'UNION':\n self.getRelnUnion(reln1, reln2)\n else:\n join_columns = self.getJoinColumns(reln1,reln2)\n print(join_columns)\n self.getRelnJoin(reln1, reln2, join_columns)\n\n relns.append(self.getTempTableName())\n self.frag_parents[self.getTempTableName()] = self.getTempTableName()\n self.temp_table_num+=1\n ops.append(tokens[i])\n else:\n relns.append( tokens[i] )\n i += 1\n\n while len(ops) != 0: \n reln2 = relns.pop()\n reln1 = relns.pop()\n op = ops.pop()\n if op == 'UNION':\n self.getRelnUnion(reln1, reln2)\n else:\n join_columns = self.getJoinColumns(reln1,reln2)\n print(join_columns)\n self.getRelnJoin(reln1, reln2, join_columns)\n relns.append(self.getTempTableName())\n self.frag_parents[self.getTempTableName()] = self.getTempTableName()\n self.temp_table_num+=1\n\n print(relns[-1])\n project_attribute_list = self.replaceAllTableName(','.join(self.getFinalNonAggregateProjections()+self.final_aggregate_projections), ',')\n\n final_query_where_clause = \"1=1 {}\".format(self.query_grp_by_clause)\n if relns[-1] not in self.temp_unioned:\n final_query_where_clause = self.replaceAllTableName(self.query_where_clause, ' ')\n QUERY = \"select {} from {} where {}\".format(project_attribute_list, relns[-1], final_query_where_clause)\n\n if self.initial_query.lower().find(\"having\")!=-1:\n QUERY = \"{} HAVING {}\".format(QUERY, self.query_having_clause)\n\n res = executeQuery(QUERY , self.frag_site_map[relns[-1]])\n\n if relns[-1].find(\"temp\")!=-1:\n QUERY = \"\"\"DROP TABLE {};\"\"\".format(relns[-1])\n executeQuery(QUERY, self.frag_site_map[relns[-1]])\n return res\n\n def getNonAggregateProjections(self):\n projections = self.initial_query.split(' from ')[0].split('select')[1].split(',')\n non_agg_proj = []\n for col in projections:\n flag = True\n for aggregate_keyword in (\"MAX\", \"MIN\", \"SUM\", \"AVG\"):\n if col.find(aggregate_keyword)!=-1:\n flag = False\n break\n if flag:\n if col.find(\".\")!=-1:\n non_agg_proj.append(col.split('.')[1].strip(' '))\n else:\n non_agg_proj.append(col.strip(' '))\n grp_by_cls = self.query_grp_by_clause.replace(\"group by\",'')\n grp_by_cls = self.query_grp_by_clause.replace(\"GROUP BY\",'')\n for attr in grp_by_cls.split(','):\n if attr == '':\n continue\n non_agg_proj.append(attr.strip(' '))\n non_agg_proj = sorted(list(set(non_agg_proj)))\n return non_agg_proj\n\n def getFinalNonAggregateProjections(self):\n projections = self.initial_query.split(' from ')[0].split('select')[1].split(',')\n non_agg_proj = []\n for col in projections:\n flag = True\n for aggregate_keyword in (\"MAX\", \"MIN\", \"SUM\", \"AVG\"):\n if col.find(aggregate_keyword)!=-1:\n flag = False\n break\n if flag:\n if col.find(\".\")!=-1:\n non_agg_proj.append(col.split('.')[1].strip(' '))\n else:\n non_agg_proj.append(col.strip(' '))\n non_agg_proj = sorted(list(set(non_agg_proj)))\n return non_agg_proj\n \n def perform_aggregate(self, query):\n res = executeQuery(query)\n return res\n\n def replaceAllTableName(self, s, delim):\n s = ' '.join(s.split())\n s = s.split(delim)\n _s = []\n for x in s:\n if x.find('.') != -1:\n agg_attr = False\n for aggregate_keyword in (\"MAX\", \"MIN\", \"SUM\", \"AVG\"):\n if x.find(aggregate_keyword)!=-1:\n a,b = x.split('(')\n b = b.split(')')[0]\n x = \"{}({})\".format(a,b.split('.')[1])\n agg_attr = True\n break\n if agg_attr == False:\n x = x.split('.')[1]\n _s.append(x)\n s = '{}'.format(delim).join(_s)\n return s\n\n def getInfixExecutionExpression(self, join):\n if type(join) == str:\n return join\n elif type(join) == list:\n if type(join[0]) != list and join[0] in (\"UNION\", \"JOIN\", ''):\n try:\n INFIX_EXPR = ' ( ' + ' {} '.format(join[0]).join( self.getInfixExecutionExpression(join[1]) ) + ' ) '\n return INFIX_EXPR\n except:\n print(join)\n elif type(join[0]) == list:\n inter_join_exp = []\n for int_join in join:\n inter_join_exp.append(self.getInfixExecutionExpression(int_join))\n return inter_join_exp\n else:\n return join\n\n def joinCost(self, join_order):\n \"\"\"\n Join Cost = Data Transfer Cost\n Assumption Selectivity Factors = 0.5\n Cardinality of Join = Size of relation with join attribute as foreign key\n Result Site Of Join Order: Site of 1st relation in Join Order; since\n we check all possible permutations, each case is handled\n \"\"\"\n total_cost = 0\n attrs = fetchFragmentAttributeNames(join_order[0])\n result_site = getFragSite(join_order[0])\n joins_size = getFragmentCardinality(join_order[0])\n\n for i, frag in enumerate(join_order[1:]):\n\n frag_attrs = fetchFragmentAttributeNames(frag)\n join_attr = self.getJoinAttr(frag_attrs, attrs)\n \n if join_attr is None:\n return float('inf')\n\n if getFragSite(frag) == result_site:\n if join_attr in getFragForKey(frag):\n joins_size = getFragmentCardinality(frag)\n else:\n cost = self.getAttributeSize(join_attr) * joins_size\n benefit = (1-getSelectivityFactor(frag))*self.getAttributeSize(join_attr)*getFragmentCardinality(frag)\n total_cost += cost - benefit\n attrs = attrs.union(frag_attrs)\n return total_cost\n\n def getAttributeSize(self, attribute):\n if self.ATTRIBUTES_DATATYPE[attribute] == 'INT':\n return 8\n return 255\n\n def getOptimalJoinOrder(self, join_query):\n # single table\n if join_query.find('JOIN')==-1:\n return join_query\n\n frags = [ frag.strip() for frag in join_query.split('JOIN') ]\n opt_join_perm = frags\n cost = float('inf')\n for join_order in itertools.permutations(frags):\n join_order_cost = self.joinCost(join_order)\n if join_order_cost < cost:\n opt_join_perm = join_order\n cost = join_order_cost\n opt_join_order = ' JOIN '.join(opt_join_perm)\n return opt_join_order\n \n def rearrangeJoins(self, join):\n if type(join) == str:\n return join\n elif type(join) == list:\n if self.queryTreeParseCheck(join):\n intermed_joins = []\n for int_join in join:\n intermed_joins.append(self.getOptimalJoinOrder(int_join))\n return intermed_joins\n else:\n join = [ self.rearrangeJoins(ele) for ele in join ]\n return join\n\n def getQueryWhereClause(self, query):\n query = query.replace('GROUP BY', 'group by')\n query_where_clause = query.split('where')[1].split('group by')[0] \n return solve_predicates.preParsePredicate(query_where_clause)\n\n def generateJoins(self):\n if type(self.query[\"from\"]) is not list:\n self.query[\"from\"] = [self.query[\"from\"]]\n\n delim = ''\n \n for table in self.query[\"from\"]:\n fragments = fetchFragments(table)\n\n frag_type = getFragmentType(fragments[0])\n if frag_type == 'VF':\n delim = 'JOIN'\n fragments = self.verticalFragmentPruning(fragments)\n elif frag_type != 'NF':\n delim = 'UNION'\n \n if self.joins is None:\n self.joins = [delim, fragments]\n else:\n joins = []\n for frag in fragments:\n joins.append( self.appendJoinToPrevJoin(deepcopy(self.joins), frag) )\n\n self.joins = [delim, joins]\n return\n\n def queryTreeParseCheck(self, join):\n if type(join[0]) != list and join[0] not in (\"UNION\", \"NATURAL_JOIN\", \"JOIN\", ''):\n return True\n return False\n\n def appendJoinToPrevJoin(self, join, frag):\n if type(join) == str:\n return join\n elif type(join) == list:\n if self.queryTreeParseCheck(join):\n intermed_joins = []\n for int_join in join:\n intermed_joins.append(int_join+' JOIN '+frag)\n return intermed_joins\n else:\n join = [ self.appendJoinToPrevJoin(ele, frag) for ele in join ]\n return join\n\n def parseQuery(self, inputQuery):\n tokenizedQuery = json.loads( json.dumps( parse(inputQuery) ) )\n print(\"TOKENIZED_QUERY -----> \",tokenizedQuery)\n return tokenizedQuery\n\n def isAttribute(self, obj):\n if type(obj) is str and obj not in self.KEYWORDS:\n return True\n return False\n\n def getAttributes(self):\n obj = self.query\n for key, value in obj.items():\n if key.lower() != \"from\":\n self.getAttributesUtil(value)\n\n def getAttributesUtil(self, obj):\n if type(obj) is dict:\n for key, value in obj.items():\n if type(value) is dict:\n self.getAttributesUtil(value) \n elif type(value) is list:\n for obj in value:\n self.getAttributesUtil(obj)\n else:\n self.getAttributesUtil(key)\n self.getAttributesUtil(value)\n else:\n if self.isAttribute(obj):\n if obj.find('.')!=-1:\n # relation.attr\n self.QUERY_ATTRIBUTES.add(obj.split('.')[1])\n else:\n self.QUERY_ATTRIBUTES.add(obj)\n\n def getFragmentPredicate(self, fragment_id):\n if fragment_id in self.FRAGMENT_PREDICATE_CACHE.keys():\n return self.FRAGMENT_PREDICATE_CACHE[fragment_id]\n predicate = executeQuery(config.COND_QUERY.format(fragment_id))\n if len(predicate) == 0:\n return None\n predicate = solve_predicates.preParsePredicate(predicate[0][0])\n self.FRAGMENT_PREDICATE_CACHE[fragment_id] = predicate\n return predicate\n\n\n def verticalFragmentPruning(self, fragments):\n # All Attributes Required, no pruning possible\n if '*' in self.QUERY_ATTRIBUTES:\n return fragments\n\n pruned_fragments = set()\n\n for frag in fragments:\n frag_attrs = fetchFragmentAttributeNames(frag)\n if self.QUERY_ATTRIBUTES.isdisjoint(frag_attrs) is False:\n pruned_fragments.add(frag)\n return list(pruned_fragments)\n\n def getJoinAttr(self, ATTRS_1, ATTRS_2):\n join_attr = ATTRS_1.intersection(ATTRS_2)\n if join_attr.__len__()==0:\n return None\n return list(join_attr)[0]\n \n def preParseFragConditional(self, conditional):\n conditional = conditional.replace(' or ', ' OR ').split(' OR ')\n return conditional\n\n def horizontalPruning(self, join, query_where_clause):\n if type(join) == str:\n return join\n elif type(join) == list:\n if self.queryTreeParseCheck(join):\n intermediate_joins = []\n for int_join in join:\n frags = int_join.split('JOIN')\n conditionals = []\n for frag in frags:\n if frag!='':\n frag_pred = self.getFragmentPredicate(frag)\n if frag_pred is not None:\n frag_pred = self.preParseFragConditional(frag_pred)\n if len(conditionals) == 0:\n conditionals = frag_pred\n else:\n int_conditionals = []\n for pred in frag_pred:\n for cond in conditionals:\n int_conditionals.append('{} and {}'.format(pred, cond))\n conditionals = int_conditionals\n \n if len(conditionals) == 0:\n intermediate_joins.append(int_join)\n continue\n\n for cond in conditionals:\n VAR_CONDITIONALS = solve_predicates.getVarConditionals(cond)\n if solve_predicates.evaluate(query_where_clause, VAR_CONDITIONALS, self.ATTRIBUTES_DATATYPE) == True:\n intermediate_joins.append(int_join)\n break\n return intermediate_joins\n else:\n join = [ self.horizontalPruning(ele, query_where_clause) for ele in join ]\n return join\n\ndef createTableQueryGenUtil(reln_name):\n QUERY = \" describe {}\".format(reln_name)\n return executeQuery(QUERY, '1')\n\ndef executeUpdateQuery(query):\n RELN_ATTRS = {\n 'Categories' : ['categoryID','categoryName'],\n 'Products' : ['productID','productName' ,'productDescription','standardCost','listPrice','categoryID'],\n 'Inventories' : ['productID','vendorID','quantity'],\n 'Vendors':['vendorID','vendorName','addressID' ,'rating','phone','email'],\n 'Addresses':['addressID','city','state','countryName','regionName','postalCode'],\n 'Customers':['customerID','customerName','addressID','phone','email']\n }\n\n def createTempTable(table_name, attributes, where_clause):\n QUERY = \"\"\"SELECT {} FROM {} WHERE {};\"\"\".format(','.join(attributes), table_name, where_clause)\n print(QUERY)\n data = Query(QUERY).runQuery()\n if len(data)==0:\n return\n data = ','.join( [ str(tuple(row)) for row in data ])\n \n attrs = createTableQueryGenUtil(table_name)\n print(attrs)\n\n QUERY = \" CREATE TABLE IF NOT EXISTS tmpupd_table ( {} );\".format(','.join([ '{} {}'.format(x[0], x[1].upper() ) for x in attrs]))\n print(QUERY)\n executeQuery(QUERY,'1')\n\n QUERY = \" INSERT INTO tmpupd_table ({}) VALUES {};\".format(','.join(attributes), data)\n print(QUERY)\n executeQuery(QUERY,'1')\n \n def updateTempTable(table_name):\n QUERY = query.replace(table_name, 'tmpupd_table')\n print(QUERY)\n executeQuery(QUERY,'1')\n\n def updateFragmentData(table_name, where_clause):\n fragments = fetchFragments(table_name)\n frag_type = getFragmentType(fragments[0])\n frag_pk = list(getFragPrimKey(fragments[0]))[0]\n print(\"KEY--->\",frag_pk)\n if frag_type == 'VF':\n for frag_id in fragments:\n frag_name = getFragmentTableName(frag_id)\n frag_site = getFragSite(frag_id)\n attributes = fetchFragmentAttributeNames(frag_id)\n\n QUERY = \"SELECT {} FROM tmpupd_table;\".format(frag_pk)\n print(QUERY)\n data = executeQuery(QUERY, '1')\n keys = [ str(row[0]) for row in data ]\n\n QUERY = \"DELETE FROM {} where {} IN ({});\".format(frag_name, frag_pk, ','.join(keys) )\n executeQuery(QUERY,frag_site)\n\n QUERY = \"\"\"SELECT {} FROM tmpupd_table;\"\"\".format(','.join(attributes))\n print(QUERY)\n data = executeQuery(QUERY,'1')\n if len(data)==0:\n continue\n data = ','.join( [ str(tuple(row)) for row in data ])\n print(data)\n\n QUERY = \" INSERT INTO {} ({}) VALUES {};\".format(frag_name, ','.join(attributes), data)\n executeQuery(QUERY,frag_site)\n print(QUERY)\n return\n for frag_id in fragments:\n frag_name = getFragmentTableName(frag_id)\n frag_site = getFragSite(frag_id)\n attributes = fetchFragmentAttributeNames(frag_id)\n frag_predicate = executeQuery(config.COND_QUERY.format(frag_id))\n if len(frag_predicate) == 0:\n frag_predicate = [[\"1=1\"]]\n frag_predicate = solve_predicates.preParsePredicate(frag_predicate[0][0])\n\n QUERY = \"DELETE FROM {} where {};\".format(frag_name, where_clause)\n executeQuery(QUERY,frag_site)\n\n QUERY = \"\"\"SELECT {} FROM tmpupd_table WHERE {};\"\"\".format(','.join(attributes), frag_predicate)\n print(QUERY)\n data = executeQuery(QUERY,'1')\n if len(data)==0:\n continue\n data = ','.join( [ str(tuple(row)) for row in data ])\n\n QUERY = \" INSERT INTO {} ({}) VALUES {};\".format(frag_name, ','.join(attributes), data)\n executeQuery(QUERY,frag_site)\n print(QUERY)\n\n def dropTempTable():\n QUERY = \"DROP TABLE tmpupd_table;\"\n print(QUERY)\n executeQuery(QUERY,'1')\n\n query = initialParsing(query)\n query = ' '.join(query.split())\n table_name = query.split(' ')[1].strip(' ')\n attributes = sorted(RELN_ATTRS[table_name])\n where_clause = \"1=1\"\n if query.find('where')!=-1:\n where_clause = query.split('where')[1].strip(' ')\n\n sites = set([ getFragSite(frag_id) for frag_id in fetchFragments(table_name) ])\n print(\"PARTICIPANT SITES \",sites)\n for site in sites:\n try:\n URLS = {}\n URLS['1'] = 'http://10.3.5.215:8081/upd_qry'\n URLS['2'] = 'http://10.3.5.214:8081/upd_qry'\n URLS['3'] = 'http://10.3.5.213:8081/upd_qry'\n URL = URLS[str(site)]\n req_obj = {'query': query}\n query_response = requests.post(URL, json = req_obj, timeout=3)\n query_response_object = query_response.json()\n print(\"SITE {} READY FOR QUERY EXECUTION\".format(site))\n except:\n print(\"ABORTED by SITE \", site)\n return\n \n createTempTable(table_name, attributes, where_clause)\n updateTempTable(table_name)\n\n for site in sites:\n try:\n URLS = {}\n URLS['1'] = 'http://10.3.5.215:8081/upd_qry'\n URLS['2'] = 'http://10.3.5.214:8081/upd_qry'\n URLS['3'] = 'http://10.3.5.213:8081/upd_qry'\n URL = URLS[str(site)]\n req_obj = {'query': query}\n query_response = requests.post(URL, json = req_obj, timeout=3)\n query_response_object = query_response.json()\n print(\"SITE {} READY TO COMMIT\".format(site))\n except:\n dropTempTable()\n print(\"ABORTED BY SITE \",site)\n return\n\n QUERY = \"select * from tmpupd_table\"\n print(QUERY)\n print(executeQuery(QUERY,'1'))\n\n updateFragmentData(table_name, where_clause)\n dropTempTable()\n\n\nquery = input()\n\nif query.find('update')!=-1 or query.find(\"UPDATE\")!=-1:\n executeUpdateQuery(query)\nelse:\n query = Query(query)\n print(query.runQuery())","sub_path":"query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":34760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"621981043","text":"#!/usr/bin/env python3\n\nimport numpy as np\nimport os\nimport gym\nfrom gym import spaces\nimport tensorflow as tf\n\nimport rospy\nimport ActionHandler\nimport project_point_cloud\nimport convertOpen3d\nimport envutils\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\nfrom stable_baselines.common.policies import CnnPolicy, MlpPolicy\nfrom stable_baselines import PPO1\nfrom stable_baselines.common.tf_layers import conv, linear, conv_to_fc, lstm\nimport open3d as o3d\n\nclass ScanEnv(gym.Env):\n\n def __init__(self):\n self.take_action = ActionHandler.ActionHandler()\n self.env_functions = envutils.env_utils()\n\n self.n_actions = 6\n self.action_space = spaces.Discrete(self.n_actions)\n self.sensor_max_range = 0.5\n self.h = 100\n self.w = 100\n self.imsize = (self.h, self.w)\n self.observation_space = spaces.Box(low=0, high=255, shape=(self.h, self.w,1))\n self.num_steps = 0\n self.reward_history = np.zeros(401)\n self.reward_stack = np.empty((0,401))\n\n def reset(self):\n self.reward_history[:] = 0\n self.num_steps = 0\n return self.env_functions.reset(self.imsize, self.sensor_max_range)\n \n def step(self, action):\n self.num_steps+=1\n self.take_action.move(action+1)\n obs = self.env_functions.get_obs(self.imsize, self.sensor_max_range)\n reward = self.env_functions.get_reward()\n self.reward_history[self.num_steps-1] = reward\n #done = self.env_functions.terminate()\n #if(self.num_steps%1==0):\n # print(\"Reward: \", reward)\n # print(\"step_num: \", self.num_steps)\n done = self.num_steps>400 or self.env_functions.terminate()\n if(done):\n self.reward_stack = np.append(self.reward_stack, self.reward_history.reshape(1,-1), axis=0)\n rewards = self.env_functions.rewards\n print(\"Ep length \", self.num_steps)\n print(\"Ep first reward \", rewards[0])\n print(\"Ep Max reward \", rewards[1:self.num_steps].max())\n print(\"Ep min reward \", rewards[1:self.num_steps].min())\n print(\"Ep mean reward \", rewards[1:self.num_steps].mean())\n print(\"Ep stddev \", rewards[1:self.num_steps].std())\n return obs, reward, done, {}\n \n def render(self, mode='human'):\n print(\"Number of steps \", self.num_steps)\n o3d.visualization.draw_geometries([self.env_functions.last_cloud])\n\ndef cnn(scaled_images, **kwargs):\n \"\"\"\n CNN from Nature paper.\n\n :param scaled_images: (TensorFlow Tensor) Image input placeholder\n :param kwargs: (dict) Extra keywords parameters for the convolutional layers of the CNN\n :return: (TensorFlow Tensor) The CNN output layer\n \"\"\"\n activ = tf.nn.relu\n layer_1 = activ(conv(scaled_images, 'c1', n_filters=4, filter_size=3, stride=2, init_scale=np.sqrt(2), **kwargs))\n layer_2 = activ(conv(layer_1, 'c2', n_filters=4, filter_size=3, stride=2, init_scale=np.sqrt(2), **kwargs))\n layer_3 = activ(conv(layer_2, 'c3', n_filters=4, filter_size=3, stride=2, init_scale=np.sqrt(2), **kwargs))\n layer_3 = conv_to_fc(layer_3)\n return activ(linear(layer_3, 'fc1', n_hidden=64, init_scale=np.sqrt(2)))\n\ndef fixed_policy(env):\n env.reset()\n for i in range(16):\n obs, _, _, _ = env.step(1)\n np.save(\"obs_depth_bunny.npy\", obs)\n for i in range(16):\n env.step(1)\n env.step(5)\n for i in range(60):\n env.step(1)\n env.step(5)\n for i in range(60):\n env.step(1)\n\ndef random_policy(env):\n env.reset()\n for i in range(15):\n obs, _, _, _ = env.step(env.action_space.sample())\n #np.save(\"obs_depth_bunny_random.npy\", obs)\n for i in range(115):\n env.step(env.action_space.sample())\n\nif __name__==\"__main__\":\n rospy.init_node(\"Scan_Environment_Training\")\n\n env = ScanEnv()\n obs = env.reset()\n #print(obs.min())\n\n model = PPO1.load(\"ScanEnv_minmaxreward2_bunny2\", env=env)\n #model = PPO1(CnnPolicy, env, verbose=1)\n #model.learn(total_timesteps=20000)\n #model.save(\"ScanEnv_minmaxreward2_bunny2\")\n #np.save(\"reward_history_1_bunny2.npy\", env.reward_stack)\n\n #model = PPO1.load(\"ScanEnv_minmaxreward2_bunny\", env=env)\n\n #obs = env.reset()\n\n while True:\n action, _states = model.predict(obs)\n obs, rewards, done, info = env.step(action)\n if done:\n #np.save(\"obs_cnn.npy\", obs)\n o3d.io.write_point_cloud(\"learned_policy_buddha.pcd\", env.env_functions.last_cloud)\n env.render()\n break\n \n #fixed_policy(env)\n #random_policy(env)\n #o3d.io.write_point_cloud(\"random_policy_buddha.pcd\", env.env_functions.last_cloud)\n","sub_path":"scripts/scanEnv.py","file_name":"scanEnv.py","file_ext":"py","file_size_in_byte":4396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"227307716","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n# =============================================================================\n\"\"\"This module includes a set of metric classes for evaluating the model's\nperformance. The specific metric classes could be converted from C++\nimplmentation or implemented directly using Python.\n\n\nExample usage::\n\n from singa import tensor\n from singa import metric\n import numpy as np\n\n x = tensor.Tensor((3, 5))\n x.uniform(0, 1) # randomly genearte the prediction activation\n x = tensor.Softmax(x) # normalize the prediction into probabilities\n y = tensor.from_numpy(np.array([0, 1, 3], dtype=np.int)) # set the truth\n\n f = metric.Accuracy()\n acc = f.evaluate(x, y) # averaged accuracy over all 3 samples in x\n\n\"\"\"\nfrom __future__ import division\nfrom __future__ import absolute_import\n\nfrom builtins import range\nfrom builtins import object\n\nfrom . import singa_wrap as singa\nfrom . import tensor\nimport numpy as np\n\n\nclass Metric(object):\n \"\"\"Base metric class.\n\n Subclasses that wrap the C++ loss classes can use the inherited foward,\n and evaluate functions of this base class. Other subclasses need\n to override these functions. Users need to feed in the **predictions** and\n ground truth to get the metric values.\n \"\"\"\n\n def __init__(self):\n self.swig_metric = None\n\n def forward(self, x, y):\n \"\"\"Compute the metric for each sample.\n\n Args:\n x (Tensor): predictions, one row per sample\n y (Tensor): ground truth values, one row per sample\n\n Returns:\n a tensor of floats, one per sample\n \"\"\"\n return tensor.from_raw_tensor(self.swig_metric.Forward(x.data, y.data))\n\n def evaluate(self, x, y):\n \"\"\"Compute the averaged metric over all samples.\n\n Args:\n x (Tensor): predictions, one row per sample\n y (Tensor): ground truth values, one row per sample\n Returns:\n a float value for the averaged metric\n \"\"\"\n return self.swig_metric.Evaluate(x.data, y.data)\n\n\nclass Accuracy(Metric):\n \"\"\"Compute the top one accuracy for single label prediction tasks.\n\n It calls the C++ functions to do the calculation.\n \"\"\"\n\n def __init__(self):\n self.swig_metric = singa.Accuracy()\n\n\nclass Precision(Metric):\n \"\"\"Make the top-k labels of max probability as the prediction\n\n Compute the precision against the groundtruth labels\n \"\"\"\n\n def __init__(self, top_k):\n self.top_k = top_k\n\n def forward(self, x, y):\n \"\"\"Compute the precision for each sample.\n\n Convert tensor to numpy for computation\n\n Args:\n x (Tensor): predictions, one row per sample\n y (Tensor): ground truth labels, one row per sample\n\n Returns:\n a tensor of floats, one per sample\n \"\"\"\n\n dev = x.device\n x.to_host()\n y.to_host()\n\n x_np = tensor.to_numpy(x)\n y_np = tensor.to_numpy(y)\n\n # Sort in descending order\n pred_np = np.argsort(-x_np)[:, 0 : self.top_k]\n\n prcs_np = np.zeros(pred_np.shape[0], dtype=np.float32)\n\n for i in range(pred_np.shape[0]):\n # groundtruth labels\n label_np = np.argwhere(y_np[i])\n\n # num of common labels among prediction and groundtruth\n num_intersect = np.intersect1d(pred_np[i], label_np).size\n prcs_np[i] = num_intersect / float(self.top_k)\n\n precision = tensor.from_numpy(prcs_np)\n\n x.to_device(dev)\n y.to_device(dev)\n precision.to_device(dev)\n\n return precision\n\n def evaluate(self, x, y):\n \"\"\"Compute the averaged precision over all samples.\n\n Args:\n x (Tensor): predictions, one row per sample\n y (Tensor): ground truth values, one row per sample\n Returns:\n a float value for the averaged metric\n \"\"\"\n\n return tensor.average(self.forward(x, y))\n\n\nclass Recall(Metric):\n \"\"\"Make the top-k labels of max probability as the prediction\n\n Compute the recall against the groundtruth labels\n \"\"\"\n\n def __init__(self, top_k):\n self.top_k = top_k\n\n def forward(self, x, y):\n \"\"\"Compute the recall for each sample.\n\n Convert tensor to numpy for computation\n\n Args:\n x (Tensor): predictions, one row per sample\n y (Tensor): ground truth labels, one row per sample\n\n Returns:\n a tensor of floats, one per sample\n \"\"\"\n\n dev = x.device\n x.to_host()\n y.to_host()\n\n x_np = tensor.to_numpy(x)\n y_np = tensor.to_numpy(y)\n\n # Sort in descending order\n pred_np = np.argsort(-x_np)[:, 0 : self.top_k]\n\n recall_np = np.zeros(pred_np.shape[0], dtype=np.float32)\n\n for i in range(pred_np.shape[0]):\n # Return the index of non-zero dimension of i-th sample\n label_np = np.argwhere(y_np[i])\n\n # Num of common labels among prediction and groundtruth\n num_intersect = np.intersect1d(pred_np[i], label_np).size\n recall_np[i] = float(num_intersect) / label_np.size\n\n recall = tensor.from_numpy(recall_np)\n\n x.to_device(dev)\n y.to_device(dev)\n recall.to_device(dev)\n\n return recall\n\n def evaluate(self, x, y):\n \"\"\"Compute the averaged precision over all samples.\n\n Args:\n x (Tensor): predictions, one row per sample\n y (Tensor): ground truth values, one row per sample\n Returns:\n a float value for the averaged metric\n \"\"\"\n\n return tensor.average(self.forward(x, y))\n","sub_path":"python/singa/metric.py","file_name":"metric.py","file_ext":"py","file_size_in_byte":6440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"567692657","text":"# -*- coding: utf-8 -*-\nfrom django.contrib import admin\nfrom .models import BlogPost\n\n\nclass BlogPostAdmin(admin.ModelAdmin):\n list_display = (\n 'author',\n 'published',\n 'title',\n 'created',\n )\n list_filter = ('author', 'published', 'created')\nadmin.site.register(BlogPost, BlogPostAdmin)\n","sub_path":"blog/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"508937040","text":"import numpy as np\n\n\ndef first_derivative(xf_d, yf_d):\n h = xf_d[1] - xf_d[0]\n f = [(yf_d[1] - yf_d[0]) / h]\n for i in range(1, len(xf_d) - 1):\n f.append(float(((yf_d[i + 1] - yf_d[i - 1]) / 2) / h))\n f.append((yf_d[len(xf_d) - 1] - yf_d[len(xf_d) - 2]) / h)\n return f\n\n\ndef second_derivative(xs_d, ys_d):\n h = xs_d[1] - xs_d[0]\n first_der = first_derivative(xs_d, ys_d)\n f = [(ys_d[1] - ys_d[0]) / h]\n for i in range(1, len(xs_d) - 1):\n f.append((first_der[i + 1] - first_der[i - 1]) / 2 / h)\n f.append((first_der[len(xs_d) - 1] - first_der[len(xs_d) - 2]) / h)\n return f\n\n\ndef spline(x_s, y_s):\n h = []\n a = []\n b = []\n c = []\n d = []\n result = []\n answer = []\n temp = []\n temp_row = []\n matrix = []\n matrix_row = []\n for i in range(0, len(x_s) - 1):\n h.append(x_s[i + 1] - x_s[i])\n a.append(y_s[i])\n c.append(1)\n c[0] = 0\n c.append(0)\n for i in range(0, len(x_s) - 2):\n matrix_row.clear()\n for j in range(0, len(x_s) - 2):\n matrix_row.append(0)\n matrix.append(list(matrix_row))\n for i in range(0, len(x_s) - 2):\n answer.append(0)\n temp_row.clear()\n for j in range(0, len(x_s)):\n temp_row.append(0)\n temp.append(list(temp_row))\n for i in range(0, len(x_s) - 2):\n temp[i][i] = h[i] * c[i]\n temp[i][i + 1] = 4 * h[i] * c[i + 1]\n temp[i][i + 2] = h[i] * c[i + 2]\n for i in range(0, len(x_s) - 2):\n for j in range(0, len(x_s) - 2):\n matrix[i][j] = temp[i][j + 1]\n for i in range(0, len(x_s) - 2):\n answer[i] = 3 * (y[i + 2] - 2 * y[i + 1] + y[i]) / h[i]\n temp_c = np.linalg.solve(matrix, answer) # Решение системы уравнений с помощью готовой библиотеки NumPy\n for i in range(0, len(x_s) - 2):\n c[i + 1] = temp_c[i]\n for i in range(0, len(x_s) - 2):\n delta = y[i + 1] - y[i]\n b.append((delta / h[i]) - ((2 * c[i] + c[i + 1]) * h[i] / 3))\n d.append((c[i + 1] - c[i]) / 3 / h[i])\n d.append(-c[len(x_s) - 2] / (3 * h[len(x_s) - 2]))\n b.append((y[len(x_s) - 1] - y[len(x_s) - 2]) / h[len(x_s) - 2] - (c[len(x_s) - 2] / 3 * h[len(x_s) - 2] * 2))\n for i in range(0, len(x_s) - 1):\n result.append(str(a[i]) + '+' +\n str(b[i]) + \"(x-\" +\n str(x[i]) + \")+\" +\n str(c[i]) + \"(x-\" +\n str(x[i]) + \")^2+\" +\n str(d[i]) + \"(x-\" +\n str(x[i]) + \")^3\")\n return result\n\n\ncheck = True\nprint(\"\\nВведите массив чисел х через пробел: \\n\")\nx = list(map(int, input().split()))\nwhile check:\n print(\"\\nВведите массив чисел y(y = x) через пробел: \\n\")\n y = list(map(int, input().split()))\n if len(y) == len(x):\n check = False\n else:\n print(\"\\nx != y, введите\", len(x), \"значений y!\\n\")\nprint(\"xi:\", *x, \"yi:\", *y,)\nflag = True\nwhile flag:\n print(\"Выберите метод:\\n1 - Кубический сплайн\\n2 - Первая производная\\n3 - Вторая производная\")\n selector = int(input())\n if selector == 1:\n result = spline(x, y)\n for i in range(0, len(result)):\n print(result[i], x[i], \"<=x<=\", x[i + 1], end='\\n\\n')\n elif selector == 2:\n result = first_derivative(x, y)\n print(\"f'(x) =\", *result)\n elif selector == 3:\n result = second_derivative(x, y)\n print(\"f''(x) =\", *result)\n elif selector == 0:\n flag = False\n","sub_path":"3rd semester/computational mathematics/interpolation.py","file_name":"interpolation.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"194963809","text":"\"\"\"Cloud Foundry test\"\"\"\r\nfrom typing import Any, Union\r\n\r\nfrom flask import Flask, render_template, request, send_from_directory\r\nimport sqlite3\r\nimport os\r\nimport random\r\nimport time\r\nimport array as arr\r\nimport io\r\n\r\napp = Flask(__name__)\r\n\r\n# print(os.getenv(\"PORT\"))\r\nport = int(os.getenv('VCAP_APP_PORT', '8080'))\r\n\r\n\r\n@app.route('/')\r\ndef home():\r\n conn = sqlite3.connect('myDB.db')\r\n print(\"Opened database successfully\")\r\n cur = conn.cursor()\r\n strt = int(round(time.time()*1000))\r\n print(strt)\r\n for x in range(0,1000):\r\n cur.execute(\"SELECT COUNT(*) from quakes WHERE mag = ?\", (random.randint(0,8),))\r\n rows = cur.fetchone()\r\n else:\r\n end = int(round(time.time()*1000))\r\n print(end)\r\n total = end - strt\r\n print(total)\r\n return render_template('testhtml.html',rows=total)\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(host='0.0.0.0', port=port)\r\n","sub_path":"rdm.py","file_name":"rdm.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"127553405","text":"import datetime\n\n\nfrom django.shortcuts import render, redirect\nfrom django.views import View\nfrom django.views.generic.edit import CreateView, UpdateView, DeleteView\nfrom django.views.generic.detail import DetailView\nfrom django.views.generic.list import ListView\nfrom django.template.response import TemplateResponse\nfrom django.http import HttpResponse, HttpResponseRedirect, request\nfrom django.urls import reverse, reverse_lazy\nfrom django.contrib.auth import login, logout, authenticate\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin\n\nfrom smpapp.models import (\n SCHOOL_CLASS,\n Student,\n Teacher,\n SchoolSubject,\n StudentGrades,\n FinalGrades,\n UnpreparedList,\n PresenceList,\n Book,\n)\n\nfrom smpapp.forms import (\n StudentSearchForm,\n StudentGradesForm,\n FinalGradesForm,\n PresenceListForm,\n UnpreparedListForm,\n LoginForm,\n ChangePassForm,\n NewBookForm,\n)\n\n# Create your views here.\n\n\n# Landing Page\nclass LPView(View):\n def get(self, requset):\n return TemplateResponse(requset, 'index.html')\n\n\n''' Teacher Section'''\n\n# Full Teacher View\n\n\nclass TeacherStartView(View):\n def get(self, request):\n return render(request, 'panel_1.html', {'all_class': SCHOOL_CLASS})\n\n\nclass TeacherView(LoginRequiredMixin,View):\n def get(self, request, class_id, subject_id):\n students = Student.objects.filter(school_class=class_id)\n subject = SchoolSubject.objects.get(pk=subject_id)\n grades = StudentGrades.objects.filter(school_subject_id=subject_id)\n finals = FinalGrades.objects.filter(school_subject_id=subject_id)\n unprepared_list = UnpreparedList.objects.filter(school_subject_id=subject_id)\n presence_list = PresenceList.objects.filter(school_subject_id=subject_id,\n day=datetime.date.today()\n )\n\n ctx = {\n 'subject': subject,\n 'students': students,\n 'grades': grades,\n 'finals': finals,\n 'unprepared_list': unprepared_list,\n 'presence_list': presence_list,\n 'class_id': class_id,\n }\n\n return render(request, 'teacher_full.html', ctx)\n\n\nclass TeacherProfieView(UpdateView):\n model = User\n fields = '__all__'\n template_name = 'teacher_profil.html'\n success_url = reverse_lazy('teacher_start')\n\n\nclass StudentSearchView(View):\n\n def get(self, request):\n form = StudentSearchForm()\n return render(request, 'student_search.html', {'form': form})\n\n def post(self, request):\n form = StudentSearchForm(request.POST)\n if form.is_valid():\n name = form.cleaned_data['name']\n students = Student.objects.filter(last_name__icontains=name)\n return render(request, 'student_search.html', {'form': form, 'students': students})\n\n\nclass StudentGradesFormView(View):\n def get(self, request, class_id, subject_id, student_id):\n form = StudentGradesForm()\n stud = Student.objects.get(pk=student_id)\n grades = StudentGrades.objects.filter(\n student_id=student_id,\n school_subject=subject_id\n )\n print(vars(grades))\n ctx = {\n 'grades': grades,\n 'stud': stud,\n 'form': form,\n }\n return render(request, 'teacher_grades.html', ctx)\n\n def post(self, request, class_id, subject_id, student_id):\n form = StudentGradesForm(request.POST)\n if form.is_valid():\n grade = form.cleaned_data['grade']\n evaluation = form.cleaned_data['evaluation']\n grades = StudentGrades.objects.filter(\n student_id=student_id,\n school_subject=subject_id\n )\n\n try:\n sum = float(grade)\n for g in grades:\n sum += int(g.grade)\n avg = round(sum / len(grades), 2)\n except ZeroDivisionError:\n avg = 0\n\n grades = StudentGrades.objects.create(\n school_subject_id=subject_id,\n student_id=student_id,\n grade = float(grade),\n avg = avg,\n evaluation = evaluation,\n )\n\n url = reverse('teacher_class', kwargs={\n 'class_id': class_id,\n 'subject_id': subject_id,\n })\n return HttpResponseRedirect(url)\n\n\nclass FinalGradesFormView(View):\n def get(self, request, class_id, subject_id, student_id):\n\n stud = Student.objects.get(pk=student_id)\n grades = StudentGrades.objects.filter(\n student_id=student_id,\n school_subject=subject_id,\n )\n\n try:\n final_grades = FinalGrades.objects.get(\n student_id=student_id,\n school_subject=subject_id\n )\n except:\n new_grades = FinalGrades.objects.create(\n student_id=student_id,\n school_subject=SchoolSubject.objects.get(pk=subject_id),\n avg1 = 0,\n avg2 = 0,\n half = 1,\n final = 1,\n )\n return HttpResponse('Odśwież')\n\n try:\n sum = 0\n for g in grades:\n sum += int(g.grade)\n avg = round(sum / len(grades), 2)\n except ZeroDivisionError:\n avg = 0\n\n\n form = FinalGradesForm(initial={'half': final_grades.half, 'final': final_grades.final })\n ctx = {\n 'grades': grades,\n 'stud': stud,\n 'avg': avg,\n 'final_grades': final_grades,\n 'form': form,\n }\n return render(request, 'teacher_grades_final.html', ctx)\n\n def post(self, request, class_id, subject_id, student_id):\n form = FinalGradesForm(request.POST)\n if form.is_valid():\n half = form.cleaned_data['half']\n final = form.cleaned_data['final']\n final_grades, new_final_grades = FinalGrades.objects.get_or_create(\n student_id=student_id,\n school_subject=subject_id\n )\n\n\n final_grades.half = half\n final_grades.final = final\n final_grades.save()\n\n\n url = reverse('teacher_class', kwargs={\n 'class_id': class_id,\n 'subject_id': subject_id,\n })\n return HttpResponseRedirect(url)\n\n\nclass PresenceListFormView(View):\n def get(self, request, class_id, subject_id, student_id):\n date = datetime.date.today()\n studs = Student.objects.get(pk=int(student_id))\n print(date)\n form = PresenceListForm(initial={'day': date, 'student': studs})\n return render(request, 'class_presence.html', {\n 'form': form,\n 'student': studs,\n 'day': date\n })\n\n def post(self, request, class_id, subject_id, student_id):\n form = PresenceListForm(request.POST)\n if form.is_valid():\n student = form.cleaned_data['student']\n day = form.cleaned_data['day']\n present = form.cleaned_data['present']\n PresenceList.objects.create(\n student_id=student_id,\n day=day,\n present=present,\n school_subject_id=subject_id,\n )\n url = reverse_lazy('teacher_class', kwargs={\n 'subject_id': subject_id,\n 'class_id': class_id\n })\n return HttpResponseRedirect(url)\n\n\nclass UnpreparedListFormView(CreateView):\n form_class = UnpreparedListForm\n template_name = 'unprepared_form.html'\n success_url = reverse_lazy('teacher_search')\n\n\n''' Student Section'''\n\n\nclass StudentView(View):\n def get(self, request, student_id):\n student = Student.objects.get(pk=student_id)\n grades = StudentGrades.objects.filter(student_id=student_id)\n unprepared_list = UnpreparedList.objects.filter(student_id=student_id)\n\n ctx = {\n 'student': student,\n 'grades': grades,\n 'unprepared_list': unprepared_list,\n }\n return render(request, 'student_full.html', ctx)\n\n\n''' Auth Section '''\n\n\nclass LoginView(View):\n\n def get(self, request):\n form = LoginForm()\n return render(request, 'login.html', {'form': form})\n\n def post(self, request):\n form = LoginForm(request.POST)\n if form.is_valid():\n login2 = form.cleaned_data['login']\n password = form.cleaned_data['password']\n user = authenticate(\n username=login2,\n password=password\n )\n if user is not None:\n login(request, user)\n return HttpResponseRedirect('teacher/search')\n else:\n return HttpResponse('Niepoprawne dane do logowania')\n\n\nclass LogoutView(View):\n def get(self, request):\n logout(request)\n return HttpResponseRedirect(reverse('login'))\n\n\nclass ChangePassView(View):\n\n def get(self, request, user_id):\n form = ChangePassForm()\n return render(request, 'change_pass.html', {'form': form})\n\n def post(self, request, user_id):\n form = ChangePassForm(request.POST)\n if form.is_valid():\n user = User.objects.get(pk=user_id)\n user = authenticate(\n username=user.username,\n password=form.cleaned_data['old_pass']\n )\n if not user.check_password(form.cleaned_data['old_pass']):\n return HttpResponse('Niepoprane aktualne haslo')\n\n if form.cleaned_data['new_pass'] != form.cleaned_data['new_pass_2']:\n return HttpResponse('Nowe hasla nie s takie same')\n\n user.set_password(form.cleaned_data['new_pass'])\n user.save()\n return HttpResponse('Haso zmienione')\n\n\ndef signup(request):\n if request.method == 'POST':\n form = UserCreationForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n raw_password = form.cleaned_data.get('password1')\n user = authenticate(username=username, password=raw_password)\n login(request, user)\n return redirect('teacher_search')\n else:\n form = UserCreationForm()\n return render(request, 'signup.html', {'form': form})\n\n\nclass UserListView(ListView):\n model = User\n template_name = 'user_list.html'\n\n\n''' Library Section '''\n\n\nclass LibraryView(View):\n def get(self, request):\n return TemplateResponse(request, 'library.html')\n\n\nclass NewBookFormView(CreateView):\n form_class = NewBookForm\n template_name = 'book_create_form.html'\n success_url = reverse_lazy('library')\n\n\nclass BookUpdateView(UpdateView):\n model = Book\n template_name = 'book_update_form.html'\n fields = '__all__'\n success_url = reverse_lazy('library')\n\n\nclass BookDeleteView(DeleteView):\n model = Book\n template_name = 'book_form.html'\n success_url = reverse_lazy('library')\n\n\nclass BookDetailView(DetailView):\n model = Book\n template_name = 'book_detail.html'\n\n\n''' Auditorium Section '''\n\nclass RoomsView():\n pass","sub_path":"smpapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"334785913","text":"import os\nimport requests\nimport hashlib\nimport json as js\nfrom mutagen.id3 import ID3, APIC\nfrom mutagen.mp3 import MP3\n\n\ndef kugou_code(code):\n # 这堆东西别瞎改,酷狗特别奇葩,data发的字符串,双引号还不能换成引号\n data2 = {\"appid\": 1001, \"clientver\": 8392, \"mid\": \"b1422385bca909d7ac9aadb285f05541\",\n \"clienttime\": 636307277, \"key\": \"1bb5ba48267c0a4750ecda8d7b10368c\"}\n data = '{\"appid\":1001,\"clientver\":8392,\"mid\":\"b1422385bca909d7ac9aadb285f05541\",\"clienttime\":636307277,\"key\":\"1bb5ba48267c0a4750ecda8d7b10368c\",\"data\":\"' + str(code) + '\"}'\n\n # ----------------第一部分:获取用户信息----------------\n page = requests.post(url=\"http://t.kugou.com/command/\", data=data).text\n # print(page)\n page = eval(page)\n # 复制前面的信息,补充后面的data\n json2 = data2\n json2[\"data\"] = page[\"data\"]['info']\n if json2[\"data\"][\"type\"] == 4: # 歌单酷狗码\n # 删除多余的data信息,以免出事\n del json2['data']['name'], json2['data']['username'], json2['data']['img'], json2['data']['img_size']\n json2['data']['page'] = 1\n json2['data']['pagesize'] = json2['data']['count']\n del json2['data']['count']\n # 这个我也不知道是什么,原版这样填的我就这样写吧\n json2['data']['type'] = 3\n print('共有' + str(json2['data']['pagesize']) + '首歌')\n # 下面的是原版的json,改崩了对照下\n # json2 = '{\"appid\":1001,\"clientver\":8392,\"mid\":\"b1422385bca909d7ac9aadb285f05541\",\"clienttime\":636307277,\"key\":\"1bb5ba48267c0a4750ecda8d7b10368c\",\"data\":{\"id\":8,\"type\":3,\"userid\":\"399348742\",\"collect_type\":0,\"page\":1,\"pagesize\":81}}'\n json2 = str(json2).replace(\"\\'\", \"\\\"\")\n\n # -----------------第二部分:根据用户信息获取歌单-------------------\n json3 = requests.post(\n url='http://www2.kugou.kugou.com/apps/kucodeAndShare/app/', data=json2).text\n json3 = eval(json3)\n song_list = json3['data']\n # 某些多版本的歌曲专辑不同会导致错误\n with open('数据/log.txt', 'a', encoding='utf-8') as log:\n log.write(\"酷狗码列表下载-->\\n\"+str(song_list)+\"\\n\")\n print(1)\n return song_list\n elif json2['data'][\"type\"] == 1: # 单曲酷狗码\n with open('数据/log.txt', 'a', encoding='utf-8') as log:\n log.write(\"酷狗码单曲下载-->\\n\"+str(page)+\"\\n\")\n return page['data']['list']['hash']\n\n\ndef lyrics(json_list):\n if str(json_list).find('纯音乐,请欣赏') != -1:\n print('✔已检测到纯音乐,不需要歌词')\n elif json_list == None or json_list['data']['lyrics'] == '':\n print('❌此歌曲无歌词')\n else:\n with open('音乐/' + json_list['data']['audio_name'] + '.lrc', 'w', encoding='gb18030') as f:\n f.write(\n json_list['data']['lyrics'].replace('\\ufeff', '').replace('\\r', ''))\n print('歌词下载完成')\n\n\nclass kugou_download:\n def __init__(self):\n self.headers = {\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4162.0 Safari/537.36 Edg/85.0.538.0'}\n with open('数据/cookies.txt', 'r') as f:\n cookies_dict = {}\n try:\n cookies1 = f.read()\n cookies_list = cookies1.replace(' ', '').split(';')\n for str1 in cookies_list:\n key, values = str1.split('=', 1)\n cookies_dict[key] = values\n except:\n cookies1 = 'kg_mid=b434c13fcd475da311e141a0cf532557; _WCMID=16477e145e53a4a7e38ece94; kg_dfid=1aJRd418KcGl0dnFZB3ucZDk; Hm_lvt_aedee6983d4cfc62f509129360d6bb3d=1582544353; kg_dfid_collect=d41d8cd98f00b204e9800998ecf8427e'\n cookies_list = cookies1.replace(' ', '').split(';')\n for str1 in cookies_list:\n key, values = str1.split('=', 1)\n cookies_dict[key] = values\n self.cookies = cookies_dict\n\n def download_main(self, song_hash, is_lyrics):\n hash_url = 'https://wwwapi.kugou.com/yy/index.php?r=play/getdata&callback=jQuery19107707606997391536_1606614033664&hash={}'.format(\n song_hash)\n print(\"正在从{}获取歌曲信息\".format(hash_url))\n main_json = js.loads(requests.get(url=hash_url, headers=self.headers,\n cookies=self.cookies).text[41:-2])\n with open('数据/log.txt', 'a', encoding='utf-8') as log:\n log.write(\"信息获取-->\\n\"+str(main_json)+\"\\n\")\n if main_json['status'] == 0:\n os.system(\"start https://www.kugou.com/song/\")\n return \"cookies过期或使用次数过多被封禁或发生其他错误,请稍后再试\\n以下是错误代码:\\n\"+str(main_json)+\"\\n可以尝试在打开的浏览器页面中输入验证码解决\"\n print(main_json['data']['album_id'])\n if main_json['data']['have_album']==0:\n return \"❌由于酷狗官网自身的bug,<{}>无法下载或者在浏览器播放\\n只能在客户端播放(这我也很绝望啊)\\n不信你去试试https://www.kugou.com/song/#hash={}\\n\".format(\n main_json['data']['audio_name'],song_hash)\n album_id = eval(main_json['data']['album_id'])\n hash_url = 'https://wwwapi.kugou.com/yy/index.php?r=play/getdata&callback=jQuery19107707606997391536_1606614033664&hash={}&album_id={}'.format(\n song_hash, album_id)\n main_json = js.loads(requests.get(url=hash_url, headers=self.headers,\n cookies=self.cookies).text[41:-2])\n with open('数据/log.txt', 'a', encoding='utf-8') as log:\n log.write(\"mp3下载-->\\n\"+str(main_json)+\"\\n\")\n # 傻逼文件名的检测替换\n file_name_error = ['\"', '?', '/', '*', ':', '\\\\', '|', '<', '>']\n for file_name in file_name_error:\n if main_json['data']['audio_name'].find(file_name) != -1:\n main_json['data']['audio_name'] = main_json['data']['audio_name'].replace(\n file_name, ' ')\n song_url = main_json['data']['play_url'].replace('\\\\', '')\n print(\"正在从\"+song_url+\"下载\")\n song_name = main_json['data']['audio_name']\n img_url = main_json['data']['img']\n song_length = int(main_json['data']['timelength'])\n song_free = main_json['data']['is_free_part'] # 试听歌曲为1,普通歌曲为0\n if song_url == '': # 检测歌曲是否能下载\n return '❌歌曲<{}>无数据或需要付费下载'.format(song_name)\n else:\n try: # 检测是否存在已下载文件\n notice_file_name = ''\n notice = ''\n if song_free == 1: # 试听歌曲检测\n notice = '⚠歌曲为试听版,请核实'\n notice_file_name = '[试听]'\n with open('音乐/' + notice_file_name + song_name + '.mp3', 'xb') as f: # 检测歌曲是否已经存在,不存在则写入歌曲\n song = requests.get(\n url=song_url, headers=self.headers, cookies=self.cookies)\n f.write(song.content)\n try: # 写入歌曲封面\n mp3file = '音乐/' + notice_file_name + song_name + '.mp3'\n songFile = MP3(mp3file,ID3=ID3)\n try: # 给没有ID3 tag的歌曲加入tag\n songFile.add_tags()\n except:\n pass\n picData = requests.get(\n url=img_url, headers=self.headers, cookies=self.cookies).content\n songFile.tags.add(\n APIC( # 插入封面\n encoding=3,\n mime='image/jpeg',\n type=3,\n desc=u'Cover',\n data=picData\n )\n ) \n songFile.save()\n except:\n print(\"歌曲封面写入失败\")\n song_length_format = \"%02d:%02d\" % (\n int(song_length / 1000) // 60, int(song_length / 1000) % 60)\n\n if is_lyrics:\n lyrics(main_json)\n return '✔歌曲<{}>下载完成\\n歌曲时长{}\\n'.format(song_name, song_length_format) + notice\n except: # 歌曲存在的替换\n return '⚠歌曲<' + song_name + '>已存在'\n\n def download_backup(self, Hash, is_lyrics):\n # V2版系统,pc版,加密方式为md5(hash +\"kgcloudv2\")\n Music_api_1 = 'http://trackercdnbj.kugou.com/i/v2/?cmd=23&pid=1&behavior=download'\n # V2版系统,手机版,加密方式为md5(hash +\"kgcloudv2\") (备用)\n Music_api_2 = 'http://trackercdn.kugou.com/i/v2/?appid=1005&pid=2&cmd=25&behavior=play'\n # 老版系统,加密方式为md5(hash +\"kgcloud\")(备用)\n Music_api_3 = 'http://trackercdn.kugou.com/i/?cmd=4&pid=1&forceDown=0&vip=1'\n v2_key = hashlib.md5((Hash + 'kgcloudv2').encode(\"utf-8\")).hexdigest()\n v1_key = hashlib.md5((Hash + 'kgcloud').encode(\"utf-8\")).hexdigest()\n\n json = requests.get(Music_api_1 + '&hash={}&key={}'.format(Hash,\n v2_key), cookies=self.cookies, headers=self.headers).text\n json = eval(json)\n if json[\"status\"] == 1:\n song_url = json[\"url\"].replace(\"\\\\\\\\/\", '/').replace('\\\\/', '/')\n print(song_url)\n song_name = json[\"fileName\"]\n print(\"正在从\"+song_url+\"下载\")\n # 检测歌曲是否已经存在,不存在则写入歌曲\n with open('音乐/' + song_name + '.mp3', 'xb') as f:\n song = requests.get(\n url=song_url, headers=self.headers, cookies=self.cookies)\n f.write(song.content)\n return '✔歌曲<{}>下载完成'.format(song_name)\n\n def download_name(self, name):\n url_json1 = 'https://songsearch.kugou.com/song_search_v2?callback=jQuery11240770641348037286_1566198223730' \\\n '&keyword={}&page=1&pagesize=30&userid=-1&clientver=&platform=WebFilter&tag=em&filter=2&iscorrection' \\\n '=1&privilege_filter=0&_=1566198223734'.format(name)\n page1 = requests.get(url=url_json1, headers=self.headers).text\n song_json = eval(page1[41:-2])\n with open('数据/log.txt', 'a', encoding='utf-8') as log:\n log.write(\"获取歌曲名称json-->\\n\"+str(song_json))\n return song_json\n","sub_path":"下载组件.py","file_name":"下载组件.py","file_ext":"py","file_size_in_byte":10791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"340380571","text":"import logging\nimport os\nimport re\nimport yaml\n\nfrom cekit.builder import Builder\nfrom cekit.errors import CekitError\n\nlogger = logging.getLogger('cekit')\n\n# Ignore any failure on non-core modules, we will catch it later\n# and suggest a solution\ntry:\n # Squash library\n from docker_squash.squash import Squash\nexcept ImportError:\n pass\n\ntry:\n # Docker Python library, the old one\n from docker.api.client import APIClient as APIClientClass\nexcept ImportError:\n pass\n\ntry:\n # Docker Python library, the new one\n from docker.client import Client as APIClientClass\nexcept ImportError:\n pass\n\nANSI_ESCAPE = re.compile(r'\\x1B\\[[0-?]*[ -/]*[@-~]')\n\n\nclass DockerBuilder(Builder):\n \"\"\"This class wraps docker build command to build and image\"\"\"\n\n def __init__(self, build_engine, target, params=None):\n if not params:\n params = {}\n self._tags = params.get('tags', [])\n self._pull = params.get('pull', False)\n self._base = params.get('base')\n super(DockerBuilder, self).__init__(build_engine, target, params)\n\n # Default Docker daemon connection timeout 10 minutes\n # It needs to be high enough to allow Docker daemon to export the\n # image for squashing.\n try:\n self.timeout = int(os.getenv('DOCKER_TIMEOUT', 600))\n except ValueError:\n raise CekitError(\"Provided timeout value: %s cannot be parsed as integer, exiting.\" %\n os.getenv('DOCKER_TIMEOUT'))\n\n if not self.timeout > 0:\n raise CekitError(\n \"Provided timeout value needs to be greater than zero, currently: %s, exiting.\" % self.timeout)\n\n @staticmethod\n def dependencies():\n deps = {}\n\n deps['python-docker'] = {\n 'library': 'docker',\n 'package': 'python-docker-py',\n 'fedora': {\n 'package': 'python3-docker'}\n }\n\n deps['docker-squash'] = {\n 'library': 'docker_squash',\n 'fedora': {\n 'package': 'python3-docker-squash'\n }\n }\n\n return deps\n\n def build(self, build_args=None):\n self.docker_client = APIClientClass(version=\"1.22\", timeout=self.timeout)\n\n \"\"\"After the source files are generated, the container image can be built.\n We're using Docker to build the image currently.\n \"\"\"\n args = {}\n args['path'] = os.path.join(self.target, 'image')\n args['tag'] = self._tags[0]\n args['pull'] = self._pull\n args['rm'] = True\n\n # Custom tags for the container image\n logger.debug(\"Building image with tags: '%s'\" %\n \"', '\".join(self._tags))\n\n logger.info(\"Building container image...\")\n\n try:\n docker_layer_ids = []\n out = self.docker_client.build(**args)\n build_log = [\"\"]\n for line in out:\n if b'stream' in line:\n line = yaml.safe_load(line)['stream']\n elif b'status' in line:\n line = yaml.safe_load(line)['status']\n elif b'errorDetail' in line:\n line = yaml.safe_load(line)['errorDetail']['message']\n raise CekitError(\"Image build failed: '%s'\" % line)\n\n if line != build_log[-1]:\n # this prevents poluting cekit log with dowloading/extracting msgs\n log_msg = ANSI_ESCAPE.sub('', line).strip()\n for msg in log_msg.split('\\n'):\n logger.info('Docker: %s' % msg)\n build_log.append(line)\n\n if '---> Running in ' in line:\n docker_layer_ids.append(line.split(' ')[-1].strip())\n elif 'Successfully built ' in line:\n docker_layer_ids.append(line.split(' ')[-1].strip())\n elif '---> Using cache' in build_log[-2]:\n docker_layer_ids.append(line.split(' ')[-1].strip())\n\n self.squash_image(docker_layer_ids[-1])\n\n for tag in self._tags[1:]:\n if ':' in tag:\n img_repo, img_tag = tag.split(\":\")\n self.docker_client.tag(self._tags[0], img_repo, tag=img_tag)\n else:\n self.docker_client.tag(self._tags[0], tag)\n logger.info(\"Image built and available under following tags: %s\"\n % \", \".join(self._tags))\n\n except Exception as ex:\n msg = \"Image build failed, see logs above.\"\n if len(docker_layer_ids) >= 2:\n logger.error(\"You can look inside the failed image by running \"\n \"'docker run --rm -ti %s bash'\" % docker_layer_ids[-2])\n if \"To enable Red Hat Subscription Management repositories:\" in ' '.join(build_log) and \\\n not os.path.exists(os.path.join(self.target, 'image', 'repos')):\n msg = \"Image build failed with a yum error and you don't \" \\\n \"have any yum repository configured, please check \" \\\n \"your image/module descriptor for proper repository \" \\\n \" definitions.\"\n raise CekitError(msg, ex)\n\n def squash_image(self, layer_id):\n logger.info(\"Squashing image %s...\" % (layer_id))\n # XXX: currently, cleanup throws a 409 error from the docker daemon. this needs to be investigated in docker_squash\n squash = Squash(docker=self.docker_client, log=logger, from_layer=self._base, image=layer_id,\n tag=self._tags[0],\n cleanup=False)\n squash.run()\n","sub_path":"cekit/builders/docker_builder.py","file_name":"docker_builder.py","file_ext":"py","file_size_in_byte":5754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"586048267","text":"'''\nThis problem was asked by Facebook.\n\nGiven a string of parentheses, find the balanced string that can be produced from it using the minimum number of insertions and deletions. If there are multiple solutions, return any of them.\n\nFor example, given \"(()\", you could return \"(())\". Given \"))()(\", you could return \"()()()()\n\n'''\n\nif __name__ == \"__main__\":\n string = [i for i in input()]\n stack = []\n ans = []\n for i in range(len(string)):\n if string[i] == ')' and len(stack) == 0:\n ans.append('(')\n ans.append(')')\n elif string[i] == '(':\n ans.append('(')\n stack.append('(')\n else:\n ans.append(')')\n stack.pop(-1)\n\n for i in range(len(stack)):\n ans.append(')') \n\n print(''.join(ans))\n\n\n","sub_path":"Problem#430.py","file_name":"Problem#430.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"420090945","text":"import os\nfrom setuptools import setup\n\nrequirements_file = os.path.join(os.curdir, 'requirements.txt')\n\nwith open(requirements_file, 'r') as fh: \n requirements = [line for line in fh.read().splitlines() if line]\n\nsetup(\n name='flpd_helper',\n version='0.1.3',\n install_requires=requirements,\n description='An idiomatic package for manipulating the MongoDB in https://github.com/dm-wyncode/docker-mongo-flpd-hackathon-data.',\n url='git@github.com:dm-wyncode/flpd_helper.git',\n author='Don Morehouse',\n author_email='dm.wyncode@gmail.com',\n license='MIT',\n packages=['flpd_helper', ],\n zip_safe=False,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"8"} +{"seq_id":"594668269","text":"from scipy.stats import poisson,skellam\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nimport requests as rs\nsns.set_style(style=\"darkgrid\")\nimport random\nimport argparse\n## Get stats (Goals/Goals Against/Points)\n\nparser = argparse.ArgumentParser(description = \"This is a parser\")\nparser.add_argument(\"liga\", help = \"Enter League here!\")\nparser.add_argument(\"season\", help = \"Enter season here!\")\nargs = parser.parse_args()\n\nliga = args.liga\nseason = args.season\n\ndef get_goals():\n ##Import matches from OpenLigaDB\n url = \"https://www.openligadb.de/api/getmatchdata/{0}/{1}\".format(liga, season)\n games = rs.get(url).content\n\n import json\n games=json.loads(games)\n \n #Define variables\n home_team=[]\n away_team=[]\n home_goals=[]\n away_goals=[]\n home_points=[]\n away_points=[]\n\n #Loops trough each games and gets Teams and Scores\n for each in games:\n home_team.append(each[\"Team1\"][\"TeamName\"])\n away_team.append(each[\"Team2\"][\"TeamName\"])\n try:\n home_goals.append(each[\"MatchResults\"][1][\"PointsTeam1\"])\n away_goals.append(each[\"MatchResults\"][1][\"PointsTeam2\"])\n except:\n home_goals.append(None)\n away_goals.append(None)\n try:\n if each[\"MatchResults\"][1][\"PointsTeam1\"]>each[\"MatchResults\"][1][\"PointsTeam2\"]:\n home_points.append(3)\n away_points.append(0)\n elif each[\"MatchResults\"][1][\"PointsTeam1\"]step:\n prob=a[i]\n step=step+prob\n i=i+1\n \n score_home=i\n \n step=b[0]\n i=0\n \n while random1>step:\n prob=b[i]\n step=step+prob\n i=i+1\n \n score_away=i\n \n return score_home, score_away\n ##return score_home, score_away\n\ndef upcoming_games(data):\n home_team=[]\n away_team=[]\n\n for each in data:\n if each[\"MatchIsFinished\"]==False:\n home_team.append(each[\"Team1\"][\"TeamName\"])\n away_team.append(each[\"Team2\"][\"TeamName\"])\n\n games={\"Home Team\":home_team,\"Away Team\":away_team} \n \n return games\n\ndef play_shedule(shedule, home_stats, away_stats, avg_home, avg_away):\n #Calculate number of games\n number_games=len(shedule[\"Away Team\"])\n \n home_score=[]\n away_score=[]\n \n for each in range(0,number_games):\n score_home, score_away=predict_match(shedule[\"Home Team\"][each],shedule[\"Away Team\"][each],home_stats, away_stats, avg_home, avg_away) \n home_score.append(score_home)\n away_score.append(score_away)\n \n dic = {\"Home Team\":shedule[\"Home Team\"], \"Away Team\": shedule[\"Away Team\"],\"Home Goals\": home_score, \"Away Goals\": away_score}\n df=pd.DataFrame(dic)\n \n return df\n\ndef create_table(played, results):\n home_points=[]\n away_points=[]\n \n def points(each):\n if each[\"Home Goals\"]>each[\"Away Goals\"]:\n home_points.append(3)\n away_points.append(0)\n elif each[\"Home Goals\"] NOW() - INTERVAL 1 MONTH ORDER BY `added` ASC;\"\n chart_db = _mysql.connect(host=db_creds.db_creds['host'], user=db_creds.db_creds['user'], passwd=db_creds.db_creds['passwd'], db=db_creds.db_creds['db'])\n chart_db.query(fetch_data_query)\n chart_db_result = chart_db.store_result().fetch_row(how=1, maxrows=0)\n chart_db = None\n\n return chart_db_result\n\n except Exception:\n return None\n\n\n@app.route('/')\ndef index(search_string=None, emoji=False):\n\n if request.headers['Host']:\n if request.headers['Host'] == 'xn--h78h.ericoc.com' or request.headers['Host'] == 'xn--h78h.ericoc.com.':\n emoji = True\n\n return render_template('index.html.j2', indego_stations=find_stations(search_string), emoji=emoji)\n\n@app.route('/search/')\ndef search_stations(search_string=None):\n return index(search_string=search_string)\n\n@app.route('/search')\ndef search_form():\n return redirect(url_for('search_stations', search_string=request.args.get('search')))\n\n@app.route('/chart/')\ndef chart_station(chart_string=None):\n\n chart_results = find_stations(chart_string)\n\n if chart_results:\n chart_stations = list(chart_results.values())\n code = 200\n else:\n chart_stations = None\n code = 404\n\n return render_template('chart.html.j2', chart_stations=chart_stations, chart_string=chart_string), code\n\n\n@app.route('/chartjs/')\ndef chartjs_station(chartjs_id=None):\n\n chartjs_results = find_stations(chartjs_id)\n\n if chartjs_results:\n chartjs_stations = list(chartjs_results.values())\n code = 200\n else:\n chartjs_stations = None\n code = 404\n\n chartjs_template = render_template('chart.js.j2', chartjs_stations=chartjs_stations), code\n chartjs_response = make_response(chartjs_template)\n chartjs_response.headers['Content-Type'] = 'text/javascript'\n return chartjs_response\n\n\n@app.route('/chartdata/')\ndef chartdata_station(chartdata_id=None):\n\n chartdata_result = find_stations(chartdata_id)\n chartdata_station = list(chartdata_result.values())\n chart_data = fetch_chart_data(chartdata_id)\n\n if chart_data and len(chart_data) > 1:\n code = 200\n else:\n chartdata_station = None\n chart_data = None\n code = 404\n\n chartdata_template = render_template('chartdata.js.j2', chartdata_station=chartdata_station, chart_data=chart_data), code\n chartdata_response = make_response(chartdata_template)\n chartdata_response.headers['Content-Type'] = 'text/javascript'\n return chartdata_response\n\n\n@app.route('/favicon.ico')\n@app.route('/icon.png')\ndef static_from_root():\n return send_from_directory(app.static_folder, request.path[1:])\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"329287634","text":"# -*- coding: utf-8 -*-\r\n\r\nimport requests\r\nimport bs4\r\nfrom bs4 import BeautifulSoup\r\nimport os\r\nimport sys\r\nimport wget\r\nfrom pydub import AudioSegment\r\nimport time\r\nimport string\r\nfrom zhon import hanzi\r\n\r\n\r\ndef language_selection():\r\n\tmain_page = 'https://www.sbs.com.au/radio/yourlanguage_podcasts'\r\n\tr = requests.get(url=main_page)\r\n\tsoup = BeautifulSoup(r.text, 'html.parser')\r\n\tlanguage_list = soup.find_all('div', class_=\"field field-name-field-list-url field-type-link-field field-label-hidden\")\r\n\tlinks = {i.a.string.lower(): i.a['href'] for i in language_list}\r\n\tunsupported_list = ['assyrian','croatian','hebrew','lao','living black','punjabi','portuguese']\r\n\twhile True:\r\n\t\ttry:\r\n\t\t\t#l = 'mandarin'\r\n\t\t\tl = input('Please select your language: ').lower()\r\n\t\t\tif l in unsupported_list:\r\n\t\t\t\traise KeyError\r\n\t\t\tchoice = links[l]\r\n\t\t\tbreak\r\n\t\texcept KeyError:\r\n\t\t\tprint('Sorry, the language you entered is currently not supported. Please try another one.')\r\n\tif l == 'spanish' or l == 'tigrinya':\r\n\t\treturn choice\r\n\tr = requests.get(url=choice)\r\n\tsoup = BeautifulSoup(r.text, 'html.parser')\r\n\tfor i in soup.find_all('a', class_=\"language-toggle\"):\r\n\t\tif i.string != 'English':\r\n\t\t\treturn 'https://www.sbs.com.au' + i['href']\r\n\r\n\r\ndef find_all_resources(link, max_pages=10):\r\n\tresources = []\r\n\tpages = max_pages\r\n\tcurrent_link = link\r\n\twhile pages != 0:\r\n\t\tpages -= 1\r\n\t\tr = requests.get(url=current_link)\r\n\t\tsoup = BeautifulSoup(r.text, 'html.parser')\r\n\t\t# get all resource links on current page\r\n\t\tfor i in soup.find_all('div', class_='audio__player-info'):\r\n\t\t\tresources.append(i.div.next_sibling.next_sibling.a['href'])\r\n\t\tif pages != 0:\r\n\t\t\tcurrent_link = 'https://www.sbs.com.au' + soup.find('li', class_='pager-next').a['href']\r\n\treturn resources\r\n\r\n\r\ndef is_string(x):\r\n\treturn type(x) is bs4.element.NavigableString\r\n\r\n\r\ndef time_is_shorter_than(time, max_time):\r\n\tt1 = time.split()\r\n\t# if longer than 1 hour or less than 1 minute, exclude it\r\n\tif len(t1) != 4:\r\n\t\treturn False\r\n\tt2 = max_time.split()\r\n\tif int(t1[0]) < int(t2[0]):\r\n\t\treturn True\r\n\telif int(t1[0]) == int(t2[0]):\r\n\t\tif int(t1[2]) <= int(t2[2]):\r\n\t\t\treturn True\r\n\treturn False\r\n\r\n\r\ndef text_is_longer_than(length, min_text):\r\n\treturn length >= min_text\r\n\r\n\r\ndef filtering(time, length, max_time='8 min 0 sec', min_text=100):\r\n\treturn time_is_shorter_than(time, max_time) and text_is_longer_than(length, min_text)\r\n\r\n\r\ndef scrapper(link, index, max_time, min_length):\r\n\tr = requests.get(url=link)\r\n\tsoup = BeautifulSoup(r.text, 'html.parser')\r\n\tt = soup.find('div', class_='ds-1col')\r\n\t# if resource is not find, return directly\r\n\tif type(t) == type(None):\r\n\t\treturn\r\n\taudio = t.find('source')['src']\r\n\tdes = t.find('div', itemprop='description', recursive=False)\r\n\ttext = ''\r\n\tfor i in des.find_all('p'):\r\n\t\ttry:\r\n\t\t\ttext += i.string\r\n\t\texcept TypeError:\r\n\t\t\tpass\r\n\tif type(text) == type(None):\r\n\t\ttext = ''\r\n\tpara = t.find('div', class_='field-type-text-with-summary', recursive=False)\r\n\t# determine if the news contains summary paragraphs\r\n\tif type(para) is not type(None):\r\n\t\ts = ''\r\n\t\tfor i in para.div.div.find_all('p', recursive=False):\r\n\t\t\t# not an empty paragraph\r\n\t\t\tif len(i.contents) is not 0:\r\n\t\t\t\t# is the string that contains contents wanted\r\n\t\t\t\tif is_string(i.contents[0]):\r\n\t\t\t\t\ts += i.contents[0].string\r\n\t\ttext += s\r\n\t# remove punctuations and numbers\r\n\teliminate_set = string.punctuation + string.digits + hanzi.punctuation\r\n\treplace_set = ' ' * len(eliminate_set)\r\n\ttrans_tab = str.maketrans(eliminate_set, replace_set)\r\n\ttext = text.translate(trans_tab).upper()\r\n\t'''\r\n\t# get number of words and audio length\r\n\tinfo = {}\r\n\tinfo['words'] = word_counter(text)\r\n\taudio_length = str(t.find('div', class_='field-name-field-duration').contents[1])\r\n\ttime = audio_length.split()\r\n\t# audio is longer than an hour\r\n\tif len(time) > 4:\r\n\t\tinfo['hours'] = 1\r\n\t# audio is less than an hour\r\n\telse:\r\n\t\tinfo['hours'] = 0\r\n\t\tif len(time) < 4:\r\n\t\t\t# audio is less than one minute\r\n\t\t\tif time[-1] == 'sec':\r\n\t\t\t\tinfo['minutes'] = 0\r\n\t\t\t\tinfo['seconds'] = int(time[0])\r\n\t\t\t# audio is longer than one minute but has no second value\r\n\t\t\telse:\r\n\t\t\t\tinfo['minutes'] = int(time[0])\r\n\t\t\t\tinfo['seconds'] = 0\r\n\t\t# audio has both minute and second values\r\n\t\telse:\r\n\t\t\tinfo['minutes'] = int(time[0])\r\n\t\t\tinfo['seconds'] = int(time[2])\r\n\treturn info\r\n\t'''\r\n\t\r\n\t# filtering\r\n\taudio_length = str(t.find('div', class_='field-name-field-duration').contents[1])\r\n\ttext_length = len(text)\r\n\tif not max_time == None:\r\n\t\tif not filtering(audio_length, text_length, max_time=max_time, min_text=min_length):\r\n\t\t\treturn\r\n\t\r\n\t# current path where the program runs\r\n\tpath = os.path.split(os.path.realpath(__file__))[0]\r\n\t# if used for the first time, create a folder for all resources\r\n\tif not os.path.isdir(path + '/resources'):\t\r\n\t\tos.makedirs(path + '/resources')\r\n\tpath += '/resources'\r\n\t# create a folder for current language if the folder never exists\r\n\tlanguage = link.split('/')[-4]\r\n\tif not os.path.isdir(path + '/' + language):\r\n\t\tos.makedirs(path + '/' + language)\r\n\tpath = path + '/' + language\r\n\t# get text\r\n\twith open(path + '/' + f'{str(index)}.lab', 'w', encoding='utf-8') as f:\r\n\t\tf.write(text)\r\n\t# get audio\r\n\twget.download(audio, out=path + '/' + f'{str(index)}.mp3')\r\n\t# format transformation\r\n\tori = AudioSegment.from_file(path + '/' + f'{str(index)}.mp3', format='mp3')\r\n\tori = ori.set_frame_rate(44100)\r\n\tori.export(path + '/' + f'{str(index)}.wav', format='wav')\r\n\t# delete the original audio\r\n\tos.remove(path + '/' + f'{str(index)}.mp3')\r\n\r\n\r\ndef word_counter(text):\r\n\treturn len(text.split())\r\n\t\r\n\t\t\r\nif __name__ == '__main__':\r\n\t\r\n\tlink = language_selection()\r\n\tresources = find_all_resources(link)\r\n\tmax_time = None\r\n\tmin_length = None\r\n\tchoice = input('Do you want to apply filtering? (Y/N)\t\t')\r\n\tif choice.upper() == 'Y':\r\n\t\tmax_time = input('Please input the maximum duration for the audio (e.g. 8 min 30 sec): \t\t')\r\n\t\tmin_length = int(input('Please input the minimum length for the text:\t\t'))\r\n\tindex = 0\r\n\tfor item in resources[: 5]:\r\n\t\tindex += 1 \r\n\t\tscrapper('https://www.sbs.com.au' + item, index, max_time, min_length)\r\n\t\r\n\t'''\r\n\tinfo = {}\r\n\tinfo['words'] = 0\r\n\tinfo['hours'] = 0\r\n\tinfo['minutes'] = 0\r\n\tinfo['seconds'] = 0\r\n\tindex = 0\r\n\tfor item in resources:\r\n\t\tindex += 1\r\n\t\ts = scrapper('https://www.sbs.com.au' + item, index)\r\n\t\tinfo['words'] += s['words']\r\n\t\tinfo['hours'] += s['hours']\r\n\t\tinfo['minutes'] += s['minutes']\r\n\t\tinfo['seconds'] += s['seconds']\r\n\tprint(info)\r\n\t''' \r\n","sub_path":"Crawler/SBS/Crawler_SBS.py","file_name":"Crawler_SBS.py","file_ext":"py","file_size_in_byte":6486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"}
    ИКСС
    Пакет Primary Packet Header Идентификатор сегмента упакованных данных